peekay peekay - 1 year ago 76
Java Question

JLabel won't work with ButtonHandler

For my assignment I have to create a frame-based application that allows the user to specify RGB values in three text fields, and, when a button is pressed, displays my name and registration number in the chosen colour. I believe all my code is correct so far however it appears that there is an issue in the part that changes the colour.

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
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");
button.addActionListener(new ButtonHandler(this));

public JLabel getLabel() {
return label;

class ButtonHandler implements ActionListener {
private ex1 assignment1;
public ButtonHandler(ex1 assignment1) {
this.assignment1 = assignment1;
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);

If anyone could show me what is going wrong and how I can fix it, it would be greatly appreciated.

Answer Source

Don't ignore the IDE when it is reporting compilation errors!

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

Should be:

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

Other tips

  1. Instead of:

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


    frame.pack(); // calculates the required size
  2. In real world programming, the user would lynch a programmer for offering 3 text fields when one JColorChooser is vastly superior.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download