日期:2014-05-20 浏览次数:21176 次
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JToolBar;
public class TestAction extends JFrame implements ActionListener {
JToolBar tool;
JButton open;
JLabel img1;
public TestAction(){
super("Test");
open=new JButton("Open");
tool=new JToolBar();
tool.add(open);
add(tool,BorderLayout.NORTH);//把工具栏放上面
img1 = new JLabel();
add(img1,BorderLayout.CENTER);//把标签放在下面
open.addActionListener(this);
pack();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
/*显示文件选择框,读取一张图片*/
JFileChooser fc=new JFileChooser();
int i=fc.showOpenDialog(this);
if(i==JFileChooser.APPROVE_OPTION){
File file=fc.getSelectedFile();
String URL=file.getPath();
ImageIcon image = new ImageIcon(URL);
img1.setIcon(image);
pack();
}
}
public static void main(String args[]){
new TestAction();
}
}
------解决方案--------------------
若果这是你的全部代码的话 代码本身就有问题。还有,为什么非要用Label去显示图片呢?
弟二个问题 你可以使用FileDialog来打开想要的文件。