MrDavidNhan10 MrDavidNhan10 - 19 days ago 4
Java Question

How can I make buttons to make square with color?

Write a program that shows a window with three button. Each button has a name like “Red” , “Green” and “Blue”. In this window, there is also a label. The label contains an icon. This icon must be a CompositeIcon where in the beginning is empty. Every time you press on a button you can see a square with the button color like for an example “press blue button -> a blue square appears on the window”.
So far I have this. I have the three buttons with their color name. I every time I press one of the buttons it does not work. What do I need to do?

Code:

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

public class ActionTester{

public static void main(String[] args){
JFrame frame = new JFrame();


final JTextField textField = new JTextField();

JButton RedButton = new JButton("Red");

RedButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
SquareIcon red = new SquareIcon(20,Color.RED);
CompositeIcon ci = new CompositeIcon();
ci.addIcon(red);


}
});


JButton GreenButton = new JButton("Green");

GreenButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
SquareIcon green = new SquareIcon(20,Color.GREEN);
CompositeIcon ci = new CompositeIcon();
ci.addIcon(green);

}
});

JButton BlueButton = new JButton("Blue");

BlueButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
SquareIcon blue = new SquareIcon(20,Color.BLUE);
CompositeIcon ci = new CompositeIcon();
ci.addIcon(blue);


}
});


frame.setLayout(new FlowLayout());

frame.add(RedButton);
frame.add(GreenButton);
frame.add(BlueButton);
frame.add(textField);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
}

Answer

All you need to do is to create one Square Object that you change in the ActionListener like:

final JPanel sqr = new JPanel();

JButton RedButton = new JButton("Red");

RedButton.addActionListener(new ActionListener()
{
  @Override
  public void actionPerformed(ActionEvent e)
  {
    sqr.setBackground(Color.RED);
  }
});

And dont forget to add sqr to the frame

On another note, please avoid using imports like

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

In my project it came down to

import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;

Some IDEs can sort you imports automaticly so you dont need to bother with the most common imports anymore