Constructors of Button class:
-Button()
creates a button with empty label.
-Button(String label)
creates a button with string label.
Useful methods of Button class:
-addActionListener(ActionListener listener): void
registers the new listener to receive events from the button.
-getLabel(): String
reads the label on the button.
-setLabel(String label): void
set the label to the button.
Example:
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Label;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
class ShowImage extends Label{
BufferedImage bi=null;
public void paint(Graphics g){
if(bi!=null)
g.drawImage(bi,0,0,null);
}
public void loadImage(String filename){
try{
bi=ImageIO.read(new File(filename));
}catch(IOException ie){System.out.println("Can't read the image file");}
}
}
class InterfaceShow extends Frame implements ActionListener{
InterfaceShow(String title){
setTitle(title);
setSize(new Dimension(350,300));
setLayout(new BorderLayout());
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
Button btshow=new Button("Show image");
btshow.addActionListener(this);
Panel panel=new Panel();
panel.add(btshow);
add(panel, BorderLayout.NORTH);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
ShowImage si=new ShowImage();
si.loadImage("d:/earth.png");
add(si,BorderLayout.CENTER);
validate();
}
}
public class AWTControls {
public static void main(String[] args){
new InterfaceShow("Using Button");
}
}