gpt4 book ai didi

java - JButton 释放 Action

转载 作者:行者123 更新时间:2023-11-30 07:44:42 25 4
gpt4 key购买 nike

我正在尝试在 JButton 版本上创建一个操作,但我不确定如何完成此操作。当按下按钮时,我可以做一个很好的 Action 。按下按钮时,它会将图像更改为红点,松开时应变回默认的绿点。

我的按钮按下代码如下,如果有人可以指出我在释放按钮时如何创建 Action 的方向,那将是最有帮助的。谢谢!

@Override
public void actionPerformed(ActionEvent e) {

if (e.getSource() == change1) {

p1a.setIcon(CLR); // THIS IS THE IMAGE WHEN BUTTON PRESSED
// WOULD LIKE TO CHANGE BACK TO DEFAULT IMAGE HERE WHEN BUTTON IS RELEASED
}
}

最佳答案

I'm not looking for an Icon on the button itself to change I am looking for the image to change in a JPanel....same concept though

很高兴能提前获得这些信息

一种方法可能是将监听器附加到 ButtonModel 并监视它的状态变化...

Go Stop

import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.image.BufferedImage;
import javax.swing.ButtonModel;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public class Test {

public static void main(String[] args) {
new Test();
}

public Test() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}

public class TestPane extends JPanel {

private Icon normalIcon;
private Icon pressedIcon;

public TestPane() {
setBorder(new EmptyBorder(16, 16, 16, 16));
normalIcon = makeIcon(Color.GREEN);
pressedIcon = makeIcon(Color.RED);

setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;

JLabel label = new JLabel(normalIcon);
JButton btn = new JButton("Pressy");

add(btn, gbc);
add(label, gbc);

btn.getModel().addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
ButtonModel model = btn.getModel();
if (model.isArmed()) {
label.setIcon(pressedIcon);
} else {
label.setIcon(normalIcon);
}
}
});
}

protected Icon makeIcon(Color color) {
BufferedImage img = new BufferedImage(25, 25, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = img.createGraphics();
g2d.setColor(color);
g2d.fillOval(0, 0, 25, 25);
g2d.dispose();

return new ImageIcon(img);
}

}

}

关于java - JButton 释放 Action ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52395907/

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