快速提问如何点击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){
}
}
}
答案 0 :(得分:2)
“也许我可以这样做,例如当点击按钮时(如果面板颜色是红色打印出红色,否则如果面板是绿色打印出绿色)那将是好的”
您只需检查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);
}
}