Java sample(Button & Label)


run

---(Source List)---

//Example11.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Example11{
  JLabel lbl=new JLabel("", JLabel.CENTER);
  //main
  public static void main(String ar[]){
    Example11 sample = new Example11();
  }
  //constructor
  public Example11(){
    //make frame
    JFrame f=new JFrame("Button & Label");
    f.setDefaultCloseOperation(f.EXIT_ON_CLOSE);
    //add button
    JButton bt01=new JButton(new ImageIcon("twinstar.gif"));
    bt01.setActionCommand("twin");
    JButton bt02=new JButton(new ImageIcon("pink.gif"));
    bt02.setActionCommand("pink");
    JButton bt03=new JButton(new ImageIcon("white.gif"));
    bt03.setActionCommand("white");
    //add actionlistener
    bt01.addActionListener(new PushButtonActionListener());
    bt02.addActionListener(new PushButtonActionListener());
    bt03.addActionListener(new PushButtonActionListener());
    //layout
    JPanel p=new JPanel();
    p.add(bt01);
    p.add(bt02);
    p.add(bt03);
    f.getContentPane().add(p,BorderLayout.NORTH);
    f.getContentPane().add(lbl,BorderLayout.CENTER);
    //show frame
    f.setBounds(50,50,300,250);
    f.setVisible(true);
  }
  //actionlistener
  private class PushButtonActionListener implements ActionListener{
    public void actionPerformed(ActionEvent ae){
      if (ae.getActionCommand().equals("twin")){
        lbl.setText("AAAAAA");
      }else if (ae.getActionCommand().equals("pink")){
        lbl.setText("BBBBBBBBB");
      }else if (ae.getActionCommand().equals("white")){
        lbl.setText("CCCC");
      }
    }
  }
}