user476033
user476033

Reputation: 4737

Java GUI is being created, but event is not triggering anything

I am trying to create this simple GUI where the number of clicks is displayed on the button and incremented after each click, and so that after each click, the colours of each button are rotated one value to the right. At the moment, the GUI is created, but the background is not set and nothing happens when you click on anything. I can't seem to find a problem here. Can anyone see any ?

Thanks a lot for your help with this :)

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


public class ButtonJava extends JButton implements ActionListener  {
  private static int currentColor=0;
  private int clicks;
  private static final Color[] COLORS = {
    Color.ORANGE,
    Color.WHITE,
    Color.GREEN };

  public ButtonJava( ){
    setBackground( Color.YELLOW );
    setText( "Pick ME" );
    this.addActionListener( this );
  }

  public static void main(String[] args) {
    JFrame frame = new JFrame ("JFrame");
    JPanel panel = new JPanel( );
    frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE);
    JButton buttons[] = new JButton[3];
    for(int i = 0;i<buttons.length ; i++){
      buttons[i] = new ButtonJava(); 
      panel.add(buttons[i]);
    }
    frame.getContentPane( ).add( panel );
    frame.setSize( 500, 500);
    frame.setVisible( true );
  }

  private void updateButton() {
    changeColors();
    clicks++;
    setText( "# of clicks = " + Integer.toString(clicks) );
  }

  private void changeColors( ) {
    for (int i=0;i<COLORS.length;i++){
      setBackground(COLORS[currentColor]);
      currentColor %=2;
    }
  }

  @Override
  public void actionPerformed( ActionEvent event ) {
    updateButton( );   
  }


}

Upvotes: 0

Views: 159

Answers (3)

POSIX_ME_HARDER
POSIX_ME_HARDER

Reputation: 762

Shouldn't it be :

ButtonJava buttons[] = new ButtonJava[3];
for(int i = 0;i<buttons.length ; i++){
    buttons[i] = new ButtonJava(); 
    panel.add(buttons[i]);
 }

?

Upvotes: 0

ColinD
ColinD

Reputation: 110054

In main, you're making normal JButtons and adding them to your UI when I guess you mean to be adding ButtonJava instead.

Upvotes: 0

Nate W.
Nate W.

Reputation: 9259

Simple mistake - you're not creating your custom button class, you're using JButton.
Change the following line:
buttons[i] = new JButton("Pick Me");
To:
buttons[i] = new ButtonJava();

Upvotes: 1

Related Questions