package org.kodejava.swing;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.WindowConstants;
import java.awt.FlowLayout;
public class MultilineToolTip {
public static void main(String[] args) {
JFrame frame = new JFrame("Tool Tip Demo");
frame.setSize(500, 500);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
JLabel label = new JLabel("Hover on me!");
// Setting tool tip for our Swing JLabel component using an html
// formatted string so that we can create a multi lines tool tip.
label.setToolTipText(
"<html>Lorem Ipsum is simply dummy text of the printing and<br/>" +
"typesetting industry. Lorem Ipsum has been the industry's <br/>" +
"standard dummy text ever since the 1500s, when an unknown<br/>" +
"printer took a galley of type and scrambled it to make a<br/>" +
"type specimen book.</html>");
frame.getContentPane().setLayout(new FlowLayout(FlowLayout.CENTER));
frame.getContentPane().add(label);
frame.setVisible(true);
}
}
Tag Archives: Swing
How do I disable/enable application tool tips?
package org.kodejava.swing;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.ToolTipManager;
import javax.swing.WindowConstants;
import java.awt.FlowLayout;
import java.awt.HeadlessException;
public class DisableToolTip extends JFrame {
public DisableToolTip() throws HeadlessException {
initComponent();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new DisableToolTip().setVisible(true));
}
private void initComponent() {
setSize(500, 500);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
getContentPane().setLayout(new FlowLayout(FlowLayout.CENTER));
JButton disable = new JButton("DISABLE");
disable.setToolTipText("Application tool tip will be disabled.");
disable.addActionListener(e -> {
// Disable tool tip for the entire application
ToolTipManager.sharedInstance().setEnabled(false);
});
JButton enable = new JButton("ENABLE");
enable.setToolTipText("Application tool tip will be enabled.");
enable.addActionListener(e -> {
// Enable tool tip for the entire application
ToolTipManager.sharedInstance().setEnabled(true);
});
getContentPane().add(enable);
getContentPane().add(disable);
}
}
How do I set a tool tip for Swing components?
package org.kodejava.swing;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.WindowConstants;
import java.awt.FlowLayout;
public class ToolTipExample {
public static void main(String[] args) {
JFrame frame = new JFrame("Tool Tip Demo");
frame.setSize(500, 500);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
JLabel label = new JLabel("Hover on me!");
// Setting tool tip for our Swing JLabel component
label.setToolTipText("My JLabel Tool Tip");
frame.getContentPane().setLayout(new FlowLayout(FlowLayout.CENTER));
frame.getContentPane().add(label);
frame.setVisible(true);
}
}
How do I create an undecorated JFrame?
This code give you an example of how to create a frame without the title bar, and the frame icons such as maximize, minimize and close.
package org.kodejava.swing;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.BorderLayout;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
public class UndecoratedFrame {
private static Point point = new Point();
public static void main(String[] args) {
final JFrame frame = new JFrame();
// Disables or enables decorations for this frame. By setting undecorated
// to true will remove the frame's title bar including the maximize,
// minimize and the close icon.
frame.setUndecorated(true);
// As the the frame's title bar removed we need to close out frame for
// instance using our own button.
JButton button = new JButton("Close Me");
button.addActionListener(e -> System.exit(0));
// The mouse listener and mouse motion listener we add here is to simply
// make our frame draggable.
frame.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
point.x = e.getX();
point.y = e.getY();
}
});
frame.addMouseMotionListener(new MouseMotionAdapter() {
public void mouseDragged(MouseEvent e) {
Point p = frame.getLocation();
frame.setLocation(p.x + e.getX() - point.x, p.y + e.getY() - point.y);
}
});
frame.setSize(500, 500);
frame.setLocation(200, 200);
frame.setLayout(new BorderLayout());
frame.getContentPane().add(button, BorderLayout.NORTH);
frame.getContentPane().add(new JLabel("Drag Me", JLabel.CENTER),
BorderLayout.CENTER);
frame.setVisible(true);
}
}
How do I right justified JTextField contents?
To right justified a JTextField contents we can call the setHorizontalAlignment(JTextField.RIGHT) method of the JTextField class.
package org.kodejava.swing;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
public class TextFieldRightJustify extends JFrame {
public TextFieldRightJustify() {
initComponents();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new TextFieldRightJustify().setVisible(true));
}
private void initComponents() {
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setSize(500, 500);
Container container = getContentPane();
container.setLayout(new FlowLayout(FlowLayout.LEFT));
JTextField textField = new JTextField(15);
textField.setPreferredSize(new Dimension(100, 20));
// Right justify the JTextField contents
textField.setHorizontalAlignment(JTextField.RIGHT);
container.add(textField);
}
}
How do I format JLabel using HTML?
JLabel text can be formatted using an HTML standard tags. The example below shows you how we can use and HTML font tag to change the font size, color and style of JLabel text.
package org.kodejava.swing;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import java.awt.Container;
import java.awt.FlowLayout;
public class JLabelHTMLStyle extends JFrame {
public JLabelHTMLStyle() {
setTitle("JLabel with HTML Style");
initComponents();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new JLabelHTMLStyle().setVisible(true));
}
private void initComponents() {
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setSize(500, 500);
Container container = getContentPane();
container.setLayout(new FlowLayout(FlowLayout.CENTER));
// Create a JLabel object that display a string formatted using HTML.
// 14 font size with red and italic.
String text = "<html>" +
"<font size='16' color='orange'><strong>Hello World!</strong></font>" +
"</html>";
JLabel label = new JLabel(text);
container.add(label);
}
}
How do I display an image in JButton?
package org.kodejava.swing;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import java.awt.FlowLayout;
public class ButtonImageExample extends JFrame {
public ButtonImageExample() {
initComponents();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new ButtonImageExample().setVisible(true));
}
private void initComponents() {
setTitle("My Buttons");
setSize(500, 500);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
getContentPane().setLayout(new FlowLayout(FlowLayout.CENTER));
// Creates two JButton object with an images to display. The image can be
// a gif, jpeg, png and some other type supported. And we also set the
// mnemonic character of the button for short-cut key.
JButton okButton = new JButton("OK", new ImageIcon(
this.getClass().getResource("/images/ok.png")));
okButton.setMnemonic('O');
JButton cancelButton = new JButton("Cancel", new ImageIcon(
this.getClass().getResource("/images/cancel.png")));
cancelButton.setMnemonic('C');
getContentPane().add(okButton);
getContentPane().add(cancelButton);
}
}
How do I use JFormattedTextField to format user input?
The JFormattedTextField allows us to create a text field that can accept a formatted input. In this code snippet we create two formatted text fields that accept a valid phone number and a date.
package org.kodejava.swing;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import javax.swing.text.DateFormatter;
import javax.swing.text.MaskFormatter;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class FormattedTextFieldExample extends JFrame {
public FormattedTextFieldExample() {
initComponents();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new FormattedTextFieldExample().setVisible(true));
}
private void initComponents() {
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setTitle("Format User Input");
setSize(new Dimension(500, 500));
getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT));
MaskFormatter mask = null;
try {
// Create a MaskFormatter for accepting phone number, the # symbol accept
// only a number. We can also set the empty value with a place holder
// character.
mask = new MaskFormatter("(###) ###-####");
mask.setPlaceholderCharacter('_');
} catch (ParseException e) {
e.printStackTrace();
}
// Create a formatted text field that accept a valid phone number.
JFormattedTextField phoneField = new JFormattedTextField(mask);
phoneField.setPreferredSize(new Dimension(100, 20));
// Here we create a formatted text field that accept a date value. We
// create an instance of SimpleDateFormat and use it to create a
// DateFormatter instance which will be passed to the JFormattedTextField.
DateFormat format = new SimpleDateFormat("dd-MMMM-yyyy");
DateFormatter df = new DateFormatter(format);
JFormattedTextField dateField = new JFormattedTextField(df);
dateField.setPreferredSize(new Dimension(100, 20));
dateField.setValue(new Date());
getContentPane().add(phoneField);
getContentPane().add(dateField);
}
}
Here are some other characters that can be used in the MaskFormatter class.
| Char | Description |
|---|---|
| # | For number |
| ? | For letter |
| A | For number or letter |
| * | For anything |
| L | For letter, it will be converted to the equivalent lower case |
| U | For letter, it will be converted to the equivalent upper case |
| H | For hexadecimal value |
| ‘ | To escape another mask character |
How do I handle mouse button click event?
package org.kodejava.swing;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class MouseClickEventDemo extends JFrame {
public MouseClickEventDemo() {
initComponents();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new MouseClickEventDemo().setVisible(true));
}
private void initComponents() {
setTitle("Handling Mouse Click Event");
setSize(500, 500);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
final JTextArea textArea = new JTextArea();
textArea.setText("Click Me!");
textArea.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (e.getButton() == MouseEvent.NOBUTTON) {
textArea.setText("No button clicked" + "\n");
} else if (e.getButton() == MouseEvent.BUTTON1) {
textArea.setText("Button 1 clicked" + "\n");
} else if (e.getButton() == MouseEvent.BUTTON2) {
textArea.setText("Button 2 clicked" + "\n");
} else if (e.getButton() == MouseEvent.BUTTON3) {
textArea.setText("Button 3 clicked" + "\n");
}
textArea.append("Number of click: " + e.getClickCount() + "\n");
textArea.append("Click position (X, Y): " + e.getX() + ", " + e.getY());
}
});
getContentPane().add(textArea);
}
}
How do I handle mouse wheel event?
package org.kodejava.swing;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import java.awt.event.MouseWheelEvent;
public class MouseWheelListenerDemo extends JFrame {
public MouseWheelListenerDemo() {
initComponents();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new MouseWheelListenerDemo().setVisible(true));
}
private void initComponents() {
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setTitle("Mouse Wheel Listener Demo");
setSize(500, 500);
JTextArea textArea = new JTextArea();
textArea.addMouseWheelListener(e -> {
System.out.println("MouseWheelListenerDemo.mouseWheelMoved");
// If wheel rotation value is a negative it means rotate up, while
// positive value means rotate down
if (e.getWheelRotation() < 0) {
System.out.println("Rotated Up... " + e.getWheelRotation());
} else {
System.out.println("Rotated Down... " + e.getWheelRotation());
}
// Get scrolled unit amount
System.out.println("ScrollAmount: " + e.getScrollAmount());
// WHEEL_UNIT_SCROLL representing scroll by unit such as the
// arrow keys. WHEEL_BLOCK_SCROLL representing scroll by block
// such as the page-up or page-down key.
if (e.getScrollType() == MouseWheelEvent.WHEEL_UNIT_SCROLL) {
System.out.println("MouseWheelEvent.WHEEL_UNIT_SCROLL");
}
if (e.getScrollType() == MouseWheelEvent.WHEEL_BLOCK_SCROLL) {
System.out.println("MouseWheelEvent.WHEEL_BLOCK_SCROLL");
}
});
getContentPane().add(textArea);
}
}
The scrolling the mouse wheel the code snippet will print something like:
MouseWheelListenerDemo.mouseWheelMoved
Rotated Down... 1
ScrollAmount: 3
MouseWheelEvent.WHEEL_UNIT_SCROLL
MouseWheelListenerDemo.mouseWheelMoved
Rotated Up... -1
ScrollAmount: 3
MouseWheelEvent.WHEEL_UNIT_SCROLL








