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");
}
}
Is it possible to perform click action automatically on a button in a specified time interval?
ReplyDeleteYes, it is possible. The steps below can help you to cause action on a button automatically in a specified time delay.
ReplyDelete1. Create a class that implements the ActionListener interface and override its actionPerformed(ActionEvent e) method.
class ActList implements ActionListener{
public void actionPerformed(ActionEvent e){
//code to do sth when the button is pushed
}
}
2. Create an object of the ActList class and supply it to the addActionListener (ActionListener list) method of the button. Then create a timer object that takes time delay and ActList object. You can start the timer by using its start method.
Button bt=new Button("Auto click button");
ActList al=new ActList();
bt.addActionListener(al);
Timer timer=new Timer(2000,al);//delay 2 seconds
timer.setRepeats(false);//fire action only one time
timer.start();//start the timer