2

我试图在按下 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);

任何帮助,将不胜感激。

4

2 回答 2

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 Layoutfor 。使用 .提供JPanel的内置。您可以在此官方网站上获取有关 Layouts 使用的更多信息。另一个是始终坚持 Java 命名约定。类应该写成。要了解更多信息,请查看这个官方网站LayoutsSwingexitHandlerExitHandler

于 2013-03-17T15:30:34.670 回答
2

不要JLabelclass PlaySciHandler implements ActionListener块中添加。将其添加到您的createForm()方法中并使其不可见:picture.setVisible(false); 当您想在单击按钮后显示时,使其可见:picture.setVisible(true);

于 2013-03-17T15:26:42.620 回答