Java/Swing JFC/Button
Версия от 18:01, 31 мая 2010; (обсуждение)
Содержание
- 1 Action Button Sample
- 2 Adding a Disabled Icon to a JButton Component
- 3 Adding an Icon to a JButton Component
- 4 Adding a Rollover and Pressed Icon to a JButton Component
- 5 An example of radio button menu items in action
- 6 A Selected Button
- 7 Button Action Sample
- 8 Button action to change the panel background
- 9 Button demo: Mnemonic, alignment and action command
- 10 Button Html Demo
- 11 Button icons, a default button, HTML in a button,and button mnemonics.
- 12 Button with ICON and Multiline
- 13 Changing the Label of a JButton Component
- 14 Create a JButton that does not show focus
- 15 Creating a JButton Component from Action
- 16 Creating a Multiline Label for a JButton Component
- 17 Demonstration of button events including Action, Item and Change event types
- 18 Displaying a Button with a Border
- 19 Displaying a Button with an Icon Label
- 20 Displaying a Button with Various Label Alignments
- 21 Displaying a Button with Varying Icons
- 22 Display Message
- 23 Dynamically update the appearance of a component
- 24 HTML button
- 25 If the action does not have an icon or a different icon must be used, add or change the icon using setIcon():
- 26 JToggleButton Demo
- 27 Label text italicizes the second line
- 28 Lines are left justified. This label text will center the lines
- 29 LoadSave: Button action
- 30 Mnemonic Sample
- 31 Moving the Icon in a JButton Component
- 32 Moving the Label/Icon Pair in a JButton Component
- 33 Putting buttons on an applet
- 34 Responding to button presses
- 35 Setting the Gap Size Between the Label and Icon in a JButton Component
- 36 Sharing an Action between JButton Components
- 37 Sharing Models between Buttons
- 38 Simple Button UI
- 39 Simple ToggleButton Sample
- 40 Swing Button Demo
- 41 Swing Default Button
- 42 The event demonstration program for JToggleButton
- 43 The Swing-ified button example
- 44 Uses reflection to create groups of different types of AbstractButton
- 45 Various Swing buttons
Action Button Sample
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JRootPane;
public class ActionButtonSample {
public static void main(String args[]) {
JFrame frame = new JFrame("DefaultButton");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
String command = actionEvent.getActionCommand();
System.out.println("Selected: " + command);
}
};
Container content = frame.getContentPane();
content.setLayout(new GridLayout(2, 2));
JButton button1 = new JButton("Text Button");
button1.setMnemonic(KeyEvent.VK_B);
button1.setActionCommand("First");
button1.addActionListener(actionListener);
content.add(button1);
Icon warnIcon = new ImageIcon("Warn.gif");
JButton button2 = new JButton(warnIcon);
button2.setActionCommand("Second");
button2.addActionListener(actionListener);
content.add(button2);
JButton button3 = new JButton("Warning", warnIcon);
button3.setActionCommand("Third");
button3.addActionListener(actionListener);
content.add(button3);
String htmlButton = "<html><sup>HTML</sup> <sub><em>Button</em></sub><br>"
+ "<font color=\"#FF0080\"><u>Multi-line</u></font>";
JButton button4 = new JButton(htmlButton);
button4.setActionCommand("Fourth");
button4.addActionListener(actionListener);
content.add(button4);
JRootPane rootPane = frame.getRootPane();
rootPane.setDefaultButton(button2);
frame.setSize(300, 200);
frame.setVisible(true);
}
}
Adding a Disabled Icon to a JButton Component
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
public class Main {
public static void main(String[] argv) throws Exception {
JButton button = new JButton();
// Icon will appear gray
button.setEnabled(false);
// Set a disabled version of icon
Icon disabledIcon = new ImageIcon("d.gif");
button.setDisabledIcon(disabledIcon);
// To remove the disabled version of the icon, set to null
button.setDisabledIcon(null);
button.setDisabledIcon(new ImageIcon("icon.gif"));
}
}
Adding an Icon to a JButton Component
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
public class Main {
public static void main(String[] argv) throws Exception {
// Retrieve the icon
Icon icon = new ImageIcon("icon.gif");
// Create an action with an icon
Action action = new AbstractAction("Button Label", icon) {
// This method is called when the button is pressed
public void actionPerformed(ActionEvent evt) {
// Perform action
}
};
// Create the button; the icon will appear to the left of the label
JButton button = new JButton(action);
}
}
Adding a Rollover and Pressed Icon to a JButton Component
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
public class Main {
public static void main(String[] argv) throws Exception {
JButton button = new JButton();
// Add rollover icon
Icon rolloverIcon = new ImageIcon("r.gif");
button.setRolloverIcon(rolloverIcon);
// Add pressed icon
Icon pressedIcon = new ImageIcon("p.gif");
button.setPressedIcon(pressedIcon);
// To remove rollover icon, set to null
button.setRolloverIcon(null);
// To remove pressed icon, set to null
button.setPressedIcon(null);
}
}
// An example of radio button menu items in action.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.JTextPane;
import javax.swing.JToolBar;
import javax.swing.KeyStroke;
import javax.swing.border.BevelBorder;
public class RadioButtonMenuItemExample extends JPanel {
public JTextPane pane;
public JMenuBar menuBar;
public JToolBar toolBar;
public RadioButtonMenuItemExample() {
menuBar = new JMenuBar();
JMenu justifyMenu = new JMenu("Justify");
ActionListener actionPrinter = new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
pane.getStyledDocument().insertString(0,"Action [" + e.getActionCommand()+ "] performed!\n", null);
} catch (Exception ex) {
ex.printStackTrace();
}
}
};
JRadioButtonMenuItem leftJustify = new JRadioButtonMenuItem("Left",new ImageIcon("1.gif"));
leftJustify.setHorizontalTextPosition(JMenuItem.RIGHT);
leftJustify.setAccelerator(KeyStroke.getKeyStroke("L", Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
leftJustify.addActionListener(actionPrinter);
JRadioButtonMenuItem rightJustify = new JRadioButtonMenuItem("Right",new ImageIcon("2.gif"));
rightJustify.setHorizontalTextPosition(JMenuItem.RIGHT);
rightJustify.setAccelerator(KeyStroke.getKeyStroke("R", Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
rightJustify.addActionListener(actionPrinter);
JRadioButtonMenuItem centerJustify = new JRadioButtonMenuItem("Center",new ImageIcon("3.gif"));
centerJustify.setHorizontalTextPosition(JMenuItem.RIGHT);
centerJustify.setAccelerator(KeyStroke.getKeyStroke("M", Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
centerJustify.addActionListener(actionPrinter);
JRadioButtonMenuItem fullJustify = new JRadioButtonMenuItem("Full",new ImageIcon("4.gif"));
fullJustify.setHorizontalTextPosition(JMenuItem.RIGHT);
fullJustify.setAccelerator(KeyStroke.getKeyStroke("F", Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
fullJustify.addActionListener(actionPrinter);
ButtonGroup group = new ButtonGroup();
group.add(leftJustify);
group.add(rightJustify);
group.add(centerJustify);
group.add(fullJustify);
justifyMenu.add(leftJustify);
justifyMenu.add(rightJustify);
justifyMenu.add(centerJustify);
justifyMenu.add(fullJustify);
menuBar.add(justifyMenu);
menuBar.setBorder(new BevelBorder(BevelBorder.RAISED));
}
public static void main(String s[]) {
RadioButtonMenuItemExample example = new RadioButtonMenuItemExample();
example.pane = new JTextPane();
example.pane.setPreferredSize(new Dimension(250, 250));
example.pane.setBorder(new BevelBorder(BevelBorder.LOWERED));
JFrame frame = new JFrame("Menu Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setJMenuBar(example.menuBar);
frame.getContentPane().add(example.pane, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
}
A Selected Button
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Enumeration;
import javax.swing.AbstractButton;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JToggleButton;
import javax.swing.border.Border;
public class ASelectedButton {
public static void main(String args[]) {
JFrame frame = new JFrame("Radio Buttons");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new GridLayout(0, 1));
Border border = BorderFactory.createTitledBorder("Options");
panel.setBorder(border);
final ButtonGroup group = new ButtonGroup();
AbstractButton abstract1 = new JRadioButton("One");
panel.add(abstract1);
group.add(abstract1);
AbstractButton abstract2 = new JRadioButton("Two");
panel.add(abstract2);
group.add(abstract2);
AbstractButton abstract3 = new JRadioButton("Three");
panel.add(abstract3);
group.add(abstract3);
AbstractButton abstract4 = new JRadioButton("Four");
panel.add(abstract4);
group.add(abstract4);
AbstractButton abstract5 = new JRadioButton("Five");
panel.add(abstract5);
group.add(abstract5);
ActionListener aListener = new ActionListener() {
public void actionPerformed(ActionEvent event) {
Enumeration elements = group.getElements();
while (elements.hasMoreElements()) {
AbstractButton button = (AbstractButton) elements
.nextElement();
if (button.isSelected()) {
System.out.println("The winner is: " + button.getText());
break;
}
}
group.setSelected(null, true);
}
};
JToggleButton button = new JToggleButton("Show Selected");
button.addActionListener(aListener);
Container container = frame.getContentPane();
container.add(panel, BorderLayout.CENTER);
container.add(button, BorderLayout.SOUTH);
frame.setSize(300, 200);
frame.setVisible(true);
}
}
Button Action Sample
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class ButtonActionSample {
public static void main(String args[]) {
JFrame frame = new JFrame("Button Sample");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button = new JButton("Select Me");
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
System.out.println("I was selected.");
}
};
MouseListener mouseListener = new MouseAdapter() {
public void mousePressed(MouseEvent mouseEvent) {
int modifiers = mouseEvent.getModifiers();
if ((modifiers & InputEvent.BUTTON1_MASK) == InputEvent.BUTTON1_MASK) {
// Mask may not be set properly prior to Java 2
// See SwingUtilities.isLeftMouseButton() for workaround
System.out.println("Left button pressed.");
}
if ((modifiers & InputEvent.BUTTON2_MASK) == InputEvent.BUTTON2_MASK) {
System.out.println("Middle button pressed.");
}
if ((modifiers & InputEvent.BUTTON3_MASK) == InputEvent.BUTTON3_MASK) {
System.out.println("Right button pressed.");
}
}
public void mouseReleased(MouseEvent mouseEvent) {
if (SwingUtilities.isLeftMouseButton(mouseEvent)) {
System.out.println("Left button released.");
}
if (SwingUtilities.isMiddleMouseButton(mouseEvent)) {
System.out.println("Middle button released.");
}
if (SwingUtilities.isRightMouseButton(mouseEvent)) {
System.out.println("Right button released.");
}
System.out.println();
}
};
button.addActionListener(actionListener);
button.addMouseListener(mouseListener);
Container contentPane = frame.getContentPane();
contentPane.add(button, BorderLayout.SOUTH);
frame.setSize(300, 100);
frame.setVisible(true);
}
}
Button action to change the panel background
import java.awt.Color;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class ButtonSettingBackground extends JPanel implements ActionListener {
private JButton yellowButton = new JButton("Yellow");
private JButton blueButton = new JButton("Blue");
private JButton redButton = new JButton("Red");
public ButtonSettingBackground() {
add(yellowButton);
add(blueButton);
add(redButton);
yellowButton.addActionListener(this);
blueButton.addActionListener(this);
redButton.addActionListener(this);
}
public void actionPerformed(ActionEvent evt) {
Object source = evt.getSource();
Color color = getBackground();
if (source == yellowButton)
color = Color.yellow;
else if (source == blueButton)
color = Color.blue;
else if (source == redButton)
color = Color.red;
setBackground(color);
repaint();
}
public static void main(String[] args) {
JFrame frame = new JFrame("ButtonTest");
frame.setSize(300, 200);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
Container contentPane = frame.getContentPane();
contentPane.add(new ButtonSettingBackground());
frame.show();
}
}
Button demo: Mnemonic, alignment and action command
import javax.swing.AbstractButton;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.ImageIcon;
import javax.swing.Icon;
import java.awt.Color;
import java.awt.ruponent;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
public class ButtonDemo extends JPanel implements ActionListener {
protected JButton b1, b2, b3;
public ButtonDemo() {
Icon middleButtonIcon = new SquareIcon();
b1 = new JButton("Disable middle button");
b1.setVerticalTextPosition(AbstractButton.CENTER);
b1.setHorizontalTextPosition(AbstractButton.LEADING);
b1.setMnemonic(KeyEvent.VK_D);
b1.setActionCommand("disable");
b2 = new JButton("Middle button", middleButtonIcon);
b2.setVerticalTextPosition(AbstractButton.BOTTOM);
b2.setHorizontalTextPosition(AbstractButton.CENTER);
b2.setMnemonic(KeyEvent.VK_M);
b3 = new JButton("Enable middle button");
//Use the default text position of CENTER, TRAILING (RIGHT).
b3.setMnemonic(KeyEvent.VK_E);
b3.setActionCommand("enable");
b3.setEnabled(false);
//Listen for actions on buttons 1 and 3.
b1.addActionListener(this);
b3.addActionListener(this);
b1.setToolTipText("Click this button to disable the middle button.");
b2.setToolTipText("This middle button does nothing when you click it.");
b3.setToolTipText("Click this button to enable the middle button.");
//Add Components to this container, using the default FlowLayout.
add(b1);
add(b2);
add(b3);
}
public void actionPerformed(ActionEvent e) {
if ("disable".equals(e.getActionCommand())) {
b2.setEnabled(false);
b1.setEnabled(false);
b3.setEnabled(true);
} else {
b2.setEnabled(true);
b1.setEnabled(true);
b3.setEnabled(false);
}
}
private static void createAndShowGUI() {
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("ButtonDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ButtonDemo newContentPane = new ButtonDemo();
newContentPane.setOpaque(true); //content panes must be opaque
frame.setContentPane(newContentPane);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
createAndShowGUI();
}
class SquareIcon implements Icon {
private static final int SIZE = 10;
public void paintIcon(Component c, Graphics g, int x, int y) {
if (c.isEnabled()) {
g.setColor(Color.RED);
} else {
g.setColor(Color.GRAY);
}
g.fillRect(x, y, SIZE, SIZE);
}
public int getIconWidth() {
return SIZE;
}
public int getIconHeight() {
return SIZE;
}
}
}
Button Html Demo
/* From http://java.sun.ru/docs/books/tutorial/index.html */
/*
* Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* -Redistribution of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* -Redistribution in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed, licensed or intended
* for use in the design, construction, operation or maintenance of any
* nuclear facility.
*/
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.AbstractButton;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
/*
* ButtonHtmlDemo.java is a 1.4 application that uses the following files:
* images/right.gif images/middle.gif images/left.gif
*/
public class ButtonHtmlDemo extends JPanel implements ActionListener {
protected JButton b1, b2, b3;
public ButtonHtmlDemo() {
ImageIcon leftButtonIcon = createImageIcon("images/right.gif");
ImageIcon middleButtonIcon = createImageIcon("images/middle.gif");
ImageIcon rightButtonIcon = createImageIcon("images/left.gif");
b1 = new JButton("<html><center><b><u>D</u>isable</b><br>"
+ "<font color=#ffffdd>middle button</font>", leftButtonIcon);
Font font = b1.getFont().deriveFont(Font.PLAIN);
b1.setFont(font);
b1.setVerticalTextPosition(AbstractButton.CENTER);
b1.setHorizontalTextPosition(AbstractButton.LEADING); //aka LEFT, for
// left-to-right
// locales
b1.setMnemonic(KeyEvent.VK_D);
b1.setActionCommand("disable");
b2 = new JButton("middle button", middleButtonIcon);
b2.setFont(font);
b2.setForeground(new Color(0xffffdd));
b2.setVerticalTextPosition(AbstractButton.BOTTOM);
b2.setHorizontalTextPosition(AbstractButton.CENTER);
b2.setMnemonic(KeyEvent.VK_M);
b3 = new JButton("<html><center><b><u>E</u>nable</b><br>"
+ "<font color=#ffffdd>middle button</font>", rightButtonIcon);
b3.setFont(font);
//Use the default text position of CENTER, TRAILING (RIGHT).
b3.setMnemonic(KeyEvent.VK_E);
b3.setActionCommand("enable");
b3.setEnabled(false);
//Listen for actions on buttons 1 and 3.
b1.addActionListener(this);
b3.addActionListener(this);
b1.setToolTipText("Click this button to disable the middle button.");
b2.setToolTipText("This middle button does nothing when you click it.");
b3.setToolTipText("Click this button to enable the middle button.");
//Add Components to this container, using the default FlowLayout.
add(b1);
add(b2);
add(b3);
}
public void actionPerformed(ActionEvent e) {
if ("disable".equals(e.getActionCommand())) {
b2.setEnabled(false);
b1.setEnabled(false);
b3.setEnabled(true);
} else {
b2.setEnabled(true);
b1.setEnabled(true);
b3.setEnabled(false);
}
}
/** Returns an ImageIcon, or null if the path was invalid. */
protected static ImageIcon createImageIcon(String path) {
java.net.URL imgURL = ButtonHtmlDemo.class.getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL);
} else {
System.err.println("Couldn"t find file: " + path);
return null;
}
}
/**
* Create the GUI and show it. For thread safety, this method should be
* invoked from the event-dispatching thread.
*/
private static void createAndShowGUI() {
//Make sure we have nice window decorations.
JFrame.setDefaultLookAndFeelDecorated(true);
//Create and set up the window.
JFrame frame = new JFrame("ButtonHtmlDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
ButtonHtmlDemo newContentPane = new ButtonHtmlDemo();
newContentPane.setOpaque(true); //content panes must be opaque
frame.setContentPane(newContentPane);
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application"s GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
Button icons, a default button, HTML in a button,and button mnemonics.
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
public class Main {
public static void main(String args[]) {
ImageIcon iconA = new ImageIcon("IconA.gif");
ImageIcon iconDiable = new ImageIcon("disable.gif");
ImageIcon iconOver = new ImageIcon("over.gif");
ImageIcon iconPressed = new ImageIcon("IconAPressed.gif");
final JButton jbtnA = new JButton("Alpha", iconA);
JFrame jfrm = new JFrame();
jfrm.setLayout(new FlowLayout());
jfrm.setSize(300, 300);
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jbtnA.setRolloverIcon(iconOver);
jbtnA.setPressedIcon(iconPressed);
jbtnA.setDisabledIcon(iconDiable);
jfrm.getRootPane().setDefaultButton(jbtnA);
jbtnA.setMnemonic(KeyEvent.VK_A);
jbtnA.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
System.out.println("Alpha pressed. Beta is enabled.");
jbtnA.setEnabled(!jbtnA.isEnabled());
}
});
jfrm.add(jbtnA);
jfrm.setVisible(true);
}
}
Button with ICON and Multiline
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.KeyEvent;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
public class ButtonSample {
public static void main(String args[]) {
String title = "JButton Sample";
JFrame frame = new JFrame(title);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container content = frame.getContentPane();
content.setLayout(new GridLayout(2, 2));
JButton button1 = new JButton("Text Button");
button1.setMnemonic(KeyEvent.VK_B);
content.add(button1);
Icon warnIcon = new ImageIcon("Warn.gif");
JButton button2 = new JButton(warnIcon);
content.add(button2);
JButton button3 = new JButton("Warning", warnIcon);
content.add(button3);
String htmlButton = "<html><sup>HTML</sup> <sub><em>Button</em></sub><br>" +
"<font color=\"#FF0080\"><u>Multi-line</u></font>";
JButton button4 = new JButton(htmlButton);
content.add(button4);
frame.setSize(300, 200);
frame.setVisible(true);
}
}
Changing the Label of a JButton Component
import javax.swing.JButton;
public class Main {
public static void main(String[] argv) throws Exception {
JButton button = new JButton();
// Change the label
button.setText("New Label");
// Remove the label; this is useful for a button with only an icon
button.setText(null);
}
}
Create a JButton that does not show focus
//Create a JButton that does not show focus, does not paint a border, and
//displays different icons when rolled-over and pressed.
import java.awt.Container;
import java.awt.FlowLayout;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
public class FancyButton extends JButton {
public FancyButton(Icon icon, Icon pressed, Icon rollover) {
super(icon);
setFocusPainted(false);
setRolloverEnabled(true);
setRolloverIcon(rollover);
setPressedIcon(pressed);
setBorderPainted(false);
setContentAreaFilled(false);
}
public static void main(String[] args) {
FancyButton b1 = new FancyButton(new ImageIcon("1.gif"),new ImageIcon("2.gif"), new ImageIcon("3.gif"));
FancyButton b2 = new FancyButton(new ImageIcon("4.gif"),new ImageIcon("1.gif"), new ImageIcon("2.gif"));
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container c = f.getContentPane();
c.setLayout(new FlowLayout());
c.add(b1);
c.add(b2);
f.pack();
f.setVisible(true);
}
}
Creating a JButton Component from Action
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
public class Main {
public static void main(String[] argv) throws Exception {
Action action = new AbstractAction("Button Label") {
// This method is called when the button is pressed
public void actionPerformed(ActionEvent evt) {
// Perform action...
}
};
// Create the button from the action
JButton button = new JButton(action);
}
}
Creating a Multiline Label for a JButton Component
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
public class Main {
public static void main(String[] argv) throws Exception {
String label = "<html>" + "This is a" + "<br>" + "swing button" + "</html>";
// Create an action with the label
Action action = new AbstractAction(label) {
// This method is called when the button is pressed
public void actionPerformed(ActionEvent evt) {
// Perform action
}
};
// Create the button
JButton button = new JButton(action);
}
}
Demonstration of button events including Action, Item and Change event types
//A simple demonstration of button events including Action, Item and Change event types.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class JButtonEvents {
public static void main(String[] args) {
JButton jb = new JButton("Press Me");
jb.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ev) {
System.out.println("ActionEvent!");
}
});
jb.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent ev) {
System.out.println("ItemEvent!");
}
});
jb.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ev) {
System.out.println("ChangeEvent!");
}
});
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(jb);
f.pack();
f.setVisible(true);
}
}
Displaying a Button with a Border
import java.awt.BorderLayout;
import java.awt.Container;
import javax.swing.BorderFactory;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.border.Border;
public class ButtonBorderTest {
public static void main(String args[]) {
JFrame frame = new JFrame("Fourth Button");
Container contentPane = frame.getContentPane();
Icon icon = new ImageIcon("jexp.gif");
JButton b = new JButton("Button!");
Border bored = BorderFactory.createMatteBorder(10, 5, 10, 5, icon);
b.setBorder(bored);
contentPane.add(b, BorderLayout.CENTER);
frame.setSize(350, 200);
frame.show();
}
}
Displaying a Button with an Icon Label
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.ruponent;
import java.awt.Container;
import java.awt.Graphics;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JFrame;
public class ButtonIconTest {
static class PieIcon implements Icon {
Color color;
public PieIcon(Color c) {
color = c;
}
public int getIconWidth() {
return 20;
}
public int getIconHeight() {
return 20;
}
public void paintIcon(Component c, Graphics g, int x, int y) {
g.setColor(color);
g.fillArc(x, y, getIconWidth(), getIconHeight(), 45, 270);
}
}
public static void main(String args[]) {
JFrame frame = new JFrame("");
Container contentPane = frame.getContentPane();
Icon icon = new PieIcon(Color.red);
JButton b = new JButton("Button!", icon);
contentPane.add(b, BorderLayout.NORTH);
b = new JButton(icon);
contentPane.add(b, BorderLayout.SOUTH);
frame.setSize(300, 200);
frame.show();
}
}
Displaying a Button with Various Label Alignments
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.ruponent;
import java.awt.Container;
import java.awt.Graphics;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JFrame;
public class MovingIconTest {
static class PieIcon implements Icon {
Color color;
public PieIcon(Color c) {
color = c;
}
public int getIconWidth() {
return 20;
}
public int getIconHeight() {
return 20;
}
public void paintIcon(Component c, Graphics g, int x, int y) {
g.setColor(color);
g.fillArc(x, y, getIconWidth(), getIconHeight(), 45, 270);
}
}
public static void main(String args[]) {
JFrame frame = new JFrame();
Container contentPane = frame.getContentPane();
JButton b;
Icon icon = new PieIcon(Color.red);
b = new JButton("Default", icon);
contentPane.add(b, BorderLayout.NORTH);
b = new JButton("Text Left", icon);
b.setHorizontalTextPosition(JButton.LEFT);
contentPane.add(b, BorderLayout.SOUTH);
b = new JButton("Text Up", icon);
b.setHorizontalTextPosition(JButton.CENTER);
b.setVerticalTextPosition(JButton.TOP);
contentPane.add(b, BorderLayout.EAST);
b = new JButton("Text Down", icon);
b.setHorizontalTextPosition(JButton.CENTER);
b.setVerticalTextPosition(JButton.BOTTOM);
contentPane.add(b, BorderLayout.WEST);
b = new JButton("Align Bottom Left", icon);
b.setHorizontalAlignment(JButton.LEFT);
b.setVerticalAlignment(JButton.BOTTOM);
contentPane.add(b, BorderLayout.CENTER);
frame.setSize(300, 200);
frame.show();
}
}
Displaying a Button with Varying Icons
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.ruponent;
import java.awt.Container;
import java.awt.Graphics;
import java.awt.Polygon;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JFrame;
public class ChangingButtonIconTest {
static class TriangleIcon implements Icon {
String name;
static class State {
public static final int NORMAL = 0;
public static final int PRESSED = 1;
public static final int ROLLOVER = 2;
private State() {
}
}
int state;
Color color;
public TriangleIcon(Color c, int state) {
color = c;
this.state = state;
}
public int getIconWidth() {
return 20;
}
public int getIconHeight() {
return 20;
}
public void paintIcon(Component c, Graphics g, int x, int y) {
g.setColor(color);
Polygon p = new Polygon();
if (state == State.NORMAL) {
p.addPoint(x + (getIconWidth() / 2), y);
p.addPoint(x, y + getIconHeight() - 1);
p.addPoint(x + getIconWidth() - 1, y + getIconHeight() - 1);
} else if (state == State.PRESSED) {
p.addPoint(x, y);
p.addPoint(x + getIconWidth() - 1, y);
p.addPoint(x + (getIconWidth() / 2), y + getIconHeight() - 1);
} else {
p.addPoint(x, y);
p.addPoint(x, y + getIconHeight() - 1);
p.addPoint(x + getIconWidth() - 1, y + (getIconHeight() / 2));
}
g.fillPolygon(p);
}
}
public static void main(String args[]) {
JFrame frame = new JFrame();
Container contentPane = frame.getContentPane();
Icon normalIcon = new TriangleIcon(Color.red, TriangleIcon.State.NORMAL);
Icon pressedIcon = new TriangleIcon(Color.red,
TriangleIcon.State.PRESSED);
Icon rolloverIcon = new TriangleIcon(Color.red,
TriangleIcon.State.ROLLOVER);
JButton b = new JButton("Button", normalIcon);
b.setPressedIcon(pressedIcon);
b.setRolloverIcon(rolloverIcon);
b.setRolloverEnabled(true);
contentPane.add(b, BorderLayout.NORTH);
frame.setSize(300, 100);
frame.show();
}
}
Display Message
/*
* This example is from the book "Java Foundation Classes in a Nutshell".
* Written by David Flanagan. Copyright (c) 1999 by O"Reilly & Associates.
* You may distribute this source code for non-commercial purposes only.
* You may study, modify, and use this example for any purpose, as long as
* this notice is retained. Note that this example is provided "as is",
* WITHOUT WARRANTY of any kind either expressed or implied.
*/
import java.awt.*; // AWT classes
import javax.swing.*; // Swing components and classes
import javax.swing.border.*; // Borders for Swing components
import java.awt.event.*; // Basic event handling
public class DisplayMessage {
public static void main(String[] args) {
/*
* Step 1: Create the components
*/
JLabel msgLabel = new JLabel(); // Component to display the question
JButton yesButton = new JButton(); // Button for an affirmative response
JButton noButton = new JButton(); // Button for a negative response
/*
* Step 2: Set properties of the components
*/
msgLabel.setText(args[0]); // The msg to display
msgLabel.setBorder(new EmptyBorder(10,10,10,10)); // A 10-pixel margin
yesButton.setText((args.length >= 2)?args[1]:"Yes"); // Text for Yes button
noButton.setText((args.length >= 3)?args[2]:"No"); // Text for no button
/*
* Step 3: Create containers to hold the components
*/
JFrame win = new JFrame("Message"); // The main application window
JPanel buttonbox = new JPanel(); // A container for the two buttons
/*
* Step 4: Specify LayoutManagers to arrange components in the containers
*/
win.getContentPane().setLayout(new BorderLayout()); // layout on borders
buttonbox.setLayout(new FlowLayout()); // layout left-to-right
/*
* Step 5: Add components to containers, with optional layout constraints
*/
buttonbox.add(yesButton); // add yes button to the panel
buttonbox.add(noButton); // add no button to the panel
// add JLabel to window, telling the BorderLayout to put it in the middle
win.getContentPane().add(msgLabel, "Center");
// add panel to window, telling the BorderLayout to put it at the bottom
win.getContentPane().add(buttonbox, "South");
/*
* Step 6: Arrange to handle events in the user interface.
*/
yesButton.addActionListener(new ActionListener() { // Note: inner class
// This method is called when the Yes button is clicked.
public void actionPerformed(ActionEvent e) { System.exit(0); }
});
noButton.addActionListener(new ActionListener() { // Note: inner class
// This method is called when the No button is clicked.
public void actionPerformed(ActionEvent e) { System.exit(1); }
});
/*
* Step 7: Display the GUI to the user
*/
win.pack(); // Set the size of the window based its children"s sizes.
win.show(); // Make the window visible.
}
}
Dynamically update the appearance of a component
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class Main extends JFrame {
final JButton b = new JButton("Add");
int size = 10;
public Main() {
setSize(300, 150);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout());
add(b);
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ev) {
b.setFont(new Font("Dialog", Font.PLAIN, ++size));
b.revalidate();
}
});
setVisible(true);
}
public static void main(String[] args) {
new Main();
}
}
HTML button
import java.awt.FlowLayout;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class HtmlButtons extends JFrame {
public HtmlButtons() {
super("HTML Buttons");
setSize(400, 300);
getContentPane().setLayout(new FlowLayout());
String htmlText = "<html><p><font color=\"#800080\" "
+ "size=\"4\" face=\"Verdana\">JButton</font> </p>"
+ "<font size=\"2\"><em>" + "with HTML text</em></font></html>";
JButton btn = new JButton(htmlText);
getContentPane().add(btn);
WindowListener wndCloser = new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
};
addWindowListener(wndCloser);
setVisible(true);
}
public static void main(String args[]) {
new HtmlButtons();
}
}
If the action does not have an icon or a different icon must be used, add or change the icon using setIcon():
import javax.swing.ImageIcon;
import javax.swing.JButton;
public class Main {
public static void main(String[] argv) throws Exception {
JButton button = new JButton();
// Add or change the icon; it will appear to the left of the text
button.setIcon(new ImageIcon("icon.gif"));
// Set to null to remove icon
button.setIcon(null);
}
}
JToggleButton Demo
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.AbstractButton;
import javax.swing.ButtonModel;
import javax.swing.JFrame;
import javax.swing.JToggleButton;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class SelectingToggle {
public static void main(String args[]) {
String title = (args.length == 0 ? "Selecting Toggle" : args[0]);
JFrame frame = new JFrame(title);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JToggleButton toggleButton = new JToggleButton("Selected");
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
AbstractButton abstractButton = (AbstractButton) actionEvent.getSource();
boolean selected = abstractButton.getModel().isSelected();
System.out.println("Action - selected=" + selected + "\n");
}
};
ChangeListener changeListener = new ChangeListener() {
public void stateChanged(ChangeEvent changeEvent) {
AbstractButton abstractButton = (AbstractButton) changeEvent
.getSource();
ButtonModel buttonModel = abstractButton.getModel();
boolean armed = buttonModel.isArmed();
boolean pressed = buttonModel.isPressed();
boolean selected = buttonModel.isSelected();
System.out.println("Changed: " + armed + "/" + pressed + "/"
+ selected);
}
};
ItemListener itemListener = new ItemListener() {
public void itemStateChanged(ItemEvent itemEvent) {
int state = itemEvent.getStateChange();
if (state == ItemEvent.SELECTED) {
System.out.println("Selected");
} else {
System.out.println("Deselected");
}
}
};
// Attach Listeners
toggleButton.addActionListener(actionListener);
toggleButton.addChangeListener(changeListener);
toggleButton.addItemListener(itemListener);
Container contentPane = frame.getContentPane();
contentPane.add(toggleButton, BorderLayout.NORTH);
JToggleButton toggleButton2 = new JToggleButton("Focused");
contentPane.add(toggleButton2, BorderLayout.CENTER);
JToggleButton toggleButton3 = new JToggleButton("Not Selected");
contentPane.add(toggleButton3, BorderLayout.SOUTH);
frame.setSize(300, 125);
frame.setVisible(true);
}
}
Label text italicizes the second line
import javax.swing.JButton;
public class Main {
public static void main(String[] argv) throws Exception {
JButton button = new JButton();
button.setText("<html>" + "This is a" + "<br><i>" + "swing button"
+ "</i></html>");
}
}
Lines are left justified. This label text will center the lines
import javax.swing.JButton;
public class Main {
public static void main(String[] argv) throws Exception {
JButton button = new JButton();
button.setText("<html><center>" + "This is a" + "<br>" + "swing button"
+ "</center></html>");
}
}
LoadSave: Button action
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.io.FileReader;
import java.io.FileWriter;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.text.JTextComponent;
public class LoadSave {
public static void main(String args[]) {
final String filename = "text.out";
JFrame frame = new JFrame("Loading/Saving Example");
Container content = frame.getContentPane();
final JTextField textField = new JTextField();
content.add(textField, BorderLayout.NORTH);
JPanel panel = new JPanel();
Action loadAction = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
try {
doLoadCommand(textField, filename);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
};
loadAction.putValue(Action.NAME, "Load");
JButton loadButton = new JButton(loadAction);
panel.add(loadButton);
Action saveAction = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
try {
doSaveCommand(textField, filename);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
};
saveAction.putValue(Action.NAME, "Save");
JButton saveButton = new JButton(saveAction);
panel.add(saveButton);
Action clearAction = new AbstractAction() {
{
putValue(Action.NAME, "Clear");
}
public void actionPerformed(ActionEvent e) {
textField.setText("");
}
};
JButton clearButton = new JButton(clearAction);
panel.add(clearButton);
content.add(panel, BorderLayout.SOUTH);
frame.setSize(250, 150);
frame.setVisible(true);
}
public static void doSaveCommand(JTextComponent textComponent, String filename) throws Exception {
FileWriter writer = null;
writer = new FileWriter(filename);
textComponent.write(writer);
writer.close();
}
public static void doLoadCommand(JTextComponent textComponent, String filename) throws Exception {
FileReader reader = null;
reader = new FileReader(filename);
textComponent.read(reader, filename);
reader.close();
}
}
Mnemonic Sample
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.KeyEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
public class MnemonicSample {
public static void main(String args[]) {
JFrame frame = new JFrame("Mnemonics");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container content = frame.getContentPane();
content.setLayout(new GridLayout(1, 0));
JButton button1 = new JButton("Warning");
button1.setMnemonic(KeyEvent.VK_W);
content.add(button1);
JButton button2 = new JButton("Warning");
button2.setMnemonic(KeyEvent.VK_H);
content.add(button2);
frame.setSize(300, 200);
frame.setVisible(true);
}
}
Moving the Icon in a JButton Component
import javax.swing.JButton;
import javax.swing.SwingConstants;
public class Main {
public static void main(String[] argv) throws Exception {
JButton button = new JButton();
// Place text over center of icon; they both occupy the same space
button.setVerticalTextPosition(SwingConstants.CENTER);
button.setHorizontalTextPosition(SwingConstants.CENTER);
// Place text above icon
button.setVerticalTextPosition(SwingConstants.TOP);
button.setHorizontalTextPosition(SwingConstants.CENTER);
// Place text below icon
button.setVerticalTextPosition(SwingConstants.BOTTOM);
button.setHorizontalTextPosition(SwingConstants.CENTER);
// Place text to the left of icon, vertically centered
button.setVerticalTextPosition(SwingConstants.CENTER);
button.setHorizontalTextPosition(SwingConstants.LEFT);
// Place text to the left of icon and align their tops
button.setVerticalTextPosition(SwingConstants.TOP);
button.setHorizontalTextPosition(SwingConstants.LEFT);
// Place text to the left of icon and align their bottoms
button.setVerticalTextPosition(SwingConstants.BOTTOM);
button.setHorizontalTextPosition(SwingConstants.LEFT);
// Place text to the right of icon, vertically centered
button.setVerticalTextPosition(SwingConstants.CENTER);
button.setHorizontalTextPosition(SwingConstants.RIGHT);
// Place text to the right of icon and align their tops
button.setVerticalTextPosition(SwingConstants.TOP);
button.setHorizontalTextPosition(SwingConstants.RIGHT);
// Place text to the right of icon and align their bottoms
button.setVerticalTextPosition(SwingConstants.BOTTOM);
button.setHorizontalTextPosition(SwingConstants.RIGHT);
}
}
Moving the Label/Icon Pair in a JButton Component
import javax.swing.JButton;
import javax.swing.SwingConstants;
public class Main {
public static void main(String[] argv) throws Exception {
JButton button = new JButton();
// Place the contents in the northwest corner
button.setVerticalAlignment(SwingConstants.TOP);
button.setHorizontalAlignment(SwingConstants.LEFT);
// Place the contents centered at the top
button.setVerticalAlignment(SwingConstants.TOP);
button.setHorizontalAlignment(SwingConstants.CENTER);
// Place the contents in the northeast corner
button.setVerticalAlignment(SwingConstants.BOTTOM);
button.setHorizontalAlignment(SwingConstants.RIGHT);
// Place the contents in the southwest corner
button.setVerticalAlignment(SwingConstants.BOTTOM);
button.setHorizontalAlignment(SwingConstants.LEFT);
// Place the contents centered at the bottom
button.setVerticalAlignment(SwingConstants.BOTTOM);
button.setHorizontalAlignment(SwingConstants.CENTER);
// Place the contents in the southeast corner
button.setVerticalAlignment(SwingConstants.BOTTOM);
button.setHorizontalAlignment(SwingConstants.RIGHT);
// Place the contents vertically centered on the left
button.setVerticalAlignment(SwingConstants.CENTER);
button.setHorizontalAlignment(SwingConstants.LEFT);
// Place the contents directly in the center
button.setVerticalAlignment(SwingConstants.CENTER);
button.setHorizontalAlignment(SwingConstants.CENTER);
// Place the contents vertically centered on the right
button.setVerticalAlignment(SwingConstants.CENTER);
button.setHorizontalAlignment(SwingConstants.RIGHT);
}
}
Putting buttons on an applet
// : c14:Button1.java
// Putting buttons on an applet.
// <applet code=Button1 width=200 height=50></applet>
// From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002
// www.BruceEckel.ru. See copyright notice in CopyRight.txt.
import java.awt.Container;
import java.awt.FlowLayout;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JFrame;
public class Button1 extends JApplet {
private JButton b1 = new JButton("Button 1"), b2 = new JButton("Button 2");
public void init() {
Container cp = getContentPane();
cp.setLayout(new FlowLayout());
cp.add(b1);
cp.add(b2);
}
public static void main(String[] args) {
run(new Button1(), 200, 50);
}
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);
}
} ///:~
Responding to button presses
// : c14:Button2.java
// Responding to button presses.
// <applet code=Button2 width=200 height=75></applet>
// From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002
// www.BruceEckel.ru. See copyright notice in CopyRight.txt.
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class Button2 extends JApplet {
private JButton b1 = new JButton("Button 1"), b2 = new JButton("Button 2");
private JTextField txt = new JTextField(10);
class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String name = ((JButton) e.getSource()).getText();
txt.setText(name);
}
}
private ButtonListener bl = new ButtonListener();
public void init() {
b1.addActionListener(bl);
b2.addActionListener(bl);
Container cp = getContentPane();
cp.setLayout(new FlowLayout());
cp.add(b1);
cp.add(b2);
cp.add(txt);
}
public static void main(String[] args) {
run(new Button2(), 200, 75);
}
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);
}
} ///:~
Setting the Gap Size Between the Label and Icon in a JButton Component
import javax.swing.JButton;
public class Main {
public static void main(String[] argv) throws Exception {
JButton button = new JButton();
// Get gap size; default is 4
int gapSize = button.getIconTextGap();
// Set gap size
button.setIconTextGap(8);
}
}
Sharing an Action between JButton Components
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.ruponent;
import java.awt.Container;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JToolBar;
public class ActionTester {
static class MyAction extends AbstractAction {
public MyAction(String name, Icon icon) {
super(name, icon);
}
public void actionPerformed(ActionEvent e) {
System.out.println("Selected: " + getValue(Action.NAME));
}
}
public static void main(String args[]) {
JFrame f = new JFrame();
Container pane = f.getContentPane();
Icon icon = new RedOvalIcon();
final Action action = new MyAction("Hello", icon);
// Add tooltip
action.putValue(Action.SHORT_DESCRIPTION, "World");
JToolBar jt1 = new JToolBar();
JButton b1 = new JButton(action);
jt1.add(b1);
pane.add(jt1, BorderLayout.NORTH);
JToolBar jt2 = new JToolBar();
JButton b2 = new JButton(action);
jt2.add(b2);
pane.add(jt2, BorderLayout.SOUTH);
JButton jb = new JButton("Toggle Action");
jb.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
action.setEnabled(!action.isEnabled());
}
});
pane.add(jb, BorderLayout.CENTER);
f.setSize(200, 200);
f.show();
}
static class RedOvalIcon implements Icon {
public void paintIcon(Component c, Graphics g, int x, int y) {
g.setColor(Color.RED);
if (c.isEnabled()) {
g.fillOval(x, y, getIconWidth(), getIconHeight());
} else {
g.drawOval(x, y, getIconWidth(), getIconHeight());
}
}
public int getIconWidth() {
return 20;
}
public int getIconHeight() {
return 30;
}
}
}
Sharing Models between Buttons
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonModel;
import javax.swing.JButton;
import javax.swing.JFrame;
public class ButtonModelTesting {
static class MessageActionListener implements ActionListener {
String message;
public MessageActionListener(String msg) {
message = msg;
}
public void actionPerformed(ActionEvent e) {
System.out.println(message);
}
}
public static void main(String args[]) {
JFrame f = new JFrame("Button Model Tester");
JButton jb1 = new JButton("Hello");
ButtonModel bm = jb1.getModel();
JButton jb2 = new JButton("World");
jb2.setModel(bm);
Container c = f.getContentPane();
c.add(jb1, BorderLayout.NORTH);
c.add(jb2, BorderLayout.SOUTH);
jb1.addActionListener(new MessageActionListener("Selected One"));
jb2.addActionListener(new MessageActionListener("Selected Two"));
f.pack();
f.show();
}
}
Simple Button UI
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Insets;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.AbstractButton;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.border.Border;
import javax.swing.plaf.ruponentUI;
import javax.swing.plaf.basic.BasicButtonUI;
public class MyButtonUI extends BasicButtonUI implements java.io.Serializable,
MouseListener, KeyListener {
private final static MyButtonUI m_buttonUI = new MyButtonUI();
protected Border m_borderRaised = UIManager.getBorder("Button.border");
protected Border m_borderLowered = UIManager
.getBorder("Button.borderPressed");
protected Color m_backgroundNormal = UIManager
.getColor("Button.background");
protected Color m_backgroundPressed = UIManager
.getColor("Button.pressedBackground");
protected Color m_foregroundNormal = UIManager
.getColor("Button.foreground");
protected Color m_foregroundActive = UIManager
.getColor("Button.activeForeground");
protected Color m_focusBorder = UIManager.getColor("Button.focusBorder");
public static ComponentUI createUI(JComponent c) {
return m_buttonUI;
}
public void installUI(JComponent c) {
super.installUI(c);
c.addMouseListener(this);
c.addKeyListener(this);
}
public void uninstallUI(JComponent c) {
super.uninstallUI(c);
c.removeMouseListener(this);
c.removeKeyListener(this);
}
public void paint(Graphics g, JComponent c) {
AbstractButton b = (AbstractButton) c;
Dimension d = b.getSize();
g.setFont(c.getFont());
FontMetrics fm = g.getFontMetrics();
g.setColor(b.getForeground());
String caption = b.getText();
int x = (d.width - fm.stringWidth(caption)) / 2;
int y = (d.height + fm.getAscent()) / 2;
g.drawString(caption, x, y);
}
public Dimension getPreferredSize(JComponent c) {
Dimension d = super.getPreferredSize(c);
if (m_borderRaised != null) {
Insets ins = m_borderRaised.getBorderInsets(c);
d.setSize(d.width + ins.left + ins.right, d.height + ins.top
+ ins.bottom);
}
return d;
}
public void mouseClicked(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
JComponent c = (JComponent) e.getComponent();
c.setBorder(m_borderLowered);
c.setBackground(m_backgroundPressed);
}
public void mouseReleased(MouseEvent e) {
JComponent c = (JComponent) e.getComponent();
c.setBorder(m_borderRaised);
c.setBackground(m_backgroundNormal);
}
public void mouseEntered(MouseEvent e) {
JComponent c = (JComponent) e.getComponent();
c.setForeground(m_foregroundActive);
c.repaint();
}
public void mouseExited(MouseEvent e) {
JComponent c = (JComponent) e.getComponent();
c.setForeground(m_foregroundNormal);
c.repaint();
}
public void keyTyped(KeyEvent e) {
}
public void keyPressed(KeyEvent e) {
int code = e.getKeyCode();
if (code == KeyEvent.VK_ENTER || code == KeyEvent.VK_SPACE) {
JComponent c = (JComponent) e.getComponent();
c.setBorder(m_borderLowered);
c.setBackground(m_backgroundPressed);
}
}
public void keyReleased(KeyEvent e) {
int code = e.getKeyCode();
if (code == KeyEvent.VK_ENTER || code == KeyEvent.VK_SPACE) {
JComponent c = (JComponent) e.getComponent();
c.setBorder(m_borderRaised);
c.setBackground(m_backgroundNormal);
}
}
public static void main(String argv[]) {
JFrame f = new JFrame();
f.setSize(400, 300);
f.getContentPane().setLayout(new FlowLayout());
JPanel p = new JPanel();
JButton bt1 = new JButton("Click Me");
bt1.setUI(new MyButtonUI());
p.add(bt1);
f.getContentPane().add(p);
WindowListener wndCloser = new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
};
f.addWindowListener(wndCloser);
f.setVisible(true);
}
}
Simple ToggleButton Sample
import java.awt.BorderLayout;
import java.awt.Container;
import javax.swing.JFrame;
import javax.swing.JToggleButton;
public class ToggleButtonSample {
public static void main(String args[]) {
JFrame f = new JFrame("JToggleButton Sample");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container content = f.getContentPane();
content.add(new JToggleButton("North"), BorderLayout.NORTH);
content.add(new JToggleButton("East"), BorderLayout.EAST);
content.add(new JToggleButton("West"), BorderLayout.WEST);
content.add(new JToggleButton("Center"), BorderLayout.CENTER);
content.add(new JToggleButton("South"), BorderLayout.SOUTH);
f.setSize(300, 200);
f.setVisible(true);
}
}
Swing Button Demo
/* From http://java.sun.ru/docs/books/tutorial/index.html */
/*
* Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* -Redistribution of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* -Redistribution in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed, licensed or intended
* for use in the design, construction, operation or maintenance of any
* nuclear facility.
*/
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.AbstractButton;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
/*
* SwingButtonDemo.java is a 1.4 application that requires the following files:
* images/right.gif images/middle.gif images/left.gif
*/
public class SwingButtonDemo extends JPanel implements ActionListener {
protected JButton b1, b2, b3;
public SwingButtonDemo() {
ImageIcon leftButtonIcon = createImageIcon("images/right.gif");
ImageIcon middleButtonIcon = createImageIcon("images/middle.gif");
ImageIcon rightButtonIcon = createImageIcon("images/left.gif");
b1 = new JButton("Disable middle button", leftButtonIcon);
b1.setVerticalTextPosition(AbstractButton.CENTER);
b1.setHorizontalTextPosition(AbstractButton.LEADING); //aka LEFT, for
// left-to-right
// locales
b1.setMnemonic(KeyEvent.VK_D);
b1.setActionCommand("disable");
b2 = new JButton("Middle button", middleButtonIcon);
b2.setVerticalTextPosition(AbstractButton.BOTTOM);
b2.setHorizontalTextPosition(AbstractButton.CENTER);
b2.setMnemonic(KeyEvent.VK_M);
b3 = new JButton("Enable middle button", rightButtonIcon);
//Use the default text position of CENTER, TRAILING (RIGHT).
b3.setMnemonic(KeyEvent.VK_E);
b3.setActionCommand("enable");
b3.setEnabled(false);
//Listen for actions on buttons 1 and 3.
b1.addActionListener(this);
b3.addActionListener(this);
b1.setToolTipText("Click this button to disable the middle button.");
b2.setToolTipText("This middle button does nothing when you click it.");
b3.setToolTipText("Click this button to enable the middle button.");
//Add Components to this container, using the default FlowLayout.
add(b1);
add(b2);
add(b3);
}
public void actionPerformed(ActionEvent e) {
if ("disable".equals(e.getActionCommand())) {
b2.setEnabled(false);
b1.setEnabled(false);
b3.setEnabled(true);
} else {
b2.setEnabled(true);
b1.setEnabled(true);
b3.setEnabled(false);
}
}
/** Returns an ImageIcon, or null if the path was invalid. */
protected static ImageIcon createImageIcon(String path) {
java.net.URL imgURL = SwingButtonDemo.class.getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL);
} else {
System.err.println("Couldn"t find file: " + path);
return null;
}
}
/**
* Create the GUI and show it. For thread safety, this method should be
* invoked from the event-dispatching thread.
*/
private static void createAndShowGUI() {
//Make sure we have nice window decorations.
JFrame.setDefaultLookAndFeelDecorated(true);
//Create and set up the window.
JFrame frame = new JFrame("SwingButtonDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
SwingButtonDemo newContentPane = new SwingButtonDemo();
newContentPane.setOpaque(true); //content panes must be opaque
frame.setContentPane(newContentPane);
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application"s GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
Swing Default Button
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.KeyEvent;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JRootPane;
public class SwingDefaultButton {
public static void main(String args[]) {
JFrame frame = new JFrame("SwingDefaultButton");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container content = frame.getContentPane();
content.setLayout(new GridLayout(2, 2));
JButton button1 = new JButton("Text Button");
button1.setMnemonic(KeyEvent.VK_B);
content.add(button1);
Icon warnIcon = new ImageIcon("Warn.gif");
JButton button2 = new JButton(warnIcon);
content.add(button2);
JButton button3 = new JButton("Warning", warnIcon);
content.add(button3);
String htmlButton = "<html><sup>HTML</sup> <sub><em>Button</em></sub><br>"
+ "<font color=\"#FF0080\"><u>Multi-line</u></font>";
JButton button4 = new JButton(htmlButton);
content.add(button4);
JRootPane rootPane = frame.getRootPane();
rootPane.setDefaultButton(button2);
frame.setSize(300, 200);
frame.setVisible(true);
}
}
The event demonstration program for JToggleButton
//The event demonstration program for JToggleButton.
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JFrame;
import javax.swing.JToggleButton;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class JToggleButtonEvents {
public static void main(String[] args) {
JToggleButton jtb = new JToggleButton("Press Me");
jtb.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ev) {
System.out.println("ActionEvent!");
}
});
jtb.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent ev) {
System.out.println("ItemEvent!");
}
});
jtb.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ev) {
System.out.println("ChangeEvent!");
}
});
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container c = f.getContentPane();
c.setLayout(new FlowLayout());
c.add(jtb);
f.pack();
f.setVisible(true);
}
}
The Swing-ified button example
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JPanel;
public class ToolbarFrame2 extends Frame {
JButton cutButton, copyButton, pasteButton;
JButton javaButton, macButton, motifButton, winButton;
public ToolbarFrame2() {
setSize(450, 250);
ActionListener printListener = new ActionListener() {
public void actionPerformed(ActionEvent ae) {
System.out.println(ae.getActionCommand());
}
};
// JPanel works similarly to Panel, so we"ll use it
JPanel toolbar = new JPanel();
toolbar.setLayout(new FlowLayout(FlowLayout.LEFT));
cutButton = new JButton("Cut");
cutButton.addActionListener(printListener);
toolbar.add(cutButton);
copyButton = new JButton("Copy");
copyButton.addActionListener(printListener);
toolbar.add(copyButton);
pasteButton = new JButton("Paste");
pasteButton.addActionListener(printListener);
toolbar.add(pasteButton);
add(toolbar, BorderLayout.NORTH); // The new BorderLayout add
JPanel lnfPanel = new JPanel();
macButton = new JButton("Mac");
macButton.addActionListener(printListener);
lnfPanel.add(macButton);
javaButton = new JButton("Metal");
javaButton.addActionListener(printListener);
lnfPanel.add(javaButton);
motifButton = new JButton("Motif");
motifButton.addActionListener(printListener);
lnfPanel.add(motifButton);
winButton = new JButton("Windows");
winButton.addActionListener(printListener);
lnfPanel.add(winButton);
add(lnfPanel, BorderLayout.SOUTH);
}
public static void main(String args[]) {
ToolbarFrame2 tf2 = new ToolbarFrame2();
tf2.setVisible(true);
}
}
Uses reflection to create groups of different types of AbstractButton
// : c14:ButtonGroups.java
// Uses reflection to create groups
// of different types of AbstractButton.
// <applet code=ButtonGroups width=500 height=300></applet>
// From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002
// www.BruceEckel.ru. See copyright notice in CopyRight.txt.
import java.awt.Container;
import java.awt.FlowLayout;
import java.lang.reflect.Constructor;
import javax.swing.AbstractButton;
import javax.swing.ButtonGroup;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JToggleButton;
import javax.swing.border.TitledBorder;
public class ButtonGroups extends JApplet {
private static String[] ids = { "June", "Ward", "Beaver", "Wally", "Eddie",
"Lumpy", };
static JPanel makeBPanel(Class klass, String[] ids) {
ButtonGroup bg = new ButtonGroup();
JPanel jp = new JPanel();
String title = klass.getName();
title = title.substring(title.lastIndexOf(".") + 1);
jp.setBorder(new TitledBorder(title));
for (int i = 0; i < ids.length; i++) {
AbstractButton ab = new JButton("failed");
try {
// Get the dynamic constructor method
// that takes a String argument:
Constructor ctor = klass
.getConstructor(new Class[] { String.class });
// Create a new object:
ab = (AbstractButton) ctor.newInstance(new Object[] { ids[i] });
} catch (Exception ex) {
System.err.println("can"t create " + klass);
}
bg.add(ab);
jp.add(ab);
}
return jp;
}
public void init() {
Container cp = getContentPane();
cp.setLayout(new FlowLayout());
cp.add(makeBPanel(JButton.class, ids));
cp.add(makeBPanel(JToggleButton.class, ids));
cp.add(makeBPanel(JCheckBox.class, ids));
cp.add(makeBPanel(JRadioButton.class, ids));
}
public static void main(String[] args) {
run(new ButtonGroups(), 500, 300);
}
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);
}
} ///:~
Various Swing buttons
// : c14:Buttons.java
// Various Swing buttons.
// <applet code=Buttons width=350 height=100></applet>
// From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002
// www.BruceEckel.ru. See copyright notice in CopyRight.txt.
import java.awt.Container;
import java.awt.FlowLayout;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JToggleButton;
import javax.swing.border.TitledBorder;
import javax.swing.plaf.basic.BasicArrowButton;
public class Buttons extends JApplet {
private JButton jb = new JButton("JButton");
private BasicArrowButton up = new BasicArrowButton(BasicArrowButton.NORTH),
down = new BasicArrowButton(BasicArrowButton.SOUTH),
right = new BasicArrowButton(BasicArrowButton.EAST),
left = new BasicArrowButton(BasicArrowButton.WEST);
public void init() {
Container cp = getContentPane();
cp.setLayout(new FlowLayout());
cp.add(jb);
cp.add(new JToggleButton("JToggleButton"));
cp.add(new JCheckBox("JCheckBox"));
cp.add(new JRadioButton("JRadioButton"));
JPanel jp = new JPanel();
jp.setBorder(new TitledBorder("Directions"));
jp.add(up);
jp.add(down);
jp.add(left);
jp.add(right);
cp.add(jp);
}
public static void main(String[] args) {
run(new Buttons(), 350, 100);
}
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);
}
} ///:~