Java Tutorial/Swing/JButton — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
|
(нет различий)
|
Текущая версия на 04:57, 1 июня 2010
Содержание
- 1 Adding a Disabled Icon to a JButton Component
- 2 Adding a Rollover and Pressed Icon to a JButton Component
- 3 Adding Icon to JButton
- 4 Arrow Button
- 5 Button icons, a default button, HTML in a button,and button mnemonics.
- 6 Buttons used in toolbars.
- 7 Button with user-draw Image icon
- 8 Call button doClick method to simulate a click action
- 9 Change button Horizontal Text Position
- 10 Creating a JButton
- 11 Creating a JButton from an Action object
- 12 Creating a Multiline Label for a JButton Component
- 13 Customizing a JButton Look and Feel
- 14 Displaying HTML on JButton
- 15 Displaying Mnemonics in Button text
- 16 Dynamically update the appearance of a component
- 17 Label text italicizes the second line
- 18 Lines are left justified. This label text will center the lines
- 19 Placing Text and Icon together
- 20 Register two event listeners to JButton
- 21 Set pressed icon
- 22 Set Rollover Icon and set Rollover Enabled
- 23 Setting the Gap Size Between the Label and Icon in a JButton Component
- 24 Set tooltip for button
- 25 Transfer focus from button to button with help of arrows keys.
- 26 Using Mnemonics
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 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);
}
}
Adding Icon to JButton
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
public class IconButton {
public static void main(String args[]) {
JFrame frame = new JFrame("DefaultButton");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Icon warnIcon = new ImageIcon("yourFile.gif");
JButton button2 = new JButton(warnIcon);
frame.add(button2);
frame.setSize(300, 200);
frame.setVisible(true);
}
}
Arrow Button
import javax.swing.*;
import java.awt.*;
/**
* A button which paints on it one or more scaled arrows in one of the cardinal directions.
* @author Adrian BER
*/
public class ArrowButton extends JButton {
/** The cardinal direction of the arrow(s). */
private int direction;
/** The number of arrows. */
private int arrowCount;
/** The arrow size. */
private int arrowSize;
public ArrowButton(int direction, int arrowCount, int arrowSize) {
setMargin(new Insets(0, 2, 0, 2));
setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));
this.direction = direction;
this.arrowCount = arrowCount;
this.arrowSize = arrowSize;
}
/** Returns the cardinal direction of the arrow(s).
* @see #setDirection(int)
*/
public int getDirection() {
return direction;
}
/** Sets the cardinal direction of the arrow(s).
* @param direction the direction of the arrow(s), can be SwingConstants.NORTH,
* SwingConstants.SOUTH, SwingConstants.WEST or SwingConstants.EAST
* @see #getDirection()
*/
public void setDirection(int direction) {
this.direction = direction;
}
/** Returns the number of arrows. */
public int getArrowCount() {
return arrowCount;
}
/** Sets the number of arrows. */
public void setArrowCount(int arrowCount) {
this.arrowCount = arrowCount;
}
/** Returns the arrow size. */
public int getArrowSize() {
return arrowSize;
}
/** Sets the arrow size. */
public void setArrowSize(int arrowSize) {
this.arrowSize = arrowSize;
}
public Dimension getPreferredSize() {
return getMinimumSize();
}
public Dimension getMinimumSize() {
return new Dimension(
arrowSize * (direction == SwingConstants.EAST
|| direction == SwingConstants.WEST ? arrowCount : 3)
+ getBorder().getBorderInsets(this).left
+ getBorder().getBorderInsets(this).right
,
arrowSize * (direction == SwingConstants.NORTH
|| direction == SwingConstants.SOUTH ? arrowCount : 3)
+ getBorder().getBorderInsets(this).top
+ getBorder().getBorderInsets(this).bottom
);
}
public Dimension getMaximumSize() {
return getMinimumSize();
}
protected void paintComponent(Graphics g) {
// this will paint the background
super.paintComponent(g);
Color oldColor = g.getColor();
g.setColor(isEnabled() ? getForeground() : getForeground().brighter());
// paint the arrows
int w = getSize().width;
int h = getSize().height;
for (int i = 0; i < arrowCount; i++) {
paintArrow(g,
(w - arrowSize * (direction == SwingConstants.EAST
|| direction == SwingConstants.WEST ? arrowCount : 1)) / 2
+ arrowSize * (direction == SwingConstants.EAST
|| direction == SwingConstants.WEST ? i : 0),
(h - arrowSize * (direction == SwingConstants.EAST
|| direction == SwingConstants.WEST ? 1 : arrowCount)) / 2
+ arrowSize * (direction == SwingConstants.EAST
|| direction == SwingConstants.WEST ? 0 : i),
g.getColor());
}
g.setColor(oldColor);
}
private void paintArrow(Graphics g, int x, int y, Color highlight) {
int mid, i, j;
Color oldColor = g.getColor();
boolean isEnabled = isEnabled();
j = 0;
arrowSize = Math.max(arrowSize, 2);
mid = (arrowSize / 2) - 1;
g.translate(x, y);
switch (direction) {
case NORTH:
for (i = 0; i < arrowSize; i++) {
g.drawLine(mid - i, i, mid + i, i);
}
if(!isEnabled) {
g.setColor(highlight);
g.drawLine(mid-i+2, i, mid+i, i);
}
break;
case SOUTH:
if (!isEnabled) {
g.translate(1, 1);
g.setColor(highlight);
for (i = arrowSize - 1; i >= 0; i--) {
g.drawLine(mid - i, j, mid + i, j);
j++;
}
g.translate(-1, -1);
g.setColor(oldColor);
}
j = 0;
for (i = arrowSize - 1; i >= 0; i--) {
g.drawLine(mid - i, j, mid + i, j);
j++;
}
break;
case WEST:
for (i = 0; i < arrowSize; i++) {
g.drawLine(i, mid - i, i, mid + i);
}
if(!isEnabled) {
g.setColor(highlight);
g.drawLine(i, mid-i+2, i, mid+i);
}
break;
case EAST:
if(!isEnabled) {
g.translate(1, 1);
g.setColor(highlight);
for(i = arrowSize-1; i >= 0; i--) {
g.drawLine(j, mid-i, j, mid+i);
j++;
}
g.translate(-1, -1);
g.setColor(oldColor);
}
j = 0;
for (i = arrowSize - 1; i >= 0; i--) {
g.drawLine(j, mid - i, j, mid + i);
j++;
}
break;
}
g.translate(-x, -y);
g.setColor(oldColor);
}
}
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);
}
}
Buttons used in toolbars.
/*
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import java.awt.Insets;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JButton;
/**
* This class represents the buttons used in toolbars.
*
* @author
* @version $Id: JToolbarButton.java 498555 2007-01-22 08:09:33Z cam $
*/
public class JToolbarButton extends JButton {
/**
* Creates a new toolbar button.
*/
public JToolbarButton() {
initialize();
}
/**
* Creates a new toolbar button.
* @param txt The button text.
*/
public JToolbarButton(String txt) {
super(txt);
initialize();
}
/**
* Initializes the button.
*/
protected void initialize() {
if (!System.getProperty("java.version").startsWith("1.3")) {
setOpaque(false);
setBackground(new java.awt.Color(0, 0, 0, 0));
}
setBorderPainted(false);
setMargin(new Insets(2, 2, 2, 2));
addMouseListener(new MouseListener());
}
/**
* To manage the mouse interactions.
*/
protected class MouseListener extends MouseAdapter {
public void mouseEntered(MouseEvent ev) {
setBorderPainted(true);
}
public void mouseExited(MouseEvent ev) {
setBorderPainted(false);
}
}
}
Button with user-draw Image icon
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.ruponent;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class ButtonwithImageIcon extends JFrame {
public static void main(String[] args) {
ButtonwithImageIcon that = new ButtonwithImageIcon();
that.setVisible(true);
}
public ButtonwithImageIcon() {
setSize(450, 350);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().add(new ButtonPanel(), BorderLayout.SOUTH);
}
}
class ButtonPanel extends JPanel {
public ButtonPanel() {
JButton btn = new JButton("Push Me", new BoxIcon(Color.blue, 2));
btn.setRolloverIcon(new BoxIcon(Color.cyan, 3));
btn.setPressedIcon(new BoxIcon(Color.yellow, 4));
btn.setHorizontalTextPosition(JButton.LEFT);
btn.setBorder(BorderFactory.createEtchedBorder());
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Button was pressed.");
}
});
add(btn);
}
}
class BoxIcon implements Icon {
private Color color;
private int borderWidth;
BoxIcon(Color color, int borderWidth) {
this.color = color;
this.borderWidth = borderWidth;
}
public int getIconWidth() {
return 20;
}
public int getIconHeight() {
return 20;
}
public void paintIcon(Component c, Graphics g, int x, int y) {
g.setColor(Color.black);
g.fillRect(x, y, getIconWidth(), getIconHeight());
g.setColor(color);
g.fillRect(x + borderWidth, y + borderWidth, getIconWidth() - 2 * borderWidth,
getIconHeight() - 2 * borderWidth);
}
}
Call button doClick method to simulate a click action
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.JOptionPane;
import javax.swing.JPanel;
public class MainClass extends JFrame {
public static void main(String[] args) {
new MainClass();
}
private JButton button1 = new JButton("Click Me!"), exitButton= new JButton("Exit");
public MainClass() {
this.setSize(275, 100);
this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
ClickListener cl = new ClickListener();
JPanel panel1 = new JPanel();
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
exitButton.doClick();
}
});
button1.addActionListener(cl);
panel1.add(button1);
exitButton.addActionListener(cl);
panel1.add(exitButton);
this.add(panel1);
this.setVisible(true);
}
private class ClickListener implements ActionListener {
private int clickCount = 0;
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button1) {
clickCount++;
if (clickCount == 1)
button1.setText("clicked!");
else
button1.setText("clicked " + clickCount + " times!");
} else if (e.getSource() == exitButton) {
if (clickCount > 0)
System.exit(0);
else {
JOptionPane.showMessageDialog(MainClass.this, "You must click at least once!",
"Title", JOptionPane.ERROR_MESSAGE);
}
}
}
}
}
Change button Horizontal Text Position
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
public class SampleButton extends JFrame {
public SampleButton() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel p = new JPanel(new BorderLayout());
p.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
JButton b = new JButton("Test");
b.setHorizontalTextPosition(SwingConstants.LEFT);
b.setIcon(new ImageIcon("r.gif"));
b.setRolloverIcon(new ImageIcon("b.gif"));
b.setRolloverEnabled(true);
b.setMnemonic("t");
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Button pressed");
}
});
p.add(b);
getContentPane().add(p);
pack();
}
public static void main(String[] args) {
SampleButton sb = new SampleButton();
sb.setVisible(true);
}
}
Creating a JButton
public JButton()
JButton button = new JButton();
public JButton(Icon image)
Icon icon = new ImageIcon("dog.jpg");
JButton button = new JButton(icon);
public JButton(String text)
JButton button = new JButton("Dog");
public JButton(String text, Icon icon)
Icon icon = new ImageIcon("dog.jpg");
JButton button = new JButton("Dog", icon);
public JButton(Action action)
Action action = ...;
JButton button = new JButton(action);
Creating a JButton from an Action object
import java.awt.ruponent;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
class ShowAction extends AbstractAction {
Component parentComponent;
public ShowAction(Component parentComponent) {
super("About");
putValue(Action.MNEMONIC_KEY, new Integer(KeyEvent.VK_A));
this.parentComponent = parentComponent;
}
public void actionPerformed(ActionEvent actionEvent) {
JOptionPane.showMessageDialog(parentComponent, "About Swing", "About Box V2.0",
JOptionPane.INFORMATION_MESSAGE);
}
}
public class ContructMenuWithAction {
public static void main(final String args[]) {
JFrame frame = new JFrame("MenuSample Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton bn = new JButton(new ShowAction(frame));
frame.add(bn);
frame.setSize(350, 250);
frame.setVisible(true);
}
}
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);
}
}
Customizing a JButton Look and Feel
Property StringObject TypeButton.actionMapActionMapButton.backgroundColorButton.borderBorderButton.contentAreaFilledBooleanButton.darkShadowColorButton.dashedRectGapHeightIntegerButton.dashedRectGapWidthIntegerButton.dashedRectGapXIntegerButton.dashedRectGapYIntegerButton.defaultButtonFollowsFocus BooleanButton.disabledForegroundColorButton.disabledGrayRangeInteger[ ]Button.disabledShadowColorButton.disabledTextColorButton.disabledToolBarBorderBackground ColorButton.focusColorButton.focusInputMapInputMapButton.fontFontButton.foregroundColorButton.gradientListButton.highlightColorButton.iconIconButton.iconTextGapIntegerButton.lightColorButton.marginInsetsButton.rolloverBooleanButton.rolloverIconTypeStringButton.selectColorButton.shadowColorButton.showMnemonicsBooleanButton.textIconGapIntegerButton.textShiftOffsetIntegerButton.toolBarBorderBackgroundColorButtonUIString
Displaying HTML on JButton
import javax.swing.JButton;
import javax.swing.JFrame;
public class HTMLButton {
public static void main(String args[]) {
JFrame frame = new JFrame("DefaultButton");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
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);
frame.add(button4);
frame.setSize(300, 200);
frame.setVisible(true);
}
}
Displaying Mnemonics in Button text
import java.awt.event.KeyEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
public class MnemonicButton {
public static void main(String args[]) {
JFrame frame = new JFrame("DefaultButton");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button1 = new JButton("Text Button");
button1.setMnemonic(KeyEvent.VK_B);
frame.add(button1);
frame.setSize(300, 200);
frame.setVisible(true);
}
}
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();
}
}
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>");
}
}
Placing Text and Icon together
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
public class IconTextButton {
public static void main(String args[]) {
JFrame frame = new JFrame("DefaultButton");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Icon warnIcon = new ImageIcon("Warn.gif");
JButton button3 = new JButton("Warning", warnIcon);
frame.add(button3);
frame.setSize(300, 200);
frame.setVisible(true);
}
}
Register two event listeners to JButton
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
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);
}
};
frame.setLayout(new GridLayout(2, 2, 10, 10));
JButton button1 = new JButton("Text Button");
button1.setActionCommand("First");
button1.addActionListener(actionListener);
frame.add(button1);
frame.setSize(300, 200);
frame.setVisible(true);
}
}
Set pressed icon
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JCheckBox;
public class Main {
public static void main(String[] argv) throws Exception {
JCheckBox checkbox = new JCheckBox();
Icon pressedIcon = new ImageIcon("pres-icon.gif");
checkbox.setPressedIcon(pressedIcon);
}
}
Set Rollover Icon and set Rollover Enabled
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
public class MainClass extends JFrame {
public MainClass() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel p = new JPanel(new BorderLayout());
p.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
JButton b = new JButton("Test");
b.setHorizontalTextPosition(SwingConstants.LEFT);
b.setIcon(new ImageIcon("red-ball.gif"));
b.setRolloverIcon(new ImageIcon("blue-ball.gif"));
b.setRolloverEnabled(true);
b.setMnemonic("t");
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Button pressed");
}
});
p.add(b);
getContentPane().add(p);
pack();
}
public static void main(String[] args) {
MainClass sb = new MainClass();
sb.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);
}
}
Set tooltip for button
import javax.swing.JButton;
import javax.swing.JFrame;
public class JButtonWithTooltip extends JFrame {
public JButtonWithTooltip() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton b = new JButton("Test");
b.setToolTipText("Help text for the button");
getContentPane().add(b, "Center");
pack();
}
public static void main(String[] args) {
new JButtonWithTooltip().setVisible(true);
}
}
Transfer focus from button to button with help of arrows keys.
/*
* Copyright 2006 Sun Microsystems, Inc., 4150 Network Circle,
* Santa Clara, California 95054, U.S.A. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
import java.awt.BorderLayout;
import java.awt.ruponent;
import java.awt.Container;
import java.awt.FocusTraversalPolicy;
import java.awt.GridLayout;
import java.awt.KeyboardFocusManager;
import java.awt.LayoutManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import javax.swing.AbstractButton;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.ButtonModel;
import javax.swing.DefaultButtonModel;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.KeyStroke;
import javax.swing.LayoutFocusTraversalPolicy;
import javax.swing.SwingUtilities;
import javax.swing.border.TitledBorder;
/**
* This is a JPanel subclass which provides a special functionality
* for its children buttons components.
* It makes it possible to transfer focus from button to button
* with help of arrows keys.
* <p>The following example shows how to enable cyclic focus transfer
* <pre>
* import org.jdesktop.swinghelper.buttonpanel.*;
* import javax.swing.*;
*
* public class SimpleDemo {
* public static void main(String[] args) throws Exception {
* SwingUtilities.invokeLater(new Runnable() {
* public void run() {
* final JFrame frame = new JFrame();
* frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
*
* JXButtonPanel panel = new JXButtonPanel();
* panel.setCyclic(true);
*
* panel.add(new JButton("One"));
* panel.add(new JButton("Two"));
* panel.add(new JButton("Three"));
*
* frame.add(panel);
* frame.setSize(200, 200);
* frame.setLocationRelativeTo(null);
* frame.setVisible(true);
* }
* });
* }
* }
* </pre>
*
* If your buttons inside JXButtonPanel are added to one ButtonGroup
* arrow keys will transfer selection between them as well as they do it for focus<p>
* Note: you can control this behaviour with setGroupSelectionFollowFocus(boolean)
* <pre>
* import org.jdesktop.swinghelper.buttonpanel.*;
* import javax.swing.*;
*
* public class RadioButtonDemo {
* public static void main(String[] args) throws Exception {
* SwingUtilities.invokeLater(new Runnable() {
* public void run() {
* final JFrame frame = new JFrame();
* frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
*
* JXButtonPanel panel = new JXButtonPanel();
* ButtonGroup group = new ButtonGroup();
*
* JRadioButton rb1 = new JRadioButton("One");
* panel.add(rb1);
* group.add(rb1);
* JRadioButton rb2 = new JRadioButton("Two");
* panel.add(rb2);
* group.add(rb2);
* JRadioButton rb3 = new JRadioButton("Three");
* panel.add(rb3);
* group.add(rb3);
*
* rb1.setSelected(true);
* frame.add(panel);
*
* frame.setSize(200, 200);
* frame.setLocationRelativeTo(null);
* frame.setVisible(true);
* }
* });
* }
* }
* </pre>
*
* @author Alexander Potochkin
*
* https://swinghelper.dev.java.net/
* http://weblogs.java.net/blog/alexfromsun/
*/
public class JXButtonPanel extends JPanel {
private boolean isCyclic;
private boolean isGroupSelectionFollowFocus;
/**
* {@inheritDoc}
*/
public JXButtonPanel() {
super();
init();
}
/**
* {@inheritDoc}
*/
public JXButtonPanel(LayoutManager layout) {
super(layout);
init();
}
/**
* {@inheritDoc}
*/
public JXButtonPanel(boolean isDoubleBuffered) {
super(isDoubleBuffered);
init();
}
/**
* {@inheritDoc}
*/
public JXButtonPanel(LayoutManager layout, boolean isDoubleBuffered) {
super(layout, isDoubleBuffered);
init();
}
private void init() {
setFocusTraversalPolicyProvider(true);
setFocusTraversalPolicy(new JXButtonPanelFocusTraversalPolicy());
ActionListener actionHandler = new ActionHandler();
registerKeyboardAction(actionHandler, ActionHandler.FORWARD,
KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0),
JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
registerKeyboardAction(actionHandler, ActionHandler.FORWARD,
KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0),
JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
registerKeyboardAction(actionHandler, ActionHandler.BACKWARD,
KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0),
JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
registerKeyboardAction(actionHandler, ActionHandler.BACKWARD,
KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0),
JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
setGroupSelectionFollowFocus(true);
}
/**
* Returns whether arrow keys should support
* cyclic focus traversal ordering for for this JXButtonPanel.
*/
public boolean isCyclic() {
return isCyclic;
}
/**
* Sets whether arrow keys should support
* cyclic focus traversal ordering for this JXButtonPanel.
*/
public void setCyclic(boolean isCyclic) {
this.isCyclic = isCyclic;
}
/**
* Returns whether arrow keys should transfer button"s
* selection as well as focus for this JXButtonPanel.<p>
*
* Note: this property affects buttons which are added to a ButtonGroup
*/
public boolean isGroupSelectionFollowFocus() {
return isGroupSelectionFollowFocus;
}
/**
* Sets whether arrow keys should transfer button"s
* selection as well as focus for this JXButtonPanel.<p>
*
* Note: this property affects buttons which are added to a ButtonGroup
*/
public void setGroupSelectionFollowFocus(boolean groupSelectionFollowFocus) {
isGroupSelectionFollowFocus = groupSelectionFollowFocus;
}
private static ButtonGroup getButtonGroup(AbstractButton button) {
ButtonModel model = button.getModel();
if (model instanceof DefaultButtonModel) {
return ((DefaultButtonModel) model).getGroup();
}
return null;
}
private class ActionHandler implements ActionListener {
private static final String FORWARD = "moveSelectionForward";
private static final String BACKWARD = "moveSelectionBackward";
public void actionPerformed(ActionEvent e) {
FocusTraversalPolicy ftp = JXButtonPanel.this.getFocusTraversalPolicy();
if (ftp instanceof JXButtonPanelFocusTraversalPolicy) {
JXButtonPanelFocusTraversalPolicy xftp =
(JXButtonPanelFocusTraversalPolicy) ftp;
String actionCommand = e.getActionCommand();
Component fo =
KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner();
Component next;
xftp.setAlternativeFocusMode(true);
if (FORWARD.equals(actionCommand)) {
next = xftp.getComponentAfter(JXButtonPanel.this, fo);
} else if (BACKWARD.equals(actionCommand)) {
next = xftp.getComponentBefore(JXButtonPanel.this, fo);
} else {
throw new AssertionError("Unexpected action command: " + actionCommand);
}
xftp.setAlternativeFocusMode(false);
if (fo instanceof AbstractButton) {
AbstractButton b = (AbstractButton) fo;
b.getModel().setPressed(false);
}
if (next != null) {
if (fo instanceof AbstractButton && next instanceof AbstractButton) {
ButtonGroup group = getButtonGroup((AbstractButton) fo);
AbstractButton nextButton = (AbstractButton) next;
if (group != getButtonGroup(nextButton)) {
return;
}
if (isGroupSelectionFollowFocus() && group != null &&
group.getSelection() != null && !nextButton.isSelected()) {
nextButton.setSelected(true);
}
next.requestFocusInWindow();
}
}
}
}
}
private class JXButtonPanelFocusTraversalPolicy extends LayoutFocusTraversalPolicy {
private boolean isAlternativeFocusMode;
public boolean isAlternativeFocusMode() {
return isAlternativeFocusMode;
}
public void setAlternativeFocusMode(boolean alternativeFocusMode) {
isAlternativeFocusMode = alternativeFocusMode;
}
protected boolean accept(Component c) {
if (!isAlternativeFocusMode() && c instanceof AbstractButton) {
AbstractButton button = (AbstractButton) c;
ButtonGroup group = JXButtonPanel.getButtonGroup(button);
if (group != null && group.getSelection() != null
&& !button.isSelected()) {
return false;
}
}
return super.accept(c);
}
public Component getComponentAfter(Container aContainer, Component aComponent) {
Component componentAfter = super.getComponentAfter(aContainer, aComponent);
if (!isAlternativeFocusMode()) {
return componentAfter;
}
if (JXButtonPanel.this.isCyclic()) {
return componentAfter == null ?
getFirstComponent(aContainer) : componentAfter;
}
if (aComponent == getLastComponent(aContainer)) {
return aComponent;
}
return componentAfter;
}
public Component getComponentBefore(Container aContainer, Component aComponent) {
Component componentBefore = super.getComponentBefore(aContainer, aComponent);
if (!isAlternativeFocusMode()) {
return componentBefore;
}
if (JXButtonPanel.this.isCyclic()) {
return componentBefore == null ?
getLastComponent(aContainer) : componentBefore;
}
if (aComponent == getFirstComponent(aContainer)) {
return aComponent;
}
return componentBefore;
}
}
}
/**
* @author Alexander Potochkin
*
* https://swinghelper.dev.java.net/
* http://weblogs.java.net/blog/alexfromsun/
*/
class JXButtonPanelDemo extends JFrame {
private ButtonGroup radioGroup = new ButtonGroup();
public JXButtonPanelDemo() {
super("JXButtonPanel demo");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
JPanel topPanel = new JPanel(new GridLayout(1, 0));
final JXButtonPanel radioGroupPanel = createRadioJXButtonPanel();
topPanel.add(radioGroupPanel);
final JXButtonPanel checkBoxPanel = createCheckBoxJXButtonPanel();
topPanel.add(checkBoxPanel);
add(topPanel);
add(createButtonJXButtonPanel(), BorderLayout.SOUTH);
pack();
JMenuBar bar = new JMenuBar();
JMenu menu = new JMenu("Options");
JMenuItem item = new JMenuItem("Unselect radioButtons");
item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, InputEvent.ALT_MASK));
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// hack for 1.5
// in 1.6 ButtonGroup.clearSelection added
JRadioButton b = new JRadioButton();
radioGroup.add(b);
b.setSelected(true);
radioGroup.remove(b);
}
});
menu.add(item);
bar.add(menu);
setJMenuBar(bar);
setSize(300, 300);
setLocationRelativeTo(null);
}
private JXButtonPanel createRadioJXButtonPanel() {
JXButtonPanel panel = new JXButtonPanel();
panel.setLayout(new GridLayout(0, 1));
JRadioButton one = new JRadioButton("One");
panel.add(one);
radioGroup.add(one);
JRadioButton two = new JRadioButton("Two");
panel.add(two);
radioGroup.add(two);
JRadioButton three = new JRadioButton("Three");
panel.add(three);
radioGroup.add(three);
JRadioButton four = new JRadioButton("Four");
panel.add(four);
radioGroup.add(four);
one.setSelected(true);
panel.setBorder(BorderFactory.createTitledBorder("JXButtonPanel"));
return panel;
}
private JXButtonPanel createCheckBoxJXButtonPanel() {
JXButtonPanel panel = new JXButtonPanel();
panel.setLayout(new GridLayout(0, 1));
JCheckBox one = new JCheckBox("One");
panel.add(one);
JCheckBox two = new JCheckBox("Two");
panel.add(two);
JCheckBox three = new JCheckBox("Three");
panel.add(three);
JCheckBox four = new JCheckBox("Four");
panel.add(four);
panel.setBorder(BorderFactory.createTitledBorder("JXButtonPanel"));
return panel;
}
private JPanel createButtonJXButtonPanel() {
JPanel ret = new JPanel(new BorderLayout());
JLabel label = new JLabel("Does JXButtonPanel support arrow keys ?");
label.setBorder(BorderFactory.createEmptyBorder(0, 0, 10, 0));
JPanel temp = new JPanel();
temp.add(label);
ret.add(temp);
JXButtonPanel panel = new JXButtonPanel();
panel.setCyclic(true);
panel.add(new JButton("Yes"));
panel.add(new JButton("Sure"));
panel.add(new JButton("Absolutely !"));
panel.setBorder(BorderFactory.createTitledBorder(null,
"JXButtonPanel.setCyclic(true)",
TitledBorder.CENTER, TitledBorder.BOTTOM));
ret.setBorder(BorderFactory.createEmptyBorder(10, 0, 10, 0));
ret.add(panel, BorderLayout.SOUTH);
return ret;
}
public static void main(String[] args) throws Exception {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new JXButtonPanelDemo().setVisible(true);
}
});
}
}
Using Mnemonics
Mnemonic, one character in a label appears underlined.
import java.awt.event.KeyEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
public class MnemonicButton {
public static void main(String args[]) {
JFrame frame = new JFrame("DefaultButton");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button1 = new JButton("Text Button");
button1.setMnemonic(KeyEvent.VK_B);
frame.add(button1);
frame.setSize(300, 200);
frame.setVisible(true);
}
}