< Prev
Next >



Button class





Button class is used to create a push button control, which can generate an ActionEvent when it is clicked. In order to handle a button click event, ActionListener interface should be implemented. Button is a component which extends JComponent class and it can be added to the container like Frame or a component like Panel.




Constructors of Button


Constructor Description
public Button() Creates a button with no text on it.
public Button(String text) Creates a button with a text on it.





Methods of Button class


Methods Description
public void setText(String text) Sets a String message on the Button.
public String getText() Gets a String message of Button.
public void setLabel() Sets a String text on button.
public String getLabel() Gets the String text of this button.





An example of Button


import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class ButtonEx1
{
Frame jf;
Button button1, button2, button3;

ButtonEx1()
{
jf= new JFrame("Frame displaying buttons");
button1= new Button();
button2= new Button("Click here");
button3= new Button();

button3.setLabel("Button3");

jf.add(button1);
jf.add(button2);
jf.add(button3);

jf.setLayout(new FlowLayout());
jf.setSize(300,100);
jf.setVisible(true);
}

public static void main(String... ar)
{
new ButtonEx1();
}

}

When you run the code, you are presented a window shown below -:

Figure 1





Handling button click events by implementing ActionListener interface


import javax.swing.*;
import java.awt.*;
import java.awt.event.*;


public class ButtonEx2 implements ActionListener
{
Frame jf;
Button button1, button2;
Label label;


ButtonEx2()
{
jf= new Frame("Button click events");
button1= new Button("Yes");
button2= new Button("No");
label = new Label();

jf.add(button1);
jf.add(button2);
jf.add(label);

button1.addActionListener(this);
button2.addActionListener(this);

jf.setLayout(new FlowLayout(FlowLayout.CENTER,60,10));
jf.setSize(250,150);
jf.setVisible(true);
}


public void actionPerformed(ActionEvent ae)
{
if(ae.getActionCommand().equals("Yes"))
{
label.setText("You've clicked Yes");
jf.add(label);
jf.setVisible(true);
}

if(ae.getActionCommand().equals("No"))
{
label.setText("You've clicked No");
jf.add(label);
jf.setVisible(true);
}
}

public static void main(String... ar)
{
new ButtonEx2();
}

}

When you run the code, you are presented a window shown in the Figure2 below -:

Figure 2


When you click on any of the buttons, you will be displayed an appropriate message, for example, when we click on Yes button, we get such message -

Figure 3




Please share this article -

Facebook Google Pinterest Reddit Tumblr Twitter




< Prev
Next >
< TextArea
CheckBox >
Please subscribe our social media channels for notifications, we post a new article everyday.

Decodejava Google+ Page Decodejava Facebook Page  DecodeJava Twitter Page

Coming Next
-
C++ and Python

Ad2