-1

my first post here. I'm currently in school and usually spend my time here on Stackoverflow looking for answers to homework, this time i'd thought that perhaps i'll put my code here and maybe i'll get help more precis and quicker! Anyways, my problem is that i've written a code which you can see below, and I'm new to swing, studied it for a few hours only. My problem is that I'm not quite sure how to proceed with my problem, I have 2 buttons, what i want is when you click on first button the panel will change to Red, second button the panel changes to blue, so far only Red works and I don't know how to implement it so that blue works aswell.

Would greatly appreciate your help! (Don't be shy about pointing out a few errors or help along the way that doesn't have with the buttons to do, as I said, I'm new :P)

public class FirstProgram extends JFrame {

    public FirstProgram() {

        initUI();
    }

    private void initUI() {

        JPanel panel = new JPanel();
        panel.setBackground(Color.yellow);
        getContentPane().add(panel);
        panel.setLayout(null);

        JButton Colorbutton = new JButton("Red");
        Colorbutton.setBounds(50, 60, 80, 30);
        Colorbutton.setToolTipText("Panel changes to red");
        Colorbutton.setBackground(Color.green);

        JButton Colorrbutton = new JButton("Blue");
        Colorrbutton.setBounds(1, 30, 90, 30);
        Colorrbutton.setToolTipText("Panel changes to blue");
        Colorrbutton.setBackground(Color.orange);

        Colorbutton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent event) {
                panel.setBackground(Color.red);

            }
        });

        panel.add(Colorbutton);
        panel.add(Colorrbutton);
        setTitle("Time to change colors");
        setSize(300, 200);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {

        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                FirstProgram ex = new FirstProgram();
                ex.setVisible(true);
            }
        });
    }
}
yogidilip
  • 790
  • 6
  • 21
  • 1) Use a logical and consistent form of indenting code lines and blocks. The indentation is intended to make the flow of the code easier to follow! 2) A single blank line of white space in source code is all that is *ever* needed. Blank lines after `{` or before `}` are also typically redundant. 3) There is no question here, or if there is, it has no '?'. If there is a question hidden among those words, please add a '?', if not, please add a question (as an [edit](http://stackoverflow.com/posts/33421675/edit)). – Andrew Thompson Oct 29 '15 at 18:17
  • 4) Please learn common Java nomenclature (naming conventions - e.g. `EachWordUpperCaseClass`, `firstWordLowerCaseMethod()`, `firstWordLowerCaseAttribute` unless it is an `UPPER_CASE_CONSTANT`) and use it consistently. 5) Java GUIs have to work on different OS', screen size, screen resolution etc. using different PLAFs in different locales. As such, they are not conducive to pixel perfect layout. Instead use layout managers, or [combinations of them](http://stackoverflow.com/a/5630271/418556) along with layout padding and borders for [white space](http://stackoverflow.com/a/17874718/418556). – Andrew Thompson Oct 29 '15 at 18:18
  • I appreciate the wanting to learn. You said you've seen other Stack Overflow posts before, and this is only your first time posting. You may have noticed that other questions have a, well, specific question. Why do you think the panel is not changing to the colour blue? Have you tried debugging? Do you get any errors? Have you looked up other questions, such as "how to make multiple events with a single action listener"? You may find that answering these questions and doing a bit of research will prevent you from having to ask a question in the first place (duplicates are not welcome). – Hypino Oct 29 '15 at 18:19

4 Answers4

2

you need another ActionListener. right now you just have one and it has just one behavior. create another one and tie to the 'Blue" button

JButton RedColorbutton = new JButton("Red");
 RedColorbutton .setBounds(50, 60, 80, 30);
 RedColorbutton.setToolTipText("Panel changes to red");
 RedColorbutton.setBackground(Color.green);

 JButton BlueColorbutton = new JButton("Blue");
 BlueColorrbutton.setBounds(1,30,90,30);
 BlueColorrbutton.setToolTipText("Panel changes to blue");
 BlueColorrbutton.setBackground(Color.orange);

 RedColorbutton.addActionListener(new ActionListener() {
 @Override
 public void actionPerformed(ActionEvent event) {
 panel.setBackground(Color.red);
 }
 });

BlueColorbutton.addActionListener(new ActionListener() {
 @Override
 public void actionPerformed(ActionEvent event) {
 panel.setBackground(Color.blue);
 }
 });
AbtPst
  • 7,778
  • 17
  • 91
  • 172
2

You've set an action listener for your Colorbutton, but not for Colorrbutton

Add this next to your other ActionListener

Colorrbutton.addActionListener(new ActionListener()
{
    public void actionPerformed(ActionEvent event)
    {
        panel.setBackground(Color.blue);
    }
});
phflack
  • 2,729
  • 1
  • 9
  • 21
2

You are missing an ActionListener for the blue JButtton.

Similar to how you added the ActionListener to your ColorButton, your ColorrButton needs to have one registered. By the way, you may wish to change the ColorButton to redButton and the ColorrButton to blueButton or something like that to make things stick out better.

example:

    Colorrbutton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent event) {
            panel.setBackground(Color.blue);
        }
    });
John
  • 376
  • 1
  • 7
  • That's basicly the thought I had in mind, that I needed to put a new addActionListener for the blue color, but I didn't quite know how to write it in there, the posts i was reading was mainly writing some sort of "eventsources" code with an if statement in the actionperformed I believe, saying "if red is pushed, panel turns red" etc, but this worked and it helped me out alot, i'll take all your tips and guides and help into consideration for my next post, thanks alot guys! – Kaosutanpaus Oct 29 '15 at 19:04
0

For the sake of reducing duplicate code, you can simplify the logic even further by having your class implement ActionListener.

public class FirstProgram extends JFrame implements ActionListener {

Then, when you are instantiating your buttons, add a listener like so:

redButton.addActionListener(this);
blueButton.addActionListener(this);

And then in your implementation of actionPerformed you could do something like:

public void actionPerformed(ActionEvent e) {
    switch (e.getSource()) {
        case redButton:
            panel.setBackground(Color.red);
            break;
        case blueButton:
            panel.setBackground(Color.blue);
            break;
    }
}

Anytime the red or blue buttons performs an action, the actionPerformed will be triggered, and then the logic to determine which button was the source will take over from there. This will add a little bit of length to your code, but as(if?) your program grows, it will reduce complexity greatly

Brandon Laidig
  • 430
  • 2
  • 14