大家好,我的目的是想做一个可以在JPanel里通过点击按钮激活文件对话框来打开图片文件的一个小程序,但是有个异常,请麻烦各位看下:import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;class BackgroundPanel extends JPanel implements ActionListener {
ImageIcon icon;
JButton b1;
JFileChooser fileChooser = null;
String str = null;
Graphics g = getGraphics();
public BackgroundPanel() {
b1 = new JButton("打开文件");
b1.addActionListener(this);
this.add(b1); fileChooser = new JFileChooser("E:\\");
}
public void actionPerformed(ActionEvent e)
{
File file = null;
int result; if (e.getActionCommand().equals("打开文件"))
{
fileChooser.setApproveButtonText("打开吗");
fileChooser.setDialogTitle("确定");
result = fileChooser.showOpenDialog(this); if (result == JFileChooser.APPROVE_OPTION)
{
file = fileChooser.getSelectedFile();
str = file.getName();
icon = new ImageIcon(BackgroundPanel.class.getResource(str));
// this.setPreferredSize(new Dimension(467, 362));
PaintDemo(g);
}
}
}
public void PaintDemo(Graphics g) {
g.drawImage(icon.getImage(), 0, 0, this);
}
}class my extends JFrame {
BackgroundPanel bp;
public my() {
bp = new BackgroundPanel();
this.getContentPane().add(bp);
this.setDefaultCloseOperation(this.EXIT_ON_CLOSE);
this.setSize(500,500);
this.setVisible(true);
}
public static void main(String[] args) {
new my();
}
}
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;class BackgroundPanel extends JPanel implements ActionListener {
ImageIcon icon;
JButton b1;
JFileChooser fileChooser = null;
String str = null;
Graphics g = getGraphics();
public BackgroundPanel() {
b1 = new JButton("打开文件");
b1.addActionListener(this);
this.add(b1); fileChooser = new JFileChooser("E:\\");
}
public void actionPerformed(ActionEvent e)
{
File file = null;
int result; if (e.getActionCommand().equals("打开文件"))
{
fileChooser.setApproveButtonText("打开吗");
fileChooser.setDialogTitle("确定");
result = fileChooser.showOpenDialog(this); if (result == JFileChooser.APPROVE_OPTION)
{
file = fileChooser.getSelectedFile();
str = file.getName();
icon = new ImageIcon(BackgroundPanel.class.getResource(str));
// this.setPreferredSize(new Dimension(467, 362));
PaintDemo(g);
}
}
}
public void PaintDemo(Graphics g) {
g.drawImage(icon.getImage(), 0, 0, this);
}
}class my extends JFrame {
BackgroundPanel bp;
public my() {
bp = new BackgroundPanel();
this.getContentPane().add(bp);
this.setDefaultCloseOperation(this.EXIT_ON_CLOSE);
this.setSize(500,500);
this.setVisible(true);
}
public static void main(String[] args) {
new my();
}
}
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货