我需要制作一个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;
}
}
}
答案 0 :(得分:3)
您需要使用代码更改多项内容:
Color
对象,用于存储当前的Color
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();
}
}
答案 1 :(得分:2)
最直接的方法是为状态添加一个变量,并设计一种基于该变量绘制的方法,在这种情况下是一个足够的布尔变量:
boolean on = false; //when on use green circle
然后在paintComponent()
中使用颜色和位置更改线条以使用此变量:
g.setColor(on?c1:c2); //uses green when on
g.fillOval(125, on?y:x, 30, 30); //uses lower position when on
有了这些更改,actionPerformed()
只需要更新状态:
if (e.getSource() == b)
on = !on; //toggle state
我们绘制的方式现在完全取决于我们当前的状态,因此我们不会更改描述所绘制圆圈的任何核心变量。