gpt4 book ai didi

java - 单击时如何更改 JButton 上的图像?

转载 作者:行者123 更新时间:2023-11-30 08:23:22 24 4
gpt4 key购买 nike

    JButton lunarButton = new JButton(new ImageIcon("assets/Buttons/moon.png"));
lunarButton.setActionCommand("switch");
c.gridwidth=1;
c.gridy = 0;
searchArea.add(lunarButton, c);

.

public void actionPerformed(ActionEvent ev)
{
int count = 1;
String action = ev.getActionCommand();

if("switch".equals(action))
{
ImageIcon sun = new ImageIcon("assets/sun.png");
ImageIcon moon = new ImageIcon("assets/moon.png");

changeLunar();
count++;
if (count % 2 == 0)
{
lunarButton.setIcon(sun);
}
else
{
lunarButton.setIcon(moon);
}

我已经实现了这段代码,但是 eclipse 告诉我“无法解析 lunarButton”,它是否无法在我的 init() 方法中看到 lunarButton 变量?我在这里错过了什么?

最佳答案

您的 lunarButton 可能在本地声明,也许在 init 方法中。

一种解决方案:在类中将其声明为实例字段,而不是在init方法中。

解决方案二:甚至不用担心变量。从 ActionEvent 参数的 getSource() 方法获取 JButton 对象。转换返回到 JButton 的对象,并调用您想要的任何方法。

例如:

if("switch".equals(action))
{
// ImageIcon sun = new ImageIcon("assets/sun.png");
// ImageIcon moon = new ImageIcon("assets/moon.png");

JButton btn = (JButton) ae.getSource();

changeLunar();
count++;
if (count % 2 == 0)
{
btn.setIcon(sun);
}
else
{
btn.setIcon(moon);
}

顺便说一句:您真的不想在每次按下按钮时都从磁盘重新加载图像。而是一次读取图像,也许在构造函数中,将它们填充到 ImageIcon 字段中,并在需要时使用该字段。

关于java - 单击时如何更改 JButton 上的图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23717939/

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