Professional Documents
Culture Documents
09/08/09 SWING 2
The JButton Class
Constructors
JButton(Icon i)
JButton(String s)
JButton(String s, Icon i)
Here s, and i are the String and Icon used for the
Button.
09/08/09 SWING 3
JButton
09/08/09 SWING 4
JButton
09/08/09 SWING 5
Example
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class ButtonSample {
public static void main(String args[]) {
09/08/09 SWING 6
continue
Runnable runner = new Runnable() {
public void run() {
JFrame frame = new JFrame("Button Sample");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button = new JButton("Select Me");
// Define ActionListener
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
System.out.println("I was selected.");
}
};
09/08/09 SWING 7
Continue
// Attach listeners
button.addActionListener(actionListener);
frame.add(button, BorderLayout.SOUTH);
frame.setSize(300, 100);
frame.setVisible(true);
}
};
EventQueue.invokeLater(runner);
}
}
09/08/09 SWING 8
Output
I was selected
09/08/09 SWING 9
Example 2
import java.awt.*;
import javax.swing.*;
public class JButtons extends JFrame {
public static void main(String[] args) {
new JButtons();
}
public JButtons() {
super("Using JButton");
WindowUtilities.setNativeLookAndFeel();
addWindowListener(new ExitListener());
Container content = getContentPane();
content.setBackground(Color.WHITE);
content.setLayout(new FlowLayout());
09/08/09 SWING 10
Continue
JButton button1 = new JButton("Java");
content.add(button1);
ImageIcon cup = new ImageIcon("images/cup.gif");
JButton button2 = new JButton(cup);
content.add(button2);
JButton button3 = new JButton("Java", cup);
content.add(button3);
JButton button4 = new JButton("Java", cup);
button4.setHorizontalTextPosition
(SwingConstants.LEFT);
content.add(button4);
pack();
setVisible(true);
}
}
09/08/09 SWING 11
Output
09/08/09 SWING 12
09/08/09 SWING 13