john pfeiffer
  • Home
  • Categories
  • Tags
  • Archives

swing button press action event listener

import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;

public class Swing extends JFrame implements ActionListener
{
    private static final long serialVersionUID = 1L;

    JPanel pane = new JPanel();
  JButton pressme = new JButton("Press Me");
  JLabel answer = new JLabel("");

  Swing()
  {
    super( "Button Press" );
    setBounds( 100 , 100 , 300 , 200 );
    setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
    Container myContainer = this.getContentPane();  // inherit main frame

    myContainer.add( pane );
    pressme.setMnemonic( 'P' );
    pane.add( pressme );
    pressme.addActionListener(this);
    pressme.requestFocus();

    answer.setText( "Please press the button" );
    pane.add( answer );

    setVisible(true);
  }


  public void actionPerformed( ActionEvent event )
  {
    Object source = event.getSource();
    if( source == pressme )
    {
      answer.setText( "Button pressed!" );
      JOptionPane.showMessageDialog( null , "Popup from button." , "Message Dialog" , JOptionPane.PLAIN_MESSAGE );
      setVisible(true);
    }
  }


  public static void main( String args[] )
  { new Swing();
  }

}

  • « Linux server gui centos ubuntu
  • swing combobox DRAFT »

Published

Nov 18, 2011

Category

java

~106 words

Tags

  • action 1
  • button 10
  • event 2
  • java 252
  • listener 3
  • press 1
  • swing 9