我想在用户点击GUI中的按钮时打开图像

时间:2013-03-16 17:51:30

标签: java image swing user-interface jbutton

我试图在单击按钮后在框架内打开图像,到目前为止,我已将图像放在按钮内的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); 
        }
    }

1 个答案:

答案 0 :(得分: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);   
    } 
}