我需要让 jbutton 将红色圆圈的颜色更改为绿色,很简单。但是每次按下按钮时颜色都会在红色和绿色之间变化,你是如何做到的呢?我可以让它改变颜色一次,但仅此而已。
这是我的面板:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class mypanel extends JPanel implements ActionListener {
JButton b;
Color c1, c2;
int x, y, z, q;
public mypanel() {
this.setVisible(true);
this.setBackground(Color.darkGray);
b = new JButton("change color");
add(b);
b.setBounds(110, 0, 30, 50);
b.addActionListener(this);
c1 = Color.green;
c2 = Color.red;
x = 80;
y = 130;
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
this.requestFocus();
g.setColor(Color.black);
g.fillRect(110, 70, 60, 100);
g.setColor(c2);
g.fillOval(125, x, 30, 30);
}
public void actionPerformed(ActionEvent e) {
repaint();
if (e.getSource() == b) {
c2 = c1;
x = y;
}
}
}
最佳答案
您需要对代码进行多项更改:
- 第三个
Color
对象,用于存储当前Color
- 检查 currentColor 是红色还是绿色的方法:我使用了
boolean
- 删除
y
变量。
我注意到的最重要的事情是你改变当前变量值的方式。但这使得不可能返回旧值,因为现在有两个引用指向同一个对象。
您应该解决这个问题,阅读引用或原始值。
注意:这可以简化,但为了清楚起见,我更喜欢添加更多步骤。这样就更容易理解了。
<小时/>解决方案
public class mypanel extends JPanel implements ActionListener {
JButton b;
Color c1, c2, currentColor;
boolean isRed = true;
int x, z, q;
public mypanel() {
this.setVisible(true);
this.setBackground(Color.darkGray);
b = new JButton("change color");
add(b);
b.setBounds(110, 0, 30, 50);
b.addActionListener(this);
c1 = Color.green;
currentColor = c2 = Color.red;
x = 80;
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
this.requestFocus();
g.setColor(Color.black);
g.fillRect(110, 70, 60, 100);
g.setColor(currentColor);
g.fillOval(125, x, 30, 30);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == b) {
if (isRed){
currentColor = c1;
x = 130;
isRed = false;
} else {
currentColor = c2;
x = 80;
isRed = true;
}
}
repaint();
}
}
关于java - JButton 来回改变某物的颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33858124/