0

单击按钮后,我试图在我的框架内打开图像,到目前为止,我已将图像放在按钮内的 JLabel 中,我希望它在单击后打开。但它立即显示出来。关于如何设置它以便在单击“剪刀”按钮后打开图像的任何想法?

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

    //below is my image, and above is the button I want it to open to

    ImageIcon rock1 = new ImageIcon("rock.jpg");
    JLabel picture = new JLabel(rock1);
    picture.setBounds(60, 200, 400, 400);
    panel.add(picture);

编辑后的代码粘贴在评论中

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); 
            ImageIcon rock1 = new ImageIcon("rock.jpg"); 
            JLabel picture = new JLabel(rock1); 
            picture.setBounds(60, 200, 400, 400); panel.add(picture); 
        }
    }
4

1 回答 1

1

我认为您想在单击按钮时将 JLabel(包含图像)添加到面板中。

您必须编写下面的类,当用户单击按钮“btnPlaySci”时该类将处理该事件。

btnPlaySci.addActionListener(new PlaySciHandler(panel)); //replace your addActionListener line with this code.

import java.awt.event.*;
class PlaySciHandler implements ActionListener 
{
    JPanel panel;
    PlaySciHandler(JPanel p)
    {
         panel = p;
    }
    public void actionPerformed(ActionEvent ae)   
    {
      ImageIcon rock1 = new ImageIcon("rock.jpg");
      JLabel picture = new JLabel(rock1);
      picture.setBounds(60, 200, 400, 400);
      panel.add(picture);   
    } 
}
于 2013-03-16T17:59:23.320 回答