写了一个FrameWork类实现了菜单栏,并且为菜单栏里的Item添加事件监听,实现了选择文件的功能。
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
public class FrameWork extends JFrame {
private static final int Width = 1000;
private static final int Height = 600;
private static JFrame frame = null;
private static FlowLayout flowLayout = null;
public FrameWork() {
frame = new JFrame("Java菜单栏");
flowLayout = new FlowLayout(FlowLayout.CENTER);
flowLayout.setHgap(20);
flowLayout.setVgap(30);
frame.setLayout(flowLayout);
JMenuBar menuBar = new JMenuBar();
frame.setJMenuBar(menuBar);
JMenu fileMenu = new JMenu("文件");
JMenu openMenu = new JMenu("打开");
JMenuItem openItem = new JMenuItem("文件");
openMenu.add(openItem);
openItem.addActionListener(new MyAction());
fileMenu.add(openMenu);
menuBar.add(fileMenu);
frame.setVisible(true);
frame.setSize(Width, Height);
frame.setLocation(100, 100);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private class MyAction implements ActionListener {
public void actionPerformed(ActionEvent evt) {
Object s = evt.getSource();
JFileChooser jfc=new JFileChooser();
jfc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES );
jfc.showDialog(new JLabel(), "选择");
File file=jfc.getSelectedFile();
if(file.isDirectory()){
System.out.println("文件夹:"+file.getAbsolutePath());
}else if(file.isFile()){
System.out.println("文件:"+file.getAbsolutePath());
}
System.out.println(jfc.getSelectedFile().getName());
}
}
public static void main(String[] args) {
new FrameWork();
}
}
posted on 2015-03-18 12:51
marchalex 阅读(936)
评论(0) 编辑 收藏 所属分类:
java小程序