在我的GUI中的actionListener中按下按钮时图像无法打开?

时间:2013-03-17 14:52:30

标签: java image swing jbutton actionlistener

我正在尝试按下PlaySci按钮时打开图像,所以我将图像放在PlaySci动作监听器中,但是只有在按下退出按钮时它才会打开?

我已经看了几个小时但仍然不明白为什么,我试图完全摆脱退出按钮但是图像根本没有显示。

我将图片放在顶部的JLabel

ImageIcon scis1 = new ImageIcon("scis.jpg");

private JLabel picture = new JLabel(scis1);

以下是我的PlaySci按钮ActonListener的代码:

class PlaySciHandler implements ActionListener {
    public void actionPerformed(ActionEvent event) {

        String computerRand = sps.computerChoice();
        txtComputerRand.setText(computerRand);
        String result = sps.play(Sps.SCISSORS);
        txtResult.setText(result);
        picture.setBounds(60, 200, 400, 400);// this is the image I want displayed when the PlaySci button is pressed
        panel.add(picture);
    }
}

这是退出按钮ActionListener(由于某种原因,它是显示图像的唯一方法):

class exitHandler implements ActionListener{
    public void actionPerformed(ActionEvent e) {
        int n = JOptionPane.showConfirmDialog(frame, //when this button is pressed the image comes up?
                "Are you sure you want to exit?", 
                "Exit?", 
                JOptionPane.YES_NO_OPTION);
        if(n == JOptionPane.YES_OPTION){
            System.exit(0);
        }
    }
}

这是创建按钮并添加ActionListener的代码:

                btnPlaySci = new JButton ("Scissors!");
        btnPlaySci.setBounds(180, 40, 110, 20);
        btnPlaySci.addActionListener(new PlaySciHandler());
        panel.add (btnPlaySci);
        btnPlaySci.setForeground(Color.MAGENTA);

任何帮助都将不胜感激。

2 个答案:

答案 0 :(得分:3)

添加图片后,应重新绘制面板。请参阅PlaySciHandler actionPerformed方法的代码。

class PlaySciHandler implements ActionListener {
        public void actionPerformed(ActionEvent event) {

            String computerRand = sps.computerChoice();
            txtComputerRand.setText(computerRand);
            String result = sps.play(Sps.SCISSORS);
            txtResult.setText(result);
            picture.setBounds(60, 200, 400, 400);// this is the image I want displayed when the PlaySci button is pressed
            panel.add(picture);
            panel.repaint();//Must repaint the panel .
        }
    }

注意:作为附注,我建议您永远不要将null Layout用于JPanel。请使用Layouts提供的内置Swing 。您可以在official site获取有关布局使用情况的更多信息。另一个是始终坚持使用java命名约定。类exitHandler应该改为ExitHandler。要了解更多信息,请查看official site

答案 1 :(得分:2)

不要在JLabel区块中添加class PlaySciHandler implements ActionListener。在createForm()方法中添加picture.setVisible(false);并将其隐藏起来:picture.setVisible(true); 如果要在单击按钮后显示,请将其显示为{{1}}