java - JButton 来回改变某物的颜色?

标签 java swing

我需要让 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/

相关文章:

java - 如何将字符串转换为具有最少字符替换数的回文字符串,以便回文字符串包含给定的单词?

java - 创建基于 GUI 的计时器(或秒表)

java - 组件不显示在自定义 JPanel/JComponent 中

java - 异或的反函数是什么?

java - mysql + 阿兹卡类 : Reading "LongBlob"

java - notify() 如何按顺序或随机唤醒线程

java - Java 9 集合工厂的使用

java - 让我的文字处理器 GUI 打开文件

java - 这个彩色的 JTree 有什么问题吗? (自定义渲染器问题)

java - JFrame 中的 setColor 不起作用