Search code examples
javaswingcolorsjbutton

How to work with JButton?


Hi I am trying to make java desk top application where I am using 3 JButtons. I want that when I click any JButton it should change the color of that button and if I click on any other JButton then previous clicked button should be like before and recently clicked button change its color until another JButton is clicked

How can I achieve this

here is my button code

b1 = new JButton("Ok");
b1.setBounds(800, 725, 100, 40);
b1.setForeground(Color.BLACK);
c.add(b1);

b2 = new JButton("Print");
b2.setBounds(925, 725, 100, 40);
b2.setForeground(Color.BLACK);
c.add(b2);
b1.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent ae){
        b1.setBackground(Color.BLUE);
        JOptionPane.showMessageDialog(frame,"Welcome to allhabad High Court");
    }
});

b2.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent ae){
        b2.setBackground(Color.BLUE);
        JOptionPane.showMessageDialog(frame,"Welcome to allhabad High Court");
    }
});

Solution

  •      b1.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent ae){
           b1.setBackground(Color.BLUE);
           b2.setBackground(Color.BLACK);
    JOptionPane.showMessageDialog(frame,"Welcome to allhabad High Court");
    }
    });
    
        b2.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent ae){
           b2.setBackground(Color.BLUE);
          b1.setBackground(Color.BLACK);
    JOptionPane.showMessageDialog(frame,"Welcome to allhabad High Court");
    }
    });