我正在编写一个程序,用户可以从中选择3个不同的按钮,根据他们选择的按钮,会出现不同的图像(或者在这种情况下为gif)。我将程序拆分为3个类:GUI Window类,GUI类和Color Panel类。问题是单击按钮时无法加载图像。
/******************************GUIWindow*******************************/
import javax.swing.*;
public class GUIWindow
{
public static void main(String[] args)
{
GUI theGUI = new GUI();
theGUI.setTitle("Merry Christmas!");
theGUI.setSize(500, 600);
theGUI.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
theGUI.setVisible(true);
}
}
/******************************GUI*******************************/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class GUI extends JFrame
{
private ImageIcon cat1 = new ImageIcon("cat1.gif");
private ImageIcon cat2 = new ImageIcon("cat2.gif");
private JButton cat1Button = new JButton("1");
private JButton cat2Button = new JButton("2");
private JButton cat3Button = new JButton("3");
public GUI()
{
JPanel buttonPanel = new JPanel();
buttonPanel.add(cat1Button);
buttonPanel.add(cat2Button);
buttonPanel.add(cat3Button);
Container container = getContentPane();
container.add(buttonPanel, BorderLayout.NORTH);
cat1Button.addActionListener(new cat1Listener());
cat2Button.addActionListener(new cat2Listener());
}
private class cat1Listener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
ColorPanel panel = new ColorPanel(Color.white, cat1);
Container pane = getContentPane();
pane.add(panel);
}
}
private class cat2Listener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
ColorPanel panel = new ColorPanel(Color.white, cat2);
Container pane = getContentPane();
pane.add(panel);
}
}
}
/******************************ColorPanel*******************************/
import java.awt.*;
import javax.swing.*;
public class ColorPanel extends JPanel
{
private ImageIcon image;
public ColorPanel(Color backColor, ImageIcon i)
{
setBackground(backColor);
image = i;
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
int x = (getWidth() - image.getIconWidth()) / 2;
int y = (getHeight() - image.getIconHeight()) / 2;
image.paintIcon(this, g, x, y);
}
}