import java.awt.Graphics;
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.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.filechooser.FileNameExtensionFilter;
public class DrawBackgroundImage extends JFrame {
private JLabel bgL = new JLabel();
public DrawBackgroundImage() {
setTitle("设置背景图片");
setSize(500, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
JPanel p = new JPanel() {
private static final long serialVersionUID = 1L;
@Override
protected void paintComponent(Graphics g) {
if (bgL.getIcon() != null) {
g.drawImage(((ImageIcon)bgL.getIcon()).getImage(), 0, 0, null);
}
}
};
JButton btn = new JButton("选择背景图片");
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JFileChooser jfc = new JFileChooser();
FileNameExtensionFilter imageExtension = new FileNameExtensionFilter("Image Files (.jpg | .jpeg | .bmp | .png | .gif)", "jpg","jpeg","bmp","png","gif");
jfc.addChoosableFileFilter(imageExtension);
jfc.setDialogType(JFileChooser.SAVE_DIALOG);
int res = jfc.showSaveDialog(DrawBackgroundImage.this);
if (res == JFileChooser.APPROVE_OPTION) {
File file = jfc.getSelectedFile();
System.out.println(file.getAbsolutePath());
setBg(new ImageIcon(file.getAbsolutePath()));
}
}
});
p.add(btn);
this.getContentPane().add(p);
// 添加一些组件,便于查看
String[][] rowData = new String[9][2];
for (int i=0;i<9;i++) {
rowData[i][0] = "值1";
rowData[i][1] = "值2";
}
String[] columnNames = {"列1","列2"};
JTable table =new JTable(rowData, columnNames);
p.add(new JScrollPane(table));
}
public void setBg(ImageIcon icon) {
bgL.setIcon(icon);
repaint();
}
/**
* @param args
*/
public static void main(String[] args) {
new DrawBackgroundImage().setVisible(true);
}
}