Java重绘图像

anv*_*nvd 0 java swing image panel repaint

我的剧本有问题; 我想在按下按钮时重新绘制一个新图像(显示另一个图像),但该按钮不执行任何操作...

ActionListener one = new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                panel2.revalidate();
                panel2.repaint();
            }
        };

        btn1.addActionListener(one);



        JLabel test1 = new JLabel(myDeckOfCards.giveCardPlayer1().getImage());

        panel2.add(lab1);
        panel2.add(test1);
        panel2.add(pn5);
        panel2.add(pn1);
        panel2.add(btn1);
Run Code Online (Sandbox Code Playgroud)

Mik*_*ffe 5

在里面,actionPerformed你需要抓住你JLabel并呼唤setIcon()它,传递新的图像.

有几种方法可以获得JLabel,一种方法是确保finalactionPerformed方法范围内的某个地方声明包含它的变量,另一种方法是从内部找到它panel2(不推荐).

ActionListener如果为此目的声明一个完整的类,您也可以通过构造函数将其传递给您.

编辑:

final JLabel test1 = new JLabel(myDeckOfCards.giveCardPlayer1().getImage());

ActionListener one = new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        // Get 'anotherIcon' from somewhere, presumably from a similar
        // place to where you retrieved the initial icon
        test1.setIcon(anotherIcon);
    }
};

btn1.addActionListener(one);

panel2.add(lab1);
panel2.add(test1);
panel2.add(pn5);
panel2.add(pn1);
panel2.add(btn1);
Run Code Online (Sandbox Code Playgroud)