我只想尝试在一个面板中打开图像,然后单击另一个面板上的按钮以使该图像消失。
以下只是原始代码的缩短版本,解决了具体问题。
public class NahualProductionTest {
public static void main(String[] args) {
NahualImagesPanel nahualPanel1 = new NahualImagesPanel();
NahualSettingsPanel nahualPanel2 = new NahualSettingsPanel();
JFrame frame = new JFrame();
frame.setLayout(new GridLayout(1,2));
frame.add(nahualPanel1);
frame.add(nahualPanel2);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(900,400);
frame.setLocation(200,200);
frame.setVisible(true);
}
}
public class NahualSettingsPanel extends JPanel {
private JButton button;
private NahualImagesPanel images;
public NahualSettingsPanel(){
images = new NahualImagesPanel();
button = new JButton("Add");
add(button);
button.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
if (e.getSource()==button)
images.setVoid();
}
}
);
}
}
public class NahualImagesPanel extends JPanel{
private BufferedImage tempImage;
private int width, height, x, y;
private double wrate = 0;
private double hrate = 0;
private JButton load;
private PicPanel pics;
public NahualImagesPanel(){
setLayout(new BorderLayout());
pics = new PicPanel();
pics.setBackground(Color.DARK_GRAY);
JPanel commands = new JPanel();
commands.setLayout(new GridLayout(1,1));
load = new JButton("Add Image");
commands.add(load);
add(pics, BorderLayout.CENTER);
add(commands, BorderLayout.SOUTH);
load.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e1){
if (e1.getSource()==load){
try{
JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
chooser.showOpenDialog(null);
tempImage = ImageIO.read(chooser.getSelectedFile());
rescale(tempImage);
repaint();
} catch (IOException exception){
exception.printStackTrace();
System.exit(1);
} catch (IllegalArgumentException iae){}
}
}
}
);
}
public void setVoid(){
tempImage = null; //tempImage is set to null but after repaint() the image is still there
pics.revalidate();
pics.repaint();
}
public void rescale(Image img){
width = tempImage.getWidth();
height = tempImage.getHeight();
if (width>270 || height>250){
if (width-270>height-250){
wrate = (double) (width-270)/width;
width = 270;
height = height - (int) (wrate*height);
x = 10;
y = 15;
}
if (width-270<height-250) {
hrate = (double) (height-250)/height;
height = 250;
width = width - (int) (hrate*width);
x = (300-width)/2;
y = 15;
}
}
}
public class PicPanel extends JPanel{
@Override
public void paintComponent(Graphics g){
super.paintComponent(g);
System.out.println(tempImage);
g.drawImage(tempImage, x, y, width, height, null);
//System.out.println(tempImage);
}
}
}