Tuesday, May 20, 2014

how to add buttons on JPanel in java?





The JPanel class provides general-purpose containers for lightweight components. By default, panels do not add colors to anything except their own background; however, you can easily add borders to them and otherwise customize their painting. Details can be found in Performing Custom Painting.

In many types of look and feel, panels are opaque by default. Opaque panels work well as content panes and can help with painting efficiently, as described in Using Top-Level Containers. You can change a panel's transparency by invoking the setOpaque method. A transparent panel draws no background, so that any components underneath show through.



AddButton.java

import javax.swing.*;

import java.awt.event.*;

import java.awt.*;



public class AddButton {

  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();

  AddButton() {

    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) {

    AddButton dispbtn=new AddButton();

     

  }

} //close of class DisplyButton




OUTPUT:-




No comments:

Post a Comment