我正在尝试对JButton
版本进行操作,但不确定如何完成此操作。当按下按钮时,我可以执行一个动作。按下按钮时,它将图像更改为红色点,释放按钮时应将其更改为默认的绿色点。
如果有人可以向我指出释放按钮时如何创建动作的方向,这将是最有用的,下面是我的按钮按下代码。谢谢!
@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
}
}
答案 0 :(得分:2)
我不是在按钮本身上寻找图标来更改,而是在JPanel中寻找图像来更改。...虽然是相同的概念
很高兴提前提供这些信息
一种方法可能是将侦听器附加到ButtonModel
并监视其状态更改...
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);
}
}
}
答案 1 :(得分:1)
按下按钮时,它将图像更改为红点,释放按钮时应将其更改为默认的绿点。
这可以在JButton
内完全实现。看到类似setPressedIcon(Icon)
..
E.G。
import javax.swing.*;
import java.net.*;
public class ButtonIcons {
ButtonIcons() throws MalformedURLException {
ImageIcon redIcon = new ImageIcon(new URL(
"https://i.stack.imgur.com/wCF8S.png"));
ImageIcon grnIcon = new ImageIcon(new URL(
"https://i.stack.imgur.com/T5uTa.png"));
JButton button = new JButton("Click me!", grnIcon);
button.setPressedIcon(redIcon);
JOptionPane.showMessageDialog(null, button);
}
public static void main(String[] args) {
Runnable r = () -> {
try {
ButtonIcons o = new ButtonIcons();
} catch (MalformedURLException ex) {
ex.printStackTrace();
}
};
SwingUtilities.invokeLater(r);
}
}