按下按钮时更改图像 - Java

时间:2014-12-11 12:03:04

标签: java swing user-interface awt

gui有五个按钮和一个默认图像。我希望在按下每个按钮时更改图像。我试过这个粉红色'通过更新路径,但我不知道每次需要做什么。

public class PikminGui extends JFrame{

    private JPanel buttons;
    private JLabel title;
    private JButton grow;
    private JButton pink;
    private JButton black;
    private JButton blue;
    private JButton red;
    private JButton yellow;
    private JFrame f;
    private JLabel label;
    private JPanel panel;
    public String path;

    public PikminGui() {
        createGui();
    }

    public void createGui() {

        path = "path-to-image1";

        f = new JFrame();
        panel = new JPanel(new BorderLayout());
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setLocationRelativeTo(null);
        f.setLocation(200,200);
        f.setVisible(true);

        title = new JLabel("PIKMIN MAKER", JLabel.CENTER);
        panel.add(title,BorderLayout.NORTH);

        grow = new JButton("Grow");
        grow.setBorder(BorderFactory.createRaisedBevelBorder());
        panel.add(grow,BorderLayout.WEST);

        buttons = new JPanel();
        pink = new JButton("Pink");
        pink.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e)
            {
                path = "path-to-image2";
            }
        });
        black = new JButton("Black");
        yellow = new JButton("Yellow");
        blue = new JButton("Blue");
        red = new JButton("Red");
        buttons.setLayout(new FlowLayout());
        buttons.add(pink);
        buttons.add(black);
        buttons.add(yellow);
        buttons.add(blue);
        buttons.add(red);
        panel.add(buttons,BorderLayout.SOUTH);

        File file = new File(path);
        BufferedImage image;

        try {
            image = ImageIO.read(file);
            label = new JLabel(new ImageIcon(image));
            panel.add(label, BorderLayout.CENTER );
            f.getContentPane().add(panel);  
            f.pack();
            f.add(panel);           
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

0 个答案:

没有答案