使用WindowBuilder打开文件对话框加载图片到JPanel面板中
package gd;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
public class AddJPanelTest {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
AddJPanelTest window = new AddJPanelTest();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public AddJPanelTest() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 547, 503);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(10, 10, 500, 395);
frame.getContentPane().add(scrollPane);
JPanel panel = new JPanel();
scrollPane.setViewportView(panel);
JButton btnNewButton = new JButton("加载");
btnNewButton.setBounds(22, 432, 93, 23);
frame.getContentPane().add(btnNewButton);
label = new JLabel();
panel.add(label);
JButton btnNewButton_1 = new JButton("结束");
btnNewButton_1.setBounds(397, 432, 93, 23);
frame.getContentPane().add(btnNewButton_1);
chooser = new JFileChooser();
chooser.setCurrentDirectory(new File("."));
btnNewButton.addActionListener(new ActionListener()
{@
Override
public void actionPerformed(ActionEvent arg0)
{
// TODO Auto-generated method stub
int result = chooser.showOpenDialog(null);
if(result == JFileChooser.APPROVE_OPTION)
{
String name = chooser.getSelectedFile().getPath();
label.setIcon(new ImageIcon(name));
}
}
});
btnNewButton_1.addActionListener(new ActionListener()
{@
Override
public void actionPerformed(ActionEvent arg0)
{
// TODO Auto-generated method stub
System.exit(0);
}
});
}
private JLabel label;
private JFileChooser chooser;
}
运行结果如图所示