0

I spent 5 hours looking for solution to my question, but I really cannot. I have only learnt java swing for 2 days to do this assignment. ( my professor didn't teach what is needed to finish assignment and only talked about swing for less then 30 mins) I also tried to read Swing documentation, but I have no clue how to read documentation. Because getting into the read question I want to ask 2 irrelevant question.

  1. How to search for method() like repaint() method which I cannot find in the documentation, but I found it on other website.
  2. When learning new language, How would I start learning it from reading documentation? Do I read the tutorial or there are better way?

Questions above are raised because, in this situation, I found myself in loops of confusion, and I just do not know where to start/learn and how.

Anyway, Lets get to the point.

What make this question so confusing to me are all the conditions and requirements that need to be met.

Goal: to have 3 buttons with color's name on it that when is clicked on the color of circle icon changed.

Requirements(confusing part to me)

  1. button label must be color's name in this case red/green/blue

  2. displays a simple icon with a circle initially colored solid red

  3. the circle color must change to that indicated by the button's label.

  4. when a button is clicked you need to change the icon's color, then call the label's repaint() method. This, in turn will call the icon's paintIcon() [Jlabel calls paintIcon for us]

  5. the buttons' action listener objects must be of anonymous classes.

  6. button must create in main() and set up in loop.

    for (i=0; i<3; i++) {
     btn[i] = createButton(i,  ......);
    }
    
  7. The createButton() function you will write gets an index (0 to 2) and creates the green, blue, and red buttons, depending on the valus of i. JButton objects are returned with the proper listener attached.

Hint: Use a Color array that can be indexed by i:

   Color[] colors = new String[]{"RED", "GREEN", "BLUE"};

Then, create the color with the required color:

Below are my current code:

The problems I have are:

  1. how to label create color object that contain string. ( required by professor, but his code does not even work)

  2. How do I use repaint() in ActionPerform to send "signal" to paintIcon, so that when I click a button. Circle shape changes color.

        public class Button_hw implements Icon {
    
    
            private int size;
            private Color color;
    
            public Button_hw(int aSize)
            {
                size = aSize;
            }
    
            // @Override
            public void paintIcon(Component c, Graphics g, int x, int y) {
                Graphics2D g2 = (Graphics2D) g;
                Ellipse2D.Double planet = new Ellipse2D.Double(x,y,size,size);
                g2.setColor(color);
                g2.fill(planet);
    
            }
    
            @Override
            public int getIconWidth() {
                return size;
            }
    
            @Override
            public int getIconHeight() {
                return size;
            }
    
            public static void main(String[] args) {
    
    
                JFrame frame = new JFrame();
    
                final Color[] colors;
                colors = new Color[3];
    
                colors[0]= Color.GREEN;
                colors[1]= Color.RED;
                colors[2]= Color.BLUE;
    
    
                Button_hw Circle = new Button_hw(50);  
                final JLabel label = new JLabel(Circle);
    
                final int FIELD_WIDTH = 20;
    
                JButton btn[];
                btn = new JButton[3];
                for (int i=0; i<3; i++) {
                    btn[i] = new JButton(String.valueOf(colors[i]));
                }
    
                JTextField textField = new JTextField(FIELD_WIDTH);
                textField.setText("Click a button!");
    
                btn[0].addActionListener(new
                        ActionListener(){
                    public void actionPerformed(ActionEvent event)
                    {
                        textField.setText("green");
    
                        label.repaint();
                    }
                });
    
    
    
                btn[1].addActionListener(new
                        ActionListener(){
                    public void actionPerformed(ActionEvent event)
                    {
                        textField.setText("red");
                        label.setColor(Color.RED);
                        label.repaint();
    
                    }
                });
                btn[2].addActionListener(new
                        ActionListener(){
                    public void actionPerformed(ActionEvent event)
                    {
                        textField.setText("blue");
    
                        label.repaint();
                    }
                });      
    
                frame.setLayout(new FlowLayout());
                frame.add(label);
                frame.add(btn[0]);
                frame.add(btn[1]);
                frame.add(btn[2]);
                frame.add(textField);
    
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.pack();
                frame.setVisible(true);
    
            }
    
        }
    
TM00
  • 1,330
  • 1
  • 14
  • 26
  • must the icon be inside a `JLabel`? I think its much easier to just put it in a `JPanel`. a JLabel's _icon_ is usually an image. Which I think is out of scope for this situation. – TM00 Feb 20 '18 at 10:19
  • Doesn't "Button_hw Circle = new Button_hw(50);" and " final JLabel label = new JLabel(Circle);" put icon inside JLabel? because "frame.add(label);" does show red circle icon in the frame. I am sorry if what I am saying doesn't make sense to you, but this is what i understand. – A-nak Wannapaschaiyong Feb 20 '18 at 10:54
  • It does, it just seems strange to me :) But we'll continue with what is specified in the assignment. Will post an answer shortly. – TM00 Feb 20 '18 at 11:08

