JLabel 不能与 ButtonHandler 一起使用

JLabel won't work with ButtonHandler

对于我的作业,我必须创建一个基于框架的应用程序,允许用户在三个文本字段中指定 RGB 值,并且在按下按钮时,以所选颜色显示我的姓名和注册号。我相信到目前为止我的所有代码都是正确的,但是看起来更改颜色的部分存在问题。

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;



public class ex1 extends JFrame {
JLabel label;
JTextField r, g, b;

public ex1() {
    //panels to hold information
    JPanel bottomPanel = new JPanel();
    JPanel upperPanel = new JPanel();

    //fields that will hold the colour values
    r = new JTextField("Red", 10);
    g = new JTextField("Green", 10);
    b = new JTextField("Blue", 10);

    //add to frame
    bottomPanel.add(r);
    bottomPanel.add(g);
    bottomPanel.add(b);
    add(bottomPanel, BorderLayout.SOUTH);
    add(upperPanel, BorderLayout.CENTER);
    label = new JLabel("CE203 Assignment 1, submitted by:");
    label.setForeground(new Color(255, 0, 0));
    JButton button = new JButton("Enter");
    upperPanel.add(label);
    bottomPanel.add(button);
    button.addActionListener(new ButtonHandler(this));
}

public JLabel getLabel() {
    return label;
}

class ButtonHandler implements ActionListener {
    private ex1 assignment1;
    public ButtonHandler(ex1 assignment1) {
        this.assignment1 = assignment1;
    }
    @Override
    public void actionPerformed(ActionEvent e) {
        int r1 = Integer.parseInt(assignment1.r.getText());
        int g1 = Integer.parseInt(assignment1.g.getText());
        int b1 = Integer.parseInt(assignment1.b.getText());
        assignment1.getLabel().setForground(new Color(r1, g1, b1));
    }
}

public static void main(String[] args) {
    JFrame frame = new ex1();
    frame.setSize(400, 400);
    frame.setDefaultCloseOperation(ex1.EXIT_ON_CLOSE);
    frame.setVisible(true);
}
}

如果有人能告诉我出了什么问题以及我该如何解决,将不胜感激。

IDE报编译错误时不要忽略!

assignment1.getLabel().setForground(new Color(r1, g1, b1));

应该是:

assignment1.getLabel().setForeground(new Color(r1, g1, b1));

其他提示

  1. 而不是:

    frame.setSize(400, 400); // random guess at required size
    

    有:

    frame.pack(); // calculates the required size
    
  2. 在现实世界的编程中,当一个 JColorChooser 非常优越时,用户会因为程序员提供 3 个文本字段而对他处以私刑。