gpt4 book ai didi

java - 按下按钮时图像更改Java

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:17:51 26 4
gpt4 key购买 nike

好的,我希望在按下 helpButton 时更改我的背景图像。当鼠标悬停在鼠标监听器上时,我可以改变按钮图像。除了 Action Listener,我做了相同的步骤,但没有成功。任何帮助都会很棒!

public class test extends JFrame{

private JLabel label;
private JButton button;

private ImageIcon bgi;
private JLabel bgl;

public static Rectangle gameSquare;


private JButton startButton;
private JButton helpButton;
private final Action action = new SwingAction();


public static void main(String[] args) throws MalformedURLException, IOException {
test gui = new test ();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // when click x close program
gui.setSize(902, 305);
gui.setVisible(true);
gui.setTitle("Solid Cloud Inc - Twitter Unfolower");
}

public test() throws MalformedURLException, IOException{

bgi = new ImageIcon(getClass().getResource("tu.png"));
getContentPane().setLayout(null);

BufferedImage img = ImageIO.read(new URL("http://i1344.photobucket.com/albums/p656/SolidCloudInc/start_zpsf3781681.png"));
//ImageIcon start = new ImageIcon(getClass().getResource("start.png"));
startButton = new JButton("");
startButton.setIcon(new ImageIcon(img));
startButton.setBounds(22, 186, 114, 50);


getContentPane().add(startButton);

BufferedImage img2 = ImageIO.read(new URL("http://i1344.photobucket.com/albums/p656/SolidCloudInc/help_zpsc4fad867.png"));
final JButton helpButton = new JButton("");
helpButton.setIcon(new ImageIcon(img2));
helpButton.setBounds(192, 186, 114, 50);

getContentPane().add(helpButton);

bgl = new JLabel (bgi);
bgl.setBounds(0, 0, 886, 272);
getContentPane().add(bgl);

Events e = new Events();
startButton.addActionListener(e);
helpButton.addActionListener(e);
}

public class Events implements ActionListener {


public void actionPerformed(ActionEvent e) {

if (e.getSource() == startButton) {
label.setText("Searching");

try {
Unfollow();
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
else if (e.getSource() == helpButton){
System.out.println("gottem");
bgi = new ImageIcon(getClass().getResource("tu2.png"));
bgl = new JLabel (bgi);
}
}

}

最佳答案

bgl = new JLabel (bgi);

在这里,您创建了一个新的 JLabel,并将其放入 bgl 变量中,但正在对其进行任何操作,并且未对继续显示在 GUI 中的 JLabel 对象进行任何更改。这是一个常见的新手陷阱,认为通过更改变量的引用,您会更改该变量先前引用的原始对象的状态。它不是这样工作的。换句话说,尽管有上面的代码,bgl 变量持有的原始 JLabel 仍然存在并且仍然在 GUI 中显示其原始内容。您应该做的是更改原始 JLabel 显示的图标,或者换句话说,更改当前 JLabel 对象的状态,而不是更改 bgl 变量持有的引用。即,

bgl.setIcon(bgi);

此外,您将希望摆脱任何和所有空布局的使用以及对 setBounds(...) 的调用,因为这将导致难以维护和升级代码的错误。让布局管理器完成有关布局 GUI 的繁重工作。

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

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