Showing posts with label what is jbutton in java. Show all posts
Showing posts with label what is jbutton in java. Show all posts

Sunday, 7 April 2019

JButton in Java | What is JButton in java swing with example - Online Help

JButton in Java:

The JButton in java is a class which is used to push the button. The JButton class has three constructors are as follows:

JButton()

It is used to create an empty JButton.

JButton(String str)

It is used to create a JButton with the specified string.

JButton(String str, Icon icon)

It is used to create a JButton with a specified icon;

An image is placed on the button. The following constructors are as follows:

ImageIcon(String filename)

It is used to construct an icon where the image is stored in a file.we can set the boundary of the JButton.The general form is:
                   
                                               void setBounds(int s,int y,int w,int h)
here,
w-width
h-height

Methods for JButtons in java:

The most commonly used JButton() methods are as follows:

Void addActionListener(ActionEvent ae)

This is used to add the specified action listener to receive action events from the corresponding JButton.

void setActionCommand(String actionstr)

The setActionCommand() methods are used to set the string for the action event of the JButton.

void setText(String str)

The setText() method is used to set the text for the fields.

void setEnabled(boolean state)

The setEnabled()method is used to enable or disable the JButton.

void setBackground(Color bgcolor)

The setBackground() method is used to color the background of the JLabel.

void setForeground(Color strcolor)

The setForeground() method is used to set the color of the string for the JLabel.

Sample program for JButton in java:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*<applet code="JButtonDemo" width=500 height=500></applet>*/
public class JButtonDemo extends JApplet implements ActionListener
{
JButton b1,b2;
JTextField tf;
public void init()
{
Container c=getContenetPane();
c.setLayout(new FlowLayout());
b1=new JButton("internet explorer");
b1.setActionCommand("MicrosoftInternetExplorer");
b1.addActionListener(this);
b1.setBounds(20,20,150,50);
c.add(b1);
b2=new JButton("NN");
b2.setActionCommand("Netscape navigator");
b2.addActionListener(this);
b2.setBounds(20,20,150,50);
c.add(b2);
}
public void actionPerformed(ActionEvent ae)
{
tf.setText(ae.getActionCommand());
}
}