import javaawt;
import javaawtevent;
import javaxswing;
import javatextDateFormat;
import javaxswingevent;
import javaxswingtable;
import javaxswingtree;
import javaxswingfilechooser;
import javaio;
import javautil;
public class WinExplorer extends JFrame implements TreeSelectionListener{
JPanel contentPane=(JPanel)getContentPane();;
JMenuBar menuBar = new JMenuBar();
JMenu menuFile = new JMenu("文件");
JMenuItem menuItemExit = new JMenuItem("退出");
JToolBar toolBar = new JToolBar();
JButton bttUp = new JButton();
Icon iconUp=UIManagergetIcon("FileChooserupFolderIcon");
JLabel statusBar = new JLabel();
DetailTable detailTable = new DetailTable();
JScrollPane sp = new JScrollPane(detailTable);
JSplitPane split = new JSplitPane();
FileSystemView fileSystemView=FileSystemViewgetFileSystemView();
FileNode root=new FileNode(fileSystemViewgetRoots()[0]);
DefaultTreeModel treeModel=new DefaultTreeModel(root);
JTree tree = new JTree(treeModel);
public static void main(String argv[]){
try {
UIManagersetLookAndFeel(UIManagergetSystemLookAndFeelClassName());
Font font=new Font("宋体",FontPLAIN,12);
String names[]={"Label","CheckBox","PopupMenu","TextPane",
"MenuItem","CheckBoxMenuItem","JRadioButtonMenuItem",
"ComboBox","Button","Tree","ScrollPane","TabbedPane",
"EditorPane","TitledBorder","Menu","TextArea","OptionPane",
"MenuBar","ToolBar","ToggleButton","ToolTip","ProgressBar",
"TableHeader","Panel","List","ColorChooser","PasswordField",
"TextField","Table","Label","Viewport","RadioButtonMenuItem",
"RadioButton"};
for(int i=0;i<nameslength;i++)UIManagerput(names[i]+"font",font);
UIManagerput("Labelforeground",Colorblack);
UIManagerput("Borderforeground",Colorblack);
UIManagerput("TitledBordertitleColor",Colorblack);
new WinExplorer()show();
}catch(Exception e){
eprintStackTrace();
}
}
public WinExplorer() {
contentPanesetLayout(new BorderLayout());
Dimension dimension = getToolkit()getScreenSize();
int i = (dimensionwidth - 640) / 2;
int j = (dimensionheight - 480) / 2;
setBounds(i,j,640,480);
setTitle("资源管理器");
setDefaultCloseOperation(JFrameEXIT_ON_CLOSE);
setJMenuBar(menuBar);
statusBarsetText(" ");
menuItemExitaddActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {Systemexit(0);}
});
bttUpsetIcon(iconUp);
bttUpaddActionListener(new javaawteventActionListener() {
public void actionPerformed(ActionEvent e) {
try{
TreePath upPath=treegetSelectionPath()getParentPath();
if(upPath!=null){
treesetSelectionPath(upPath);
treescrollPathToVisible(upPath);
}
}catch(Exception ex){}
}
});
splitsetDividerSize(6);
splitsetLeftComponent(new JScrollPane(tree));
splitsetRightComponent(sp);
splitsetDividerLocation(180);
spgetViewport()setBackground(Colorwhite);
menuFileadd(menuItemExit);
menuBaradd(menuFile);
contentPaneadd(toolBar, BorderLayoutNORTH);
toolBaradd(bttUp, null);
contentPaneadd(statusBar, BorderLayoutSOUTH);
contentPaneadd(split, BorderLayoutCENTER);
treeaddTreeExpansionListener(new MyExpandsionListener());
treesetCellRenderer(new MyTreeCellRenderer());
treeaddTreeSelectionListener(this);
treesetSelectionRow(0);
treesetComponentOrientation(ComponentOrientationUNKNOWN);
}
public void valueChanged(TreeSelectionEvent e){
Object obj=treegetLastSelectedPathComponent();
if(obj==null)return;
else detailTablesetParent(((FileNode)obj)getFile());
}
class MyTreeCellRenderer extends DefaultTreeCellRenderer {
public MyTreeCellRenderer() {}
public Component getTreeCellRendererComponent(JTree tree,Object value,
boolean sel,boolean expanded,boolean leaf,int row,boolean hasFocus) {
supergetTreeCellRendererComponent(tree,value,sel,expanded,leaf,row,hasFocus);
setIcon(fileSystemViewgetSystemIcon(((FileNode)value)getFile()));
return this;
}
}
class MyExpandsionListener implements TreeExpansionListener {
public MyExpandsionListener() {}
public void treeExpanded(TreeExpansionEvent event) {
if(eventgetPath() == null){
return;
}
treesetCursor(new Cursor(CursorWAIT_CURSOR));
TreePath path = eventgetPath();
FileNode node = (FileNode)pathgetLastPathComponent();
nodeexplore();
treeModelnodeStructureChanged(node);
treesetCursor(new Cursor(CursorDEFAULT_CURSOR));
}
public void treeCollapsed(TreeExpansionEvent event) {}
}
class FileNode extends DefaultMutableTreeNode {
private boolean explored = false;
public FileNode(File file) { setUserObject(file); }
public boolean getAllowsChildren() { return isDirectory(); }
public boolean isLeaf() { return !isDirectory();}
public File getFile() { return (File)getUserObject(); }
public boolean isExplored() { return explored; }
public void setExplored(boolean b){ explored=b;}
public boolean isDirectory() { return getFile()isDirectory();}
public String toString() {
File file = (File)getUserObject();
String filename = filetoString();
int index = filenamelastIndexOf(Fileseparator);
return (index != -1 && index != filenamelength()-1)
filenamesubstring(index+1) : filename;
}
public void explore() {
if(!isExplored()) {
File file = getFile();
File[] children = filelistFiles();
if(children==null||childrenlength==0)return;
for(int i=0; i < childrenlength; ++i)
{
File f=children[i];
if(fisDirectory())add(new FileNode(children[i]));
}
explored = true;
}
}
}
class DetailTable extends JTable{
DetailTableModel model=new DetailTableModel();
public DetailTable(){
setModel(model);
setShowGrid(false);
TableColumnModel colModel = getColumnModel();
for (int i=0;i<3;i++)
colModelgetColumn(i)setCellRenderer(new DetailsTableCellRenderer());
setRowHeight(18);
thisaddMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e) {
if(egetClickCount()==2){
for (int i = 0; i <getRowCount(); i++) {
if(getCellRect(i,0,true)contains(egetPoint())){
openSelect();
break;
}
}
}
}
});
}
public void openSelect(){
Object obj=modelgetValueAt(getSelectedRow(),0);
if(obj==null)return;
File f=(File)obj;
if(fisDirectory()){
//expand tree
}else{
//open select file
}
}
public void setParent(File parent){
modelremoveAllRows();
File list[]=parentlistFiles();
if(list==null)return;
Vector vDir=new Vector(),vFile=new Vector();
for (int i = 0; i < listlength; i++) {
if(list[i]isDirectory())vDiradd(list[i]);
else vFileadd(list[i]);
}
sortElements(vFile);
sortElements(vDir);
for (int i = 0; i < vDirsize(); i++)modeladdFile((File)vDirelementAt(i));
for (int i = 0; i < vFilesize(); i++)modeladdFile((File)vFileelementAt(i));
}
public void sortElements(Vector v)
{
for(int i=0;i<vsize();i++)
{
int k=i;
for(int j=i+1;j<vsize();j++){
File fa=(File)velementAt(j);
File fb=(File)velementAt(k);
if(fileSystemViewgetSystemDisplayName(fa)toLowerCase()compareTo(
fileSystemViewgetSystemDisplayName(fb)toLowerCase())<0)k=j;
}
if(k!=i)swap(k,i,v);
}
}
private void swap(int loc1,int loc2,Vector v){
Object tmp=velementAt(loc1);
vsetElementAt(velementAt(loc2),loc1);
vsetElementAt(tmp,loc2);
}
class DetailTableModel extends DefaultTableModel {
public DetailTableModel() {
addColumn("名称");
addColumn("大小");
addColumn("修改时间");
}
public void addFile(File f){
addRow(new Object[]{f,new Double(flength()/1024),
new javasqlDate(flastModified())});
}
public void removeAllRows(){
while(getRowCount()!=0) removeRow(0);
}
public boolean isCellEditable(int row, int column) {return false;}
}
class DetailsTableCellRenderer extends DefaultTableCellRenderer {
DetailsTableCellRenderer() {}
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
if (column == 1){
setHorizontalAlignment(SwingConstantsTRAILING);
isSelected=hasFocus=false;
}else if(column==2){
setHorizontalAlignment(SwingConstantsCENTER);
isSelected=hasFocus=false;
}else setHorizontalAlignment(SwingConstantsLEADING);
return supergetTableCellRendererComponent(
table, value, isSelected, hasFocus, row, column);
}
public void setValue(Object value) {
setIcon(null);
if (value instanceof File) {
File file = (File)value;
setText(fileSystemViewgetSystemDisplayName(file));
setIcon(fileSystemViewgetSystemIcon(file));
}else{
supersetValue(value);
}
}
}
}
}
你双击左面的桌面图标就可以浏览了,别双击字。
给你一个简单的实现吧,注意一定要先运行MyServerjava
//MyCilentjava
import javaio;
import javanet;
import javaxswing;
import javaawt;
import javaawtevent;
public class MyClient extends JFrame implements ActionListener{
JTextField tf;
JTextArea tx;
JButton bt;
PrintWriter out;
public MyClient(){
tf=new JTextField(20);
tx=new JTextArea();
txsetLineWrap(true);
txsetWrapStyleWord(true);
JPanel pan=new JPanel();
JScrollPane jsp=new JScrollPane(tx);
add(jsp,"Center");
bt=new JButton("SEND");
btaddActionListener(this);
panadd(tf);
panadd(bt);
add(pan,"South");
thisaddWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
Systemexit(0);
}
});
setTitle("THE CLIENT");
setSize(400,300);
setVisible(true);
try{
Socket socket=new Socket("127001",1680);
out=new PrintWriter(socketgetOutputStream(),true);
InputStreamReader in = new InputStreamReader(socketgetInputStream());
BufferedReader sin=new BufferedReader(in);
String s;
while(true){
s=sinreadLine();
txappend("#Server Said#: "+s+"\n");
}
}catch(Exception e){
eprintStackTrace();
}
}
public void actionPerformed(ActionEvent e){
if(egetSource()==bt){
txappend("@Client Said@: "+tfgetText()+"\n");
outprintln(tfgetText());
tfsetText("");
}
}
public static void main(String[] args){
MyClient mct = new MyClient();
}
}
//MyServerjava
import javaio;
import javanet;
import javaxswing;
import javaawt;
import javaawtevent;
public class MyServer extends JFrame implements ActionListener{
JTextField tf;
JTextArea tx;
JButton bt;
JScrollPane jsp;
JPanel pan;
PrintWriter out;
public MyServer(){
tx=new JTextArea();
txsetLineWrap(true);
txsetWrapStyleWord(true);
jsp=new JScrollPane(tx);
tf=new JTextField(20);
bt=new JButton("SEND");
btaddActionListener(this);
pan=new JPanel();
panadd(tf);
panadd(bt);
add(pan,"South");
add(jsp,"Center");
thisaddWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
Systemexit(0);
}
});
setTitle("THE SERVER");
setSize(400,300);
setVisible(true);
try{
ServerSocket server = new ServerSocket(1680);
Socket socket = serveraccept();
InputStreamReader in = new InputStreamReader(socketgetInputStream());
BufferedReader sin=new BufferedReader(in);
out=new PrintWriter(socketgetOutputStream(),true);
while(true){
String s=sinreadLine();
txappend("@Client Said@: "+s+"\n");
}
}catch(Exception e){
eprintStackTrace();
}
}
public void actionPerformed(ActionEvent e){
if(egetSource()==bt){
String st = tfgetText();
txappend("#Server Said#: "+st+"\n");
outprintln(st);
tfsetText("");
}
}
public static void main(String[] args){
MyServer msr = new MyServer();
}
}
你放在桌面不好管理。
建议你在D盘建一个文件夹。比如D:/java 把你写的JAVA源文件放在里面。
然后点“开始”--“运行”--输入CMD进入DOS里面。
但是里面默认的是C盘。必须转到D盘中的java文件夹。方法如下:
cd/d d:/java
然后编译:javac HelloWorldjava
如果没错就运行:java HelloWorld
具体代码如下:
import javaxswing;
import javaawtevent;
import javaawt;
public class Calculator extends JFrame implements ActionListener {
private JFrame jf;
private JButton[] allButtons;
private JButton clearButton;
private JTextField jtf;
public Calculator() {
//对图形组件实例化
jf=new JFrame("任静的计算器10:JAVA版");
jfaddWindowListener(new WindowAdapter(){
public void windowClosing(){
Systemexit(0);
}
});
allButtons=new JButton[16];
clearButton=new JButton("清除");
jtf=new JTextField(25);
jtfsetEditable(false);
String str="123+456-7890=/";
for(int i=0;i<allButtonslength;i++){
allButtons[i]=new JButton(strsubstring(i,i+1));
}
}
public void init(){
//完成布局
jfsetLayout(new BorderLayout());
JPanel northPanel=new JPanel();
JPanel centerPanel=new JPanel();
JPanel southPanel=new JPanel();
northPanelsetLayout(new FlowLayout());
centerPanelsetLayout(new GridLayout(4,4));
southPanelsetLayout(new FlowLayout());
northPaneladd(jtf);
for(int i=0;i<16;i++){
centerPaneladd(allButtons[i]);
}
southPaneladd(clearButton);
jfadd(northPanel,BorderLayoutNORTH);
jfadd(centerPanel,BorderLayoutCENTER);
jfadd(southPanel,BorderLayoutSOUTH);
addEventHandler();
}
//添加事件监听
public void addEventHandler(){
jtfaddActionListener(this);
for(int i=0;i<allButtonslength;i++){
allButtons[i]addActionListener(this);
}
clearButtonaddActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
CalculatorthisjtfsetText("");
}
});
}
//事件处理
public void actionPerformed(ActionEvent e) {
//在这里完成事件处理 使计算器可以运行
String action=egetActionCommand();
if(action=="+"||action=="-"||action==""||action=="/"){
}
}
public void setFontAndColor(){
Font f=new Font("宋体",FontBOLD,24);
jtfsetFont(f);
jtfsetBackground(new Color(0x8f,0xa0,0xfb));
for(int i=0;i<16;i++){
allButtons[i]setFont(f);
allButtons[i]setForeground(ColorRED);
}
}
public void showMe(){
init();
setFontAndColor();
jfpack();
jfsetVisible(true);
jfsetDefaultCloseOperation(JFrameEXIT_ON_CLOSE);
}
public static void main(String[] args){
new Calculator()showMe();
}
}
以上就是关于急需一段java小程序全部的内容,包括:急需一段java小程序、如何用java做一个聊天小程序 要求使用图形用户界面,可以实现一个聊天室中多人聊天,也可以两人私聊,、关于 怎样运行JAVA 小程序等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)