嗨,我正在尝试制作 Java 桌面应用程序,其中使用 3 个 JButton。我希望当我单击任何 JButton 时,它应该更改该按钮的颜色,如果我单击任何其他 JButton,则以前单击的按钮应该像之前一样,最近单击的按钮更改其颜色,直到单击另一个 JButton
我怎样才能实现这个目标
这是我的按钮代码
b1 = new JButton("Ok");
b1.setBounds(800, 725, 100, 40);
b1.setForeground(Color.BLACK);
c.add(b1);
b2 = new JButton("Print");
b2.setBounds(925, 725, 100, 40);
b2.setForeground(Color.BLACK);
c.add(b2);
b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae){
b1.setBackground(Color.BLUE);
JOptionPane.showMessageDialog(frame,"Welcome to allhabad High Court");
}
});
b2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae){
b2.setBackground(Color.BLUE);
JOptionPane.showMessageDialog(frame,"Welcome to allhabad High Court");
}
});
最佳答案
这实际上比听起来更棘手。某些外观在呈现按钮时不使用背景
颜色属性(例如 Windows)
一种可能的解决方案可能是使用 ButtonGroup
和 JToggleButton
,这将确保一次仅选择一个按钮,并允许您监视所选按钮的状态按钮,例如...
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JToggleButton;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class ToggleButton {
public static void main(String[] args) {
new ToggleButton();
}
public ToggleButton() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
final JToggleButton b1 = new JToggleButton("Ok");
b1.setContentAreaFilled(false);
b1.setOpaque(true);
b1.getModel().addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
if (b1.isSelected()) {
b1.setBackground(Color.BLACK);
} else {
b1.setBackground(null);
}
}
});
final JToggleButton b2 = new JToggleButton("Print");
b2.setContentAreaFilled(false);
b2.setOpaque(true);
b2.getModel().addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
if (b2.isSelected()) {
b2.setBackground(Color.BLUE);
} else {
b2.setBackground(null);
}
}
});
ButtonGroup bg = new ButtonGroup();
bg.add(b1);
bg.add(b2);
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridBagLayout());
frame.add(b1);
frame.add(b2);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
另一种解决方案可能是使用JRadioButton
,它通常用于指示从一组选项中进行的单个选择。
关于java - 如何使用JButton?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22679526/