如何在Java中设计一个按钮,点了之后可以弹出文件选择页面,或者进入某个盘?
若以下回答无法解决问题,邀请你更新回答
1个回答
展开全部
import java.awt.EventQueue;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
/**
*A program for viewing images,
*/
public class ImageViewer {
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
JFrame frame=new ImageViewerFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setResizable(false);
}
});
}
}
/**
* A frame with a label to show an image.
*/
class ImageViewerFrame extends JFrame
{
public ImageViewerFrame()
{
setTitle("ImageViewer");
setSize(DEFAULT_WIDTH,DEFAULE_HEIGHT);
//use a label to display the image
label =new JLabel();
label.setSize(DEFAULT_WIDTH, DEFAULE_HEIGHT);
add(label);
//set up the file chooser
chooser=new JFileChooser();
chooser.setCurrentDirectory(new File("."));
//set up the menu bar
JMenuBar menuBar =new JMenuBar();
setJMenuBar(menuBar);
JMenu menu=new JMenu("File");
menuBar.add(menu);
JMenuItem openItem=new JMenuItem("Open");
menu.add(openItem);
openItem.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
//show file chooser dialog
int result =chooser.showOpenDialog(null);
//if file selected,set it as icon of the label
if(result==JFileChooser.APPROVE_OPTION)
{
String name=chooser.getSelectedFile().getPath();
label.setIcon(new ImageIcon(name));
}
}
});
JMenuItem exitItem=new JMenuItem("Exit");
menu.add(exitItem);
exitItem.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
System.exit(0);
}
});
}
private JLabel label;
private JFileChooser chooser;
private static final int DEFAULT_WIDTH=300;
private static final int DEFAULE_HEIGHT=400;
}
楼主给你个例子看看吧
本回答被提问者采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询