|
This Example illustrates how to create the JButton in swing application. The output of the program and source code are given below:
Source Code of CreateButton.java
import java.awt.Container;
import java.awt.FlowLayout;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class CreateButton extends JApplet {
JButton button = new JButton("JButton");
JLabel label = new JLabel();
class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String name = ((JButton) e.getSource()).getText();
label.setText(name);
}
}
private ButtonListener listener = new ButtonListener();
public void init() {
button.addActionListener(listener);
Container container = getContentPane();
container.setLayout(new FlowLayout());
container.add(button);
container.add(label);
}
public static void main(String[] args) {
run(new CreateButton(), 200, 85);
}
public static void run(JApplet applet,
int width, int height) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(applet);
frame.setSize(width, height);
applet.init();
applet.start();
frame.setVisible(true);
}
} |
|
|