快速问题 您将如何使 1 JButton
在单击时更改面板的颜色并显示它的颜色我做过一些教程,当单击不同的按钮时,有 3 个JButtons
颜色变化,但你如何只做一个JButton
更改面板颜色,例如黄色、绿色和红色。
import javax.swing.*;
import java.awt.event.*;
public class ChangeButtonColor{
JButton button;
public static void main(String[] args){
ChangeButtonColor cl = new ChangeButtonColor();
}
public ChangeButtonColor(){
JFrame frame = new JFrame("Change JButton Color");
JPanel panel = new JPanel();
button = new JButton();
button.addActionListener(new MyAction());
frame.add(button);
frame.setSize(400, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public class MyAction implements ActionListener{
public void actionPerformed(ActionEvent e){
}
}
}
"也许我可以做例如,当按钮被单击时(如果面板颜色是红色打印出红色,否则如果面板是绿色打印出绿色)那会很好吗"
您可以检查if (panel.getBackground() == Color.RED)
,例如
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ColorClick {
public static void main(String[] args) {
final JPanel panel = new JPanel(new GridBagLayout()) {
{
setBackground(Color.RED);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
};
JButton button = new JButton("Change Color");
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
if (panel.getBackground() == Color.RED) {
System.out.println("RED");
panel.setBackground(Color.GREEN);
} else if (panel.getBackground() == Color.GREEN) {
System.out.println("GREEN");
panel.setBackground(Color.RED);
}
}
});
panel.add(button);
JOptionPane.showMessageDialog(null, panel);
}
}