Wednesday, May 21, 2014

how to use buttons in java?






public class JButton extends AbstractButton implements Accessible

The class JButton is an implementation of a push button. This component has a label and generates an event when pressed. It can have Image also.

Buttons can be configured, and to some degree controlled, by Actions. Using an Action with a button has many benefits beyond directly configuring a button.



  DisplyButton.java

import javax.swing.*;

import java.awt.event.*;

import java.awt.*;



public class DisplyButton {

  private JButton b1 = new JButton("Button 1"),b2 = new JButton("Button 2");

  private JTextField txt = new JTextField(10);



  class ButtonListener implements ActionListener {

    public void actionPerformed(ActionEvent e) {

      //String name = ((JButton)e.getSource()).getText();  //Return Button name as type String.

      String arg = e.getActionCommand(); //getActionCommand return Button name as String type.



      //if(e.getSource()==b1 || e.getSource()==b2)    

      // txt.setText(arg);



      //if(arg.equals("Button 1") || arg.equalsIgnoreCase("button 2"))

      // txt.setText(arg);



      txt.setText(arg);

    }

  } //close of class ButtonListener



  private ButtonListener bl = new ButtonListener();

  DisplyButton() {

    JFrame jf=new JFrame("JButton");

    b1.addActionListener(bl);

    b2.addActionListener(bl);

    Container cp = jf.getContentPane();

    cp.setLayout(new BorderLayout());



    JPanel jpForBtn=new JPanel();

    jpForBtn.setLayout(new FlowLayout(FlowLayout.RIGHT)); //FlowLayout.LEFT, FlowLayout.CENTER

    jpForBtn.add(b1);

    jpForBtn.add(b2);



    txt.setBackground(Color.WHITE);

 

    cp.add(jpForBtn,BorderLayout.SOUTH); //add JPanel on Bottom right corner of frame

    cp.add(txt,BorderLayout.NORTH);      //add JTextField on top of frame

  

  

    jf.setSize(600,400);

    jf.setResizable(false);

    jf.setDefaultCloseOperation(jf.EXIT_ON_CLOSE);

    jf.setVisible(true);



  } //close of constructor



  public static void main(String[] args) {

    DisplyButton dispbtn=new DisplyButton();

     

  }

} //close of class DisplyButton




OUTPUT:-



No comments:

Post a Comment