gpt4 book ai didi

java - 使用按钮 Swing 更改图像

转载 作者:行者123 更新时间:2023-12-04 05:21:53 24 4
gpt4 key购买 nike

我以这种方式定义了 2 个类:

public class Cartes extends JPanel
{
private BufferedImage image;
protected int tabC[] = new int[9];
public int randomC ;

public Cartes ()
{

..........

BufferedImage myPicture = null;

try {
myPicture = ImageIO.read(new File("images/"+randomC+".png"));
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}

JLabel picLabel = new JLabel(new ImageIcon( myPicture ));
add( picLabel );
}

public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawImage(image, 0, 0, null); //
}
}

注: randomC是在构造函数中生成的整数,允许我随机选择一个图像。


public class VueGeo extends JFrame
{
public Cartes pan = new Cartes();
private JButton bouton = new JButton("Change");

public VueGeo()
{

...

container.add(pan, BorderLayout.CENTER);

bouton.addActionListener(new BoutonListener ());

...

this.setContentPane(container);

this.setVisible(true);

}

class BoutonListener implements ActionListener
{
public void actionPerformed(ActionEvent arg0) {
????????
}
}
}

问题是我不知道该放什么 actionPerformed为了让我在点击更改时更改图像。有人有想法吗?

最佳答案

在 Cartes 中创建一个 setter 方法:

public void setImage(BufferedImage i)
{ image = i; }

然后,在行动中,
cartes.setImage( (whatever image you would like) );
cartes.repaint();

关于java - 使用按钮 Swing 更改图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13594139/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com