1 Answers1

0

So I stumbled upon this question and answer and converted it to suit your example. Probably the same class, different year. This is what I got:

public class ColorChanger implements Icon {

    private Color color;

    public ColorChanger() {
        color = Color.red;
    }

    @Override
    public int getIconWidth() {
        return 10;
    }

    @Override
    public int getIconHeight() {
        return 10;
    }

    public void setColor(Color color) {
        this.color=color;
    }

    @Override
    public void paintIcon(Component c, Graphics g, int x, int y) {
        Graphics2D g2 = (Graphics2D) g;
        Ellipse2D.Double circle = new Ellipse2D.Double(0, 0, 10, 10);
        g2.setColor(color);
        g2.fill(circle);
    }    

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

        ColorChanger myCircle = new ColorChanger();
        final JLabel myLabel = new JLabel(myCircle);

        final int FIELD_WIDTH = 20;

        JTextField textField = new JTextField(FIELD_WIDTH);
        textField.setText("Click a button!");

        final String[] colors = new String[]{"RED", "GREEN", "BLUE"};

        ActionListener listener = new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {

                for (int i = 0; i < colors.length; i++) {
                    if(e.getActionCommand().equals(colors[i])) {

                        switch (colors[i]) {
                        case "RED":
                            myCircle.setColor(Color.RED);
                            break;
                        case "GREEN":
                            myCircle.setColor(Color.GREEN);
                            break;
                        case "BLUE":
                            myCircle.setColor(Color.BLUE);
                            break;

                        default:
                            myCircle.setColor(Color.BLACK);
                            break;
                        }

                        textField.setText(colors[i]);
                        break;
                    }
                }
                myLabel.repaint();
            }
        };

        JButton btn[];
        btn = new JButton[3];
        for (int i=0; i<3; i++) {
            btn[i] = new JButton(colors[i]);
            btn[i].addActionListener(listener);
        }

        myFrame.setLayout(new FlowLayout());
        myFrame.add(myLabel);
        for (int i=0; i<3; i++) {
            myFrame.add(btn[i]);
        }
        myFrame.add(textField);


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

Gui

Your Circle class must implement the Icon interface to behave as an Icon and implement the paintIcon methods. That is most likely where you went wrong.

I also added a single listener and used the ActionCommand to determine which color was selected. It just makes it a little more concise to write. Please do ask if you do not understand.

To answer your two irrelevant questions at the beginning.

  1. All methods should be available in the documentation. It may be in different classes or interfaces which are extended and implemented but it must be there.

  2. I would not start by reading the documentation. I would start with learning the syntax with introductory tutorials and from there look for examples on what you want to do. Documentation is in my opinion for official reference and explanation, not learning. In other words if you want to know what a method does in detail - read the documentation. If you want to know how to use it - find an example.

TM00
  • 1,330
  • 1
  • 14
  • 26