簡體   English   中英

當用戶單擊GUI中的按鈕時,我想打開一個圖像

[英]I would like to open an image when a user clicks on a button in GUI

單擊按鈕后,我正在嘗試使圖像在框架中打開,到目前為止,我已將圖像放入希望單擊以打開的按鈕中的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); 
        }
    }

我認為您希望在單擊按鈕時將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);   
    } 
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM