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 に答える