Java/Swing JFC/Label
Содержание
- 1 Active Label Sample
- 2 Adding an Icon to a JLabel Component
- 3 Adding Drag-and-Drop Support to a JLabel Component
- 4 A JLabel that uses inline HTML to format its text
- 5 A Label that uses inline HTML to format its text
- 6 A label with no indication it has been clicked
- 7 Animation label
- 8 A quick application to show a simple JLabel
- 9 A simple demonstration of text alignment in JLabels
- 10 Create a JLabel component
- 11 Create a JLabel with an image icon
- 12 Create JLabel component
- 13 Disable a label
- 14 Grab and Drag image scroll label
- 15 Horizontal Alignment: CENTER
- 16 Horizontal Alignment: LEFT
- 17 Horizontal Alignment: RIGHT
- 18 HTML label
- 19 JLabel is for displaying text, images or both. It does not react to input events.
- 20 JLabel with lined border
- 21 JLabel with more than one row
- 22 JSlider lets the user graphically select a value by sliding a knob within a bounded interval.
- 23 Label alignment
- 24 Label background, icon, align
- 25 LabelFocusSample: setLabelFor
- 26 Label for
- 27 LabelFor Demo
- 28 Label Text Position
- 29 Label with HTML Sample
- 30 Label with Icon
- 31 Label with Image
- 32 Label with ImageIcon (Icon)
- 33 Label with various effects
- 34 Multiline label (HTML)
- 35 Putting HTML text on Swing components
- 36 Scrollable Label
- 37 Set the Preferred Size
- 38 Setting the Focus of a JTextField Component Using a JLabel Component
- 39 Shows how displayed Mnemonic and labelFor properties work together
- 40 Solve the problem of text alignment in JLabels
- 41 Swing Label Demo
- 42 The text is horizontally and vertically centered
- 43 The text is left-justified and bottom-aligned
- 44 The text is left-justified and top-aligned
- 45 The text is right-justified and bottom-aligned
- 46 The text is right-justified and top-aligned
- 47 The text is right-justified and vertically centered
- 48 Use a ScrollBar in both vertical and horizontal direction
- 49 Variations on a text and icon label
- 50 Vertical Alignment: BOTTOM
- 51 Vertical Alignment: CENTER
- 52 Vertical Alignment: TOP
Active Label Sample
<source lang="java">
import java.awt.BorderLayout; import java.awt.Container; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.UIDefaults; import javax.swing.UIManager; public class ActiveSample {
private static final String LABEL_FACTORY = "LabelFactory"; public static void main(String args[]) { JFrame frame = new JFrame("Active Example"); UIManager.put(LABEL_FACTORY, new ActiveLabel()); final JPanel panel = new JPanel(); JButton button = new JButton("Get"); ActionListener actionListener = new ActionListener() { public void actionPerformed(ActionEvent actionEvent) { JLabel label = (JLabel) UIManager.get(LABEL_FACTORY); panel.add(label); panel.revalidate(); } }; button.addActionListener(actionListener); Container contentPane = frame.getContentPane(); contentPane.add(panel, BorderLayout.CENTER); contentPane.add(button, BorderLayout.SOUTH); frame.setSize(200, 200); frame.setVisible(true); }
} class ActiveLabel implements UIDefaults.ActiveValue {
private int counter = 0; public Object createValue(UIDefaults defaults) { JLabel label = new JLabel("" + counter++); return label; }
}
</source>
Adding an Icon to a JLabel Component
<source lang="java">
import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JLabel; public class Main {
public static void main(String[] argv) throws Exception { Icon icon = new ImageIcon("icon.gif"); JLabel label = new JLabel("Text Label", icon, JLabel.CENTER); // a label with only an icon label = new JLabel(icon); }
}
</source>
Adding Drag-and-Drop Support to a JLabel Component
<source lang="java">
import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.TransferHandler; public class Main {
public static void main(String[] argv) throws Exception { JLabel label = new JLabel("Label Text"); final String propertyName = "text"; label.setTransferHandler(new TransferHandler(propertyName)); label.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent evt) { JComponent comp = (JComponent) evt.getSource(); TransferHandler th = comp.getTransferHandler(); th.exportAsDrag(comp, evt, TransferHandler.COPY); } }); }
}
</source>
A JLabel that uses inline HTML to format its text
<source lang="java">
//A JLabel that uses inline HTML to format its text. import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; public class SwingHtmlLabel extends JPanel {
public static final String markup = "<html>line 1" + "big blue line 2<p>line 3</html>"; public static void main(String argv[]) { JPanel p = new JPanel(new java.awt.GridLayout(0, 1)); p.add(new JLabel(markup)); p.add(new java.awt.Label(markup)); JFrame f = new JFrame("SwingHtmlLabel"); f.setContentPane(p); f.setSize(600, 200); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setVisible(true); } } </source>
A Label that uses inline HTML to format its text
<source lang="java">
import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; public class Main extends JPanel {
public static final String markup = "<html>line 1<p>" + "big blue line 2<p>line 3</html>"; public static void main(String argv[]) { JPanel p = new JPanel(new java.awt.GridLayout(0, 1)); p.add(new JLabel(markup)); p.add(new java.awt.Label(markup)); JFrame f = new JFrame("HtmlLabel"); f.setContentPane(p); f.setSize(600, 200); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setVisible(true); }
}
</source>
A label with no indication it has been clicked
<source lang="java">
import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.JLabel; public class MyLabel extends JLabel {
public MyLabel(String msg) { super(msg); addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent me) { fireActionPerformed(new ActionEvent(MyLabel.this, ActionEvent.ACTION_PERFORMED, "SecretMessage")); } }); } public void addActionListener(ActionListener l) { listenerList.add(ActionListener.class, l); } public void removeActionListener(ActionListener l) { listenerList.remove(ActionListener.class, l); } protected void fireActionPerformed(ActionEvent ae) { Object[] listeners = listenerList.getListeners(ActionListener.class); for (int i = 0; i < listeners.length; i++) { ((ActionListener) listeners[i]).actionPerformed(ae); } }
}
</source>
Animation label
<source lang="java">
import java.awt.Graphics; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JLabel; public class AnimatedLabel extends JLabel implements Runnable {
protected Icon[] icons; protected int index = 0; protected boolean isRunning; public AnimatedLabel(String gifName, int numGifs) { icons = new Icon[numGifs]; for (int i = 0; i < numGifs; i++) icons[i] = new ImageIcon(gifName + i + ".gif"); setIcon(icons[0]); Thread tr = new Thread(this); tr.setPriority(Thread.MAX_PRIORITY); tr.start(); } public void setRunning(boolean r) { isRunning = r; } public boolean getRunning() { return isRunning; } public void run() { while (true) { if (isRunning) { index++; if (index >= icons.length) index = 0; setIcon(icons[index]); Graphics g = getGraphics(); icons[index].paintIcon(this, g, 0, 0); } else { if (index > 0) { index = 0; setIcon(icons[0]); } } try { Thread.sleep(500); } catch (Exception ex) { } } }
}
</source>
A quick application to show a simple JLabel
<source lang="java">
//A quick application to show a simple JLabel. import javax.swing.JFrame; import javax.swing.JLabel; public class SimpleJLabelExample {
public static void main(String[] args) { JLabel label = new JLabel("A Very Simple Text Label"); JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().add(label); frame.pack(); frame.setVisible(true); }
}
</source>
A simple demonstration of text alignment in JLabels
<source lang="java">
//A simple demonstration of text alignment in JLabels. import java.awt.Color; import java.awt.GridLayout; import javax.swing.BorderFactory; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.SwingConstants; public class AlignmentExample {
public static void main(String[] args) { JLabel label1 = new JLabel("BottomRight", SwingConstants.RIGHT); JLabel label2 = new JLabel("CenterLeft", SwingConstants.LEFT); JLabel label3 = new JLabel("TopCenter", SwingConstants.CENTER); label1.setVerticalAlignment(SwingConstants.BOTTOM); label2.setVerticalAlignment(SwingConstants.CENTER); label3.setVerticalAlignment(SwingConstants.TOP); label1.setBorder(BorderFactory.createLineBorder(Color.black)); label2.setBorder(BorderFactory.createLineBorder(Color.black)); label3.setBorder(BorderFactory.createLineBorder(Color.black)); JFrame frame = new JFrame("AlignmentExample"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel p = new JPanel(new GridLayout(3, 1, 8, 8)); p.add(label1); p.add(label2); p.add(label3); p.setBorder(BorderFactory.createEmptyBorder(8, 8, 8, 8)); frame.setContentPane(p); frame.setSize(200, 200); frame.setVisible(true); }
}
</source>
Create a JLabel component
<source lang="java">
import java.awt.FlowLayout; import java.awt.HeadlessException; import javax.swing.JFrame; import javax.swing.JLabel; public class Main extends JFrame {
public Main() throws HeadlessException { setSize(150, 300); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLayout(new FlowLayout()); JLabel label1 = new JLabel("Username :", JLabel.RIGHT); JLabel label2 = new JLabel("Password :", JLabel.RIGHT); JLabel label3 = new JLabel("Confirm Password :", JLabel.RIGHT); JLabel label4 = new JLabel("Remember Me!", JLabel.LEFT); JLabel label5 = new JLabel("Hello.", JLabel.CENTER); label5.setVerticalAlignment(JLabel.TOP); label5.setToolTipText("A tool tip with me!"); getContentPane().add(label1); getContentPane().add(label2); getContentPane().add(label3); getContentPane().add(label4); getContentPane().add(label5); } public static void main(String[] args) { new Main().setVisible(true); }
}
</source>
Create a JLabel with an image icon
<source lang="java">
import java.awt.FlowLayout; import java.awt.HeadlessException; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JLabel; public class Main extends JFrame {
public Main() throws HeadlessException { setSize(300, 300); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLayout(new FlowLayout(FlowLayout.LEFT)); Icon icon = new ImageIcon("a.png"); JLabel label1 = new JLabel("Full Name :", icon, JLabel.LEFT); JLabel label2 = new JLabel("Address :", JLabel.LEFT); label2.setIcon(new ImageIcon("b.png")); getContentPane().add(label1); getContentPane().add(label2); } public static void main(String[] args) { new Main().setVisible(true); }
}
</source>
Create JLabel component
<source lang="java">
import java.awt.FlowLayout; import java.awt.HeadlessException; import javax.swing.JFrame; import javax.swing.JLabel; public class Main extends JFrame {
public Main() throws HeadlessException { setSize(150, 300); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLayout(new FlowLayout()); JLabel label1 = new JLabel("Username :", JLabel.RIGHT); JLabel label2 = new JLabel("Password :", JLabel.RIGHT); JLabel label3 = new JLabel("Confirm Password :", JLabel.RIGHT); JLabel label4 = new JLabel("Remember Me!", JLabel.LEFT); JLabel label5 = new JLabel("Hello.", JLabel.CENTER); label5.setVerticalAlignment(JLabel.TOP); label5.setToolTipText("A tool tip with me!"); getContentPane().add(label1); getContentPane().add(label2); getContentPane().add(label3); getContentPane().add(label4); getContentPane().add(label5); } public static void main(String[] args) { new Main().setVisible(true); }
}
</source>
Disable a label
<source lang="java">
import java.awt.Color; import java.awt.FlowLayout; import javax.swing.BorderFactory; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.border.Border; public class Main {
public static void main(String args[]) { JFrame f = new JFrame("Label Demo"); f.setLayout(new FlowLayout()); f.setSize(200, 360); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JLabel label= new JLabel("asdf"); Border border = BorderFactory.createLineBorder(Color.BLACK); label.setBorder(border); label.setEnabled(false); f.add(label); f.setVisible(true); }
}
</source>
Grab and Drag image scroll label
<source lang="java">
import java.awt.Container; import java.awt.Cursor; import java.awt.Point; import java.awt.event.MouseEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JScrollPane; import javax.swing.JViewport; import javax.swing.event.MouseInputAdapter; public class GrabAndDragDemo extends JFrame {
public GrabAndDragDemo() { super("Grab and drag Demo"); ImageIcon ii = new ImageIcon("largejexpLogo.jpg"); JScrollPane jsp = new JScrollPane(new GrabAndScrollLabel(ii)); getContentPane().add(jsp); setSize(300, 250); setVisible(true); WindowListener l = new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }; addWindowListener(l); } public static void main(String[] args) { new GrabAndDragDemo(); }
} class GrabAndScrollLabel extends JLabel {
public GrabAndScrollLabel(ImageIcon i) { super(i); MouseInputAdapter mia = new MouseInputAdapter() { int xDiff, yDiff; boolean isDragging; Container c; public void mouseDragged(MouseEvent e) { c = GrabAndScrollLabel.this.getParent(); if (c instanceof JViewport) { JViewport jv = (JViewport) c; Point p = jv.getViewPosition(); int newX = p.x - (e.getX() - xDiff); int newY = p.y - (e.getY() - yDiff); int maxX = GrabAndScrollLabel.this.getWidth() - jv.getWidth(); int maxY = GrabAndScrollLabel.this.getHeight() - jv.getHeight(); if (newX < 0) newX = 0; if (newX > maxX) newX = maxX; if (newY < 0) newY = 0; if (newY > maxY) newY = maxY; jv.setViewPosition(new Point(newX, newY)); } } public void mousePressed(MouseEvent e) { setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR)); xDiff = e.getX(); yDiff = e.getY(); } public void mouseReleased(MouseEvent e) { setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); } }; addMouseMotionListener(mia); addMouseListener(mia); }
}
</source>
Horizontal Alignment: CENTER
<source lang="java">
import java.awt.Color; import java.awt.Dimension; import java.awt.FlowLayout; import javax.swing.BorderFactory; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.border.Border; public class Main {
public static void main(String args[]) { JFrame f = new JFrame("Label Demo"); f.setLayout(new FlowLayout()); f.setSize(200, 360); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JLabel label= new JLabel("asdf"); Border border = BorderFactory.createLineBorder(Color.BLACK); label.setBorder(border); label.setPreferredSize(new Dimension(150, 100)); label.setText("Centered"); label.setHorizontalAlignment(JLabel.CENTER); label.setVerticalAlignment(JLabel.CENTER); f.add(label); f.setVisible(true); }
}
</source>
Horizontal Alignment: LEFT
<source lang="java">
import java.awt.Color; import java.awt.Dimension; import java.awt.FlowLayout; import javax.swing.BorderFactory; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.border.Border; public class Main {
public static void main(String args[]) { JFrame f = new JFrame("Label Demo"); f.setLayout(new FlowLayout()); f.setSize(200, 360); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JLabel label= new JLabel("asdf"); Border border = BorderFactory.createLineBorder(Color.BLACK); label.setBorder(border); label.setPreferredSize(new Dimension(150, 100)); label.setText("Top Left"); label.setHorizontalAlignment(JLabel.LEFT); label.setVerticalAlignment(JLabel.TOP); f.add(label); f.setVisible(true); }
}
</source>
Horizontal Alignment: RIGHT
<source lang="java">
import java.awt.Color; import java.awt.Dimension; import java.awt.FlowLayout; import javax.swing.BorderFactory; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.border.Border; public class Main {
public static void main(String args[]) { JFrame f = new JFrame("Label Demo"); f.setLayout(new FlowLayout()); f.setSize(200, 360); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JLabel label= new JLabel("asdf"); Border border = BorderFactory.createLineBorder(Color.BLACK); label.setBorder(border); label.setPreferredSize(new Dimension(150, 100)); label.setText("Bottom Right"); label.setHorizontalAlignment(JLabel.RIGHT); label.setVerticalAlignment(JLabel.BOTTOM); f.add(label); f.setVisible(true); }
}
</source>
HTML label
<source lang="java">
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; import javax.swing.JLabel; public class HtmlLabel extends JFrame {
public HtmlLabel() { super("HTML Buttons"); setSize(400, 300); getContentPane().setLayout(new FlowLayout());String htmlText = "<html><p>JButton "
+ "" + "with HTML text</html>"; JLabel btn = new JLabel(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 HtmlLabel(); }
}
</source>
JLabel is for displaying text, images or both. It does not react to input events.
<source lang="java">
import java.awt.BorderLayout; import java.awt.Color; import java.awt.Font; import javax.swing.BorderFactory; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; public class MyLabel extends JFrame {
public static void main(String[] args) { String lyrics = "<html>Line
line
line</html>"; JPanel panel = new JPanel(); panel.setLayout(new BorderLayout(10, 10)); JLabel label = new JLabel(lyrics); label.setFont(new Font("Georgia", Font.PLAIN, 14)); label.setForeground(new Color(50, 50, 25)); panel.add(label, BorderLayout.CENTER); panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); JFrame f = new JFrame(); f.add(panel); f.pack(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setVisible(true); }
}
</source>
JLabel with lined border
<source lang="java">
import java.awt.Color; import java.awt.FlowLayout; import javax.swing.BorderFactory; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.border.Border; public class Main {
public static void main(String args[]) { JFrame f = new JFrame("Label Demo"); f.setLayout(new FlowLayout()); f.setSize(200, 360); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JLabel label= new JLabel("A default label"); Border border = BorderFactory.createLineBorder(Color.BLACK); label.setBorder(border); f.add(label); f.setVisible(true); }
}
</source>
JLabel with more than one row
<source lang="java">
JLabel label = new JLabel();
label.setText("<html>Line 1
Line 2</html>");
</source>
JSlider lets the user graphically select a value by sliding a knob within a bounded interval.
<source lang="java">
import java.awt.Dimension; import javax.swing.JFrame; import javax.swing.JSlider; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; public class Slider {
public static void main(String[] args) { JFrame f = new JFrame(); final JSlider slider = new JSlider(0, 150, 0); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); slider.setPreferredSize(new Dimension(150, 30)); slider.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent event) { int value = slider.getValue(); if (value == 0) { System.out.println("0"); } else if (value > 0 && value <= 30) { System.out.println("value > 0 && value <= 30"); } else if (value > 30 && value < 80) { System.out.println("value > 30 && value < 80"); } else { System.out.println("max"); } } }); f.add(slider); f.pack(); f.setLocationRelativeTo(null); f.setVisible(true); }
}
</source>
Label alignment
<source lang="java">
import java.awt.Color; import java.awt.ruponent; import java.awt.Dimension; import java.awt.Graphics; import java.awt.GridLayout; import javax.swing.BorderFactory; import javax.swing.Icon; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; public class AlignLabels extends JPanel {
JLabel[] labels = new JLabel[9]; public AlignLabels() { JLabel label; setLayout(new GridLayout(3, 3)); label = createLabel("NW alignment"); setNWalignment(label); label.setEnabled(false); labels[0] = label; label = createLabel("N alignment"); setNalignment(label); labels[1] = label; label = createLabel("NE alignment"); setNEalignment(label); labels[2] = label; label = createLabel("W alignment"); label.setText("<html>html based
W alignment"); setWalignment(label); labels[3] = label; label = createLabel("C alignment"); setCalignment(label); label.setEnabled(false); labels[4] = label; label = createLabel("E alignment"); setEalignment(label); labels[5] = label; label = createLabel("SW alignment"); setSWalignment(label); labels[6] = label; label = createLabel("S alignment"); setSalignment(label); labels[7] = label; label = createLabel("SE alignment"); setSEalignment(label); label.setEnabled(false); labels[8] = label; } public static void main(String[] a) { JFrame mainFrame = new JFrame(); mainFrame.getContentPane().add(new AlignLabels()); mainFrame.setSize(500,500); mainFrame.setVisible(true); } JLabel[] getLabels() { return labels; } JLabel createLabel(String text) { String separator = System.getProperty("line.separator"); JLabel label = new JLabel(text + separator + "multiline" + separator + "label"); label.setToolTipText(text + "\n\ndoubled space\n\ntooltip"); label.setBorder(BorderFactory.createEtchedBorder()); this.add(label); label.setPreferredSize(new Dimension(125, 125)); return label; } void setNWalignment(JLabel b) { b.setHorizontalAlignment(JLabel.LEFT); b.setVerticalAlignment(JLabel.TOP); } void setNalignment(JLabel b) { b.setHorizontalAlignment(JLabel.CENTER); b.setVerticalAlignment(JLabel.TOP); } void setNEalignment(JLabel b) { b.setHorizontalAlignment(JLabel.RIGHT); b.setVerticalAlignment(JLabel.TOP); } void setWalignment(JLabel b) { b.setHorizontalAlignment(JLabel.LEFT); b.setVerticalAlignment(JLabel.CENTER); } void setCalignment(JLabel b) { b.setHorizontalAlignment(JLabel.CENTER); b.setVerticalAlignment(JLabel.CENTER); } void setEalignment(JLabel b) { b.setHorizontalAlignment(JLabel.RIGHT); b.setVerticalAlignment(JLabel.CENTER); } void setSWalignment(JLabel b) { b.setHorizontalAlignment(JLabel.LEFT); b.setVerticalAlignment(JLabel.BOTTOM); } void setSalignment(JLabel b) { b.setHorizontalAlignment(JLabel.CENTER); b.setVerticalAlignment(JLabel.BOTTOM); } void setSEalignment(JLabel b) { b.setHorizontalAlignment(JLabel.RIGHT); b.setVerticalAlignment(JLabel.BOTTOM); }
} class ColoredSquare implements Icon {
Color color; public ColoredSquare(Color color) { this.color = color; } public void paintIcon(Component c, Graphics g, int x, int y) { Color oldColor = g.getColor(); g.setColor(color); g.fill3DRect(x, y, getIconWidth(), getIconHeight(), true); g.setColor(oldColor); } public int getIconWidth() { return 12; } public int getIconHeight() { return 12; }
}
</source>
Label background, icon, align
<source lang="java">
import java.awt.Color; import java.awt.Font; import java.awt.GridLayout; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.SwingConstants; public class LabelDemo extends JFrame {
public LabelDemo() { super("JLabel Demo"); setSize(600, 100); JPanel content = new JPanel(new GridLayout(1, 4, 4, 4)); JLabel label = new JLabel("jexp"); label.setBackground(Color.white); content.add(label); label = new JLabel("jexp", SwingConstants.CENTER); label.setOpaque(true); label.setBackground(Color.white); content.add(label); label = new JLabel("jexp"); label.setFont(new Font("Helvetica", Font.BOLD, 18)); label.setOpaque(true); label.setBackground(Color.white); content.add(label); ImageIcon image = new ImageIcon("jexpLogo.gif"); label = new JLabel("jexp", image, SwingConstants.RIGHT); label.setVerticalTextPosition(SwingConstants.TOP); label.setOpaque(true); label.setBackground(Color.white); content.add(label); getContentPane().add(content); setVisible(true); } public static void main(String args[]) { new LabelDemo(); }
}
</source>
LabelFocusSample: setLabelFor
<source lang="java">
import java.awt.BorderLayout; import java.awt.Container; import java.awt.event.KeyEvent; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; public class LabelFocusSample {
public static void main(String args[]) { JFrame frame = new JFrame("Label Focus Example"); Container content = frame.getContentPane(); JPanel panel = new JPanel(new BorderLayout()); JLabel label = new JLabel("Name: "); label.setDisplayedMnemonic(KeyEvent.VK_N); JTextField textField = new JTextField(); label.setLabelFor(textField); panel.add(label, BorderLayout.WEST); panel.add(textField, BorderLayout.CENTER); content.add(panel, BorderLayout.NORTH); content.add(new JButton("Somewhere Else"), BorderLayout.SOUTH); frame.setSize(250, 150); frame.setVisible(true); }
}
</source>
Label for
<source lang="java">
import java.awt.BorderLayout; import java.awt.Container; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import javax.swing.BoundedRangeModel; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; public class OffsetSample {
public static void main(String args[]) { JFrame frame = new JFrame("Offset Example"); Container content = frame.getContentPane(); JPanel panel = new JPanel(new BorderLayout()); JLabel label = new JLabel("Name: "); label.setDisplayedMnemonic(KeyEvent.VK_N); final JTextField textField = new JTextField(); label.setLabelFor(textField); panel.add(label, BorderLayout.WEST); panel.add(textField, BorderLayout.CENTER); content.add(panel, BorderLayout.NORTH); JButton button = new JButton("Get Offset"); ActionListener actionListener = new ActionListener() { public void actionPerformed(ActionEvent actionEvent) { System.out.println("Offset: " + textField.getScrollOffset()); System.out.println("Visibility: " + textField.getHorizontalVisibility()); BoundedRangeModel model = textField.getHorizontalVisibility(); int extent = model.getExtent(); textField.setScrollOffset(extent); } }; button.addActionListener(actionListener); content.add(button, BorderLayout.SOUTH); frame.setSize(250, 150); frame.setVisible(true); }
}
</source>
LabelFor Demo
<source lang="java">
import java.awt.BorderLayout; import java.awt.Container; import java.awt.event.KeyEvent; import javax.swing.Box; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JTextField; public class LabelFor {
public static void main(String args[]) { JFrame f = new JFrame("LabelFor Sample"); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Container content = f.getContentPane(); JLabel label = new JLabel("Username"); JTextField textField = new JTextField(); label.setDisplayedMnemonic(KeyEvent.VK_U); label.setLabelFor(textField); Container box = Box.createHorizontalBox(); box.add(label); box.add(textField); content.add(box, BorderLayout.NORTH); content.add(new JButton("Submit"), BorderLayout.SOUTH); f.setSize(300, 200); f.setVisible(true); }
}
</source>
Label Text Position
<source lang="java">
import java.awt.Container; import java.awt.GridLayout; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.border.Border; import javax.swing.border.LineBorder; public class LabelTextPos {
public static void main(String args[]) { JFrame frame = new JFrame("Label Text Pos"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Container content = frame.getContentPane(); content.setLayout(new GridLayout(2, 2)); Border border = LineBorder.createGrayLineBorder(); Icon warnIcon = new ImageIcon("Warn.gif"); JLabel label1 = new JLabel(warnIcon); label1.setText("Left-Bottom"); label1.setHorizontalTextPosition(JLabel.LEFT); label1.setVerticalTextPosition(JLabel.BOTTOM); label1.setBorder(border); content.add(label1); JLabel label2 = new JLabel(warnIcon); label2.setText("Right-TOP"); label2.setHorizontalTextPosition(JLabel.RIGHT); label2.setVerticalTextPosition(JLabel.TOP); label2.setBorder(border); content.add(label2); JLabel label3 = new JLabel(warnIcon); label3.setText("Center-Center"); label3.setHorizontalTextPosition(JLabel.CENTER); label3.setVerticalTextPosition(JLabel.CENTER); label3.setBorder(border); content.add(label3); JLabel label4 = new JLabel(warnIcon); label4.setText("Center-Bottom"); label4.setHorizontalTextPosition(JLabel.CENTER); label4.setVerticalTextPosition(JLabel.BOTTOM); label4.setBorder(border); content.add(label4); frame.setSize(300, 200); frame.setVisible(true); }
}
</source>
Label with HTML Sample
<source lang="java">
import java.awt.Container; import java.awt.GridLayout; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JLabel; public class LabelSample {
public static void main(String args[]) { String title = "JLabel Sample"; JFrame frame = new JFrame(title); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Container content = frame.getContentPane(); content.setLayout(new GridLayout(2, 2)); JLabel label1 = new JLabel("Text Label"); content.add(label1); Icon warnIcon = new ImageIcon("Warn.gif"); JLabel label2 = new JLabel(warnIcon); content.add(label2); JLabel label3 = new JLabel("Warning", warnIcon, JLabel.CENTER); content.add(label3); String htmlLabel = "<html>HTML Label
" + "Multi-line"; JLabel label4 = new JLabel(htmlLabel); content.add(label4); frame.setSize(300, 200); frame.setVisible(true); }
}
</source>
Label with Icon
<source lang="java">
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.JFrame; import javax.swing.JLabel; public class LabelIcon {
public static void main(String args[]) { JFrame frame = new JFrame("Label Icon"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Container content = frame.getContentPane(); Icon icon = new DiamondIcon(Color.red, true, 25, 25); JLabel label1 = new JLabel(icon); content.add(label1); frame.setSize(200, 100); frame.setVisible(true); }
} class DiamondIcon implements Icon {
private Color color; private boolean selected; private int width; private int height; private Polygon poly; private static final int DEFAULT_WIDTH = 10; private static final int DEFAULT_HEIGHT = 10; public DiamondIcon(Color color) { this(color, true, DEFAULT_WIDTH, DEFAULT_HEIGHT); } public DiamondIcon(Color color, boolean selected) { this(color, selected, DEFAULT_WIDTH, DEFAULT_HEIGHT); } public DiamondIcon(Color color, boolean selected, int width, int height) { this.color = color; this.selected = selected; this.width = width; this.height = height; initPolygon(); } private void initPolygon() { poly = new Polygon(); int halfWidth = width / 2; int halfHeight = height / 2; poly.addPoint(0, halfHeight); poly.addPoint(halfWidth, 0); poly.addPoint(width, halfHeight); poly.addPoint(halfWidth, height); } public int getIconHeight() { return height; } public int getIconWidth() { return width; } public void paintIcon(Component c, Graphics g, int x, int y) { g.setColor(color); g.translate(x, y); if (selected) { g.fillPolygon(poly); } else { g.drawPolygon(poly); } g.translate(-x, -y); }
}
</source>
Label with Image
<source lang="java">
import java.awt.Container; import java.awt.GridLayout; import java.awt.Image; import java.awt.Toolkit; import java.io.BufferedInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JLabel; public class LabelJarSample {
public static void main(String args[]) { String title = "JLabel Sample"; JFrame frame = new JFrame(title); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Container content = frame.getContentPane(); content.setLayout(new GridLayout(2, 2)); JLabel label1 = new JLabel("Text Label"); content.add(label1); Image warnImage = ImageLoader.getImage(LabelJarSample.class, "Warn.gif"); Icon warnIcon = new ImageIcon(warnImage); JLabel label2 = new JLabel(warnIcon); content.add(label2); JLabel label3 = new JLabel("Warning", warnIcon, JLabel.CENTER); content.add(label3); String htmlLabel = "<html>HTML Label
" + "Multi-line"; JLabel label4 = new JLabel(htmlLabel); content.add(label4); frame.setSize(300, 200); frame.setVisible(true); }
} final class ImageLoader {
private ImageLoader() { } public static Image getImage(Class relativeClass, String filename) { Image returnValue = null; InputStream is = relativeClass.getResourceAsStream(filename); if (is != null) { BufferedInputStream bis = new BufferedInputStream(is); ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { int ch; while ((ch = bis.read()) != -1) { baos.write(ch); } returnValue = Toolkit.getDefaultToolkit().createImage( baos.toByteArray()); } catch (IOException exception) { System.err.println("Error loading: " + filename); } } return returnValue; }
}
</source>
Label with ImageIcon (Icon)
<source lang="java">
import java.awt.Color; import java.awt.FlowLayout; import javax.swing.BorderFactory; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.border.Border; public class Main {
public static void main(String args[]) { JFrame f = new JFrame("Label Demo"); f.setLayout(new FlowLayout()); f.setSize(200, 360); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); ImageIcon myIcon = new ImageIcon("myIcon.gif"); JLabel label= new JLabel("A default label", myIcon, JLabel.LEFT); Border border = BorderFactory.createLineBorder(Color.BLACK); label.setBorder(border); f.add(label); f.setVisible(true); }
}
</source>
Label with various effects
<source lang="java">
import java.awt.BasicStroke; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.GradientPaint; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GridLayout; import java.awt.Image; import java.awt.Insets; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.Shape; import java.awt.Stroke; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import java.awt.font.FontRenderContext; import java.awt.font.TextLayout; import java.awt.geom.AffineTransform; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.border.LineBorder; public class JLabel2D extends JLabel {
public static final int EFFECT_PLAIN = 0; public static final int EFFECT_GRADIENT = 1; public static final int EFFECT_IMAGE = 2; public static final int EFFECT_IMAGE_ANIMATION = 3; public static final int EFFECT_COLOR_ANIMATION = 4; protected int effectIndex = EFFECT_PLAIN; protected double shearFactor = 0.0; protected Color outlineColor; protected Stroke stroke; protected GradientPaint gradient; protected Image foregroundImage; protected Thread animator; protected boolean isRunning = false; protected int m_delay; protected int m_xShift; public JLabel2D() { super(); } public JLabel2D(String text) { super(text); } public JLabel2D(String text, int alignment) { super(text, alignment); } public void setEffectIndex(int e) { effectIndex = e; repaint(); } public int getEffectIndex() { return effectIndex; } public void setShearFactor(double s) { shearFactor = s; repaint(); } public double getShearFactor() { return shearFactor; } public void setOutlineColor(Color c) { outlineColor = c; repaint(); } public Color getOutlineColor() { return outlineColor; } public void setStroke(Stroke s) { stroke = s; repaint(); } public Stroke getStroke() { return stroke; } public void setGradient(GradientPaint g) { gradient = g; repaint(); } public GradientPaint getGradient() { return gradient; } public void setForegroundImage(Image img) { foregroundImage = img; repaint(); } public Image getForegroundImage() { return foregroundImage; } public void startAnimation(int delay) { if (animator != null) return; m_delay = delay; m_xShift = 0; isRunning = true; animator = new Thread() { double arg = 0; public void run() { while (isRunning) { if (effectIndex == EFFECT_IMAGE_ANIMATION) m_xShift += 10; else if (effectIndex == EFFECT_COLOR_ANIMATION && gradient != null) { arg += Math.PI / 10; double cos = Math.cos(arg); double f1 = (1 + cos) / 2; double f2 = (1 - cos) / 2; arg = arg % (Math.PI * 2); Color c1 = gradient.getColor1(); Color c2 = gradient.getColor2(); int r = (int) (c1.getRed() * f1 + c2.getRed() * f2); r = Math.min(Math.max(r, 0), 255); int g = (int) (c1.getGreen() * f1 + c2.getGreen() * f2); g = Math.min(Math.max(g, 0), 255); int b = (int) (c1.getBlue() * f1 + c2.getBlue() * f2); b = Math.min(Math.max(b, 0), 255); setForeground(new Color(r, g, b)); } repaint(); try { sleep(m_delay); } catch (InterruptedException ex) { break; } } } }; animator.start(); } public void stopAnimation() { isRunning = false; animator = null; } public void paintComponent(Graphics g) { Dimension d = getSize(); Insets ins = getInsets(); int x = ins.left; int y = ins.top; int w = d.width - ins.left - ins.right; int h = d.height - ins.top - ins.bottom; if (isOpaque()) { g.setColor(getBackground()); g.fillRect(0, 0, d.width, d.height); } paintBorder(g); Graphics2D g2 = (Graphics2D) g; g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); FontRenderContext frc = g2.getFontRenderContext(); TextLayout tl = new TextLayout(getText(), getFont(), frc); AffineTransform shear = AffineTransform.getShearInstance(shearFactor, 0.0); Shape src = tl.getOutline(shear); Rectangle rText = src.getBounds(); float xText = x - rText.x; switch (getHorizontalAlignment()) { case CENTER: xText = x + (w - rText.width) / 2; break; case RIGHT: xText = x + (w - rText.width); break; } float yText = y + h / 2 + tl.getAscent() / 4; AffineTransform shift = AffineTransform.getTranslateInstance(xText, yText); Shape shp = shift.createTransformedShape(src); if (outlineColor != null) { g2.setColor(outlineColor); if (stroke != null) g2.setStroke(stroke); g2.draw(shp); } switch (effectIndex) { case EFFECT_GRADIENT: if (gradient == null) break; g2.setPaint(gradient); g2.fill(shp); break; case EFFECT_IMAGE: fillByImage(g2, shp, 0); break; case EFFECT_COLOR_ANIMATION: g2.setColor(getForeground()); g2.fill(shp); break; case EFFECT_IMAGE_ANIMATION: if (foregroundImage == null) break; int wImg = foregroundImage.getWidth(this); if (m_xShift > wImg) m_xShift = 0; fillByImage(g2, shp, m_xShift - wImg); break; default: g2.setColor(getForeground()); g2.fill(shp); break; } } protected void fillByImage(Graphics2D g2, Shape shape, int xOffset) { if (foregroundImage == null) return; int wImg = foregroundImage.getWidth(this); int hImg = foregroundImage.getHeight(this); if (wImg <= 0 || hImg <= 0) return; g2.setClip(shape); Rectangle bounds = shape.getBounds(); for (int xx = bounds.x + xOffset; xx < bounds.x + bounds.width; xx += wImg) for (int yy = bounds.y; yy < bounds.y + bounds.height; yy += hImg) g2.drawImage(foregroundImage, xx, yy, this); } public static void main(String argv[]) { JFrame f = new JFrame("2D Labels"); f.setSize(600, 300); f.getContentPane().setLayout(new GridLayout(6, 1, 5, 5)); f.getContentPane().setBackground(Color.white); Font bigFont = new Font("Helvetica", Font.BOLD, 24); JLabel2D lbl = new JLabel2D("Java Source and Support With Outline", JLabel.CENTER); lbl.setFont(bigFont); lbl.setForeground(Color.blue); lbl.setBorder(new LineBorder(Color.black)); lbl.setBackground(Color.cyan); lbl.setOutlineColor(Color.yellow); lbl.setStroke(new BasicStroke(5f)); lbl.setOpaque(true); lbl.setShearFactor(0.3); f.getContentPane().add(lbl); lbl = new JLabel2D("Java Source and Support With Color Gradient", JLabel.CENTER); lbl.setFont(bigFont); lbl.setOutlineColor(Color.black); lbl.setEffectIndex(JLabel2D.EFFECT_GRADIENT); GradientPaint gp = new GradientPaint(0, 0, Color.red, 100, 50, Color.blue, true); lbl.setGradient(gp); f.getContentPane().add(lbl); lbl = new JLabel2D("Java Source and Support Filled With Image", JLabel.CENTER); lbl.setFont(bigFont); lbl.setEffectIndex(JLabel2D.EFFECT_IMAGE); ImageIcon icon = new ImageIcon("mars.gif"); lbl.setForegroundImage(icon.getImage()); lbl.setOutlineColor(Color.red); f.getContentPane().add(lbl); lbl = new JLabel2D("Java Source and Support With Image Animation", JLabel.CENTER); lbl.setFont(bigFont); lbl.setEffectIndex(JLabel2D.EFFECT_IMAGE_ANIMATION); icon = new ImageIcon("ocean.gif"); lbl.setForegroundImage(icon.getImage()); lbl.setOutlineColor(Color.black); lbl.startAnimation(400); f.getContentPane().add(lbl); lbl = new JLabel2D("Java Source and Support With Color Animation", JLabel.CENTER); lbl.setFont(bigFont); lbl.setEffectIndex(JLabel2D.EFFECT_COLOR_ANIMATION); lbl.setGradient(gp); lbl.setOutlineColor(Color.black); lbl.startAnimation(400); f.getContentPane().add(lbl); JLabel lbl1 = new JLabel("Plain Java Source and Support For Comparison", JLabel.CENTER); lbl1.setFont(bigFont); lbl1.setForeground(Color.black); f.getContentPane().add(lbl1); WindowListener wndCloser = new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }; f.addWindowListener(wndCloser); f.setVisible(true); }
}
</source>
Multiline label (HTML)
<source lang="java">
import java.awt.Color; import java.awt.FlowLayout; import javax.swing.BorderFactory; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.border.Border; public class Main {
public static void main(String args[]) { JFrame f = new JFrame("Label Demo"); f.setLayout(new FlowLayout()); f.setSize(200, 360); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JLabel label= new JLabel("<html>Use HTML to create
" + "a multiline message." + "
One
Two
Three"); Border border = BorderFactory.createLineBorder(Color.BLACK); label.setBorder(border); f.add(label); f.setVisible(true); }
}
</source>
Putting HTML text on Swing components
<source lang="java">
// : c14:HTMLButton.java // Putting HTML text on Swing components. // <applet code=HTMLButton width=250 height=500></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.JLabel; public class HTMLButton extends JApplet {
private JButton b = new JButton("<html>"+ "
Press me now!");
public void init() { b.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { getContentPane().add( new JLabel("<html>" + "<i>Kapow!")); // Force a re-layout to include the new label: validate(); } }); Container cp = getContentPane(); cp.setLayout(new FlowLayout()); cp.add(b); } public static void main(String[] args) { run(new HTMLButton(), 200, 500); } 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); }
} ///:~
</source>
Scrollable Label
<source lang="java">
import java.awt.Dimension; import java.awt.Rectangle; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JScrollPane; import javax.swing.Scrollable; public class ScrollableLabel extends JLabel implements Scrollable {
public ScrollableLabel(ImageIcon i) { super(i); } public Dimension getPreferredScrollableViewportSize() { return getPreferredSize(); } public int getScrollableBlockIncrement(Rectangle r, int orietation, int direction) { return 10; } public boolean getScrollableTracksViewportHeight() { return false; } public boolean getScrollableTracksViewportWidth() { return false; } public int getScrollableUnitIncrement(Rectangle r, int orientation, int direction) { return 10; } public static void main(String[] args) { JFrame f = new JFrame("JScrollPane Demo"); ImageIcon ii = new ImageIcon("largejexpLogo.gif"); JScrollPane jsp = new JScrollPane(new ScrollableLabel(ii)); f.getContentPane().add(jsp); f.setSize(300, 250); f.setVisible(true); }
}
</source>
Set the Preferred Size
<source lang="java">
import java.awt.Color; import java.awt.Dimension; import java.awt.FlowLayout; import javax.swing.BorderFactory; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.border.Border; public class Main {
public static void main(String args[]) { JFrame f = new JFrame("Label Demo"); f.setLayout(new FlowLayout()); f.setSize(200, 360); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JLabel label= new JLabel("asdf"); Border border = BorderFactory.createLineBorder(Color.BLACK); label.setBorder(border); label.setPreferredSize(new Dimension(150, 100)); f.add(label); f.setVisible(true); }
}
</source>
Setting the Focus of a JTextField Component Using a JLabel Component
<source lang="java">
import java.awt.event.KeyEvent; import javax.swing.JLabel; import javax.swing.JTextField; public class Main {
public static void main(String[] argv) throws Exception { JTextField textfield = new JTextField(25); // Create label and associate with text field JLabel label = new JLabel("Text Label"); label.setDisplayedMnemonic(KeyEvent.VK_L); label.setLabelFor(textfield); }
}
</source>
Shows how displayed Mnemonic and labelFor properties work together
<source lang="java">
//Shows how displayedMnemonic and labelFor properties work together import java.awt.GridLayout; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; public class MnemonicLabels {
public static void main(String[] args) { JTextField firstField = new JTextField(10); JTextField middleField = new JTextField(10); JTextField lastField = new JTextField(10); JLabel firstLabel = new JLabel("First Name", JLabel.RIGHT); firstLabel.setDisplayedMnemonic("F"); firstLabel.setLabelFor(firstField); JLabel middleLabel = new JLabel("Middle Initial", JLabel.RIGHT); middleLabel.setDisplayedMnemonic("I"); middleLabel.setDisplayedMnemonicIndex(7); middleLabel.setLabelFor(middleField); JLabel lastLabel = new JLabel("Last Name", JLabel.RIGHT); lastLabel.setDisplayedMnemonic("L"); lastLabel.setLabelFor(lastField); JPanel p = new JPanel(); p.setLayout(new GridLayout(3, 2, 5, 5)); p.add(firstLabel); p.add(firstField); p.add(middleLabel); p.add(middleField); p.add(lastLabel); p.add(lastField); JFrame f = new JFrame("MnemonicLabels"); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setContentPane(p); f.pack(); f.setVisible(true); }
}
</source>
Solve the problem of text alignment in JLabels
<source lang="java">
import java.awt.Color; import java.awt.GridLayout; import javax.swing.BorderFactory; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.SwingConstants; public class Main {
public static void main(String[] args) { JLabel label1 = new JLabel("BottomRight", SwingConstants.RIGHT); JLabel label2 = new JLabel("CenterLeft", SwingConstants.LEFT); JLabel label3 = new JLabel("TopCenter", SwingConstants.CENTER); label1.setVerticalAlignment(SwingConstants.BOTTOM); label2.setVerticalAlignment(SwingConstants.CENTER); label3.setVerticalAlignment(SwingConstants.TOP); label1.setBorder(BorderFactory.createLineBorder(Color.black)); label2.setBorder(BorderFactory.createLineBorder(Color.black)); label3.setBorder(BorderFactory.createLineBorder(Color.black)); JFrame frame = new JFrame("AlignmentExample"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel p = new JPanel(new GridLayout(3, 1, 8, 8)); p.add(label1); p.add(label2); p.add(label3); p.setBorder(BorderFactory.createEmptyBorder(8, 8, 8, 8)); frame.setContentPane(p); frame.setSize(200, 200); frame.setVisible(true); }
}
</source>
Swing Label Demo
<source lang="java">
/* 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.GridLayout; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; /*
* SwingLabelDemo.java is a 1.4 application that needs one other file: * images/middle.gif */
public class SwingLabelDemo extends JPanel {
public SwingLabelDemo() { super(new GridLayout(3,1)); //3 rows, 1 column JLabel label1, label2, label3; ImageIcon icon = createImageIcon("images/middle.gif", "a pretty but meaningless splat"); //Create the first label. label1 = new JLabel("Image and Text", icon, JLabel.CENTER); //Set the position of its text, relative to its icon: label1.setVerticalTextPosition(JLabel.BOTTOM); label1.setHorizontalTextPosition(JLabel.CENTER); //Create the other labels. label2 = new JLabel("Text-Only Label"); label3 = new JLabel(icon); //Create tool tips, for the heck of it. label1.setToolTipText("A label containing both image and text"); label2.setToolTipText("A label containing only text"); label3.setToolTipText("A label containing only an image"); //Add the labels. add(label1); add(label2); add(label3); } /** Returns an ImageIcon, or null if the path was invalid. */ protected static ImageIcon createImageIcon(String path, String description) { java.net.URL imgURL = SwingLabelDemo.class.getResource(path); if (imgURL != null) { return new ImageIcon(imgURL, description); } 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("SwingLabelDemo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Create and set up the content pane. SwingLabelDemo newContentPane = new SwingLabelDemo(); 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(); } }); }
}
</source>
The text is horizontally and vertically centered
<source lang="java">
import javax.swing.JLabel; public class Main {
public static void main(String[] argv) throws Exception { JLabel label = new JLabel("Text Label", JLabel.CENTER); }
}
</source>
The text is left-justified and bottom-aligned
<source lang="java">
import javax.swing.JLabel; public class Main {
public static void main(String[] argv) throws Exception { JLabel label = new JLabel("Text Label", JLabel.LEFT); label.setVerticalAlignment(JLabel.BOTTOM); }
}
</source>
The text is left-justified and top-aligned
<source lang="java">
import javax.swing.JLabel; public class Main {
public static void main(String[] argv) throws Exception { JLabel label = new JLabel("Text Label", JLabel.LEFT); label.setVerticalAlignment(JLabel.TOP); }
}
</source>
The text is right-justified and bottom-aligned
<source lang="java">
import javax.swing.JLabel; public class Main {
public static void main(String[] argv) throws Exception { JLabel label = new JLabel("Text Label", JLabel.RIGHT); label.setVerticalAlignment(JLabel.BOTTOM); }
}
</source>
The text is right-justified and top-aligned
<source lang="java">
import javax.swing.JLabel; public class Main {
public static void main(String[] argv) throws Exception { JLabel label = new JLabel("Text Label", JLabel.RIGHT); label.setVerticalAlignment(JLabel.TOP); }
}
</source>
The text is right-justified and vertically centered
<source lang="java">
import javax.swing.JLabel; public class Main {
public static void main(String[] argv) throws Exception { JLabel label = new JLabel("Text Label", JLabel.RIGHT); }
}
</source>
Use a ScrollBar in both vertical and horizontal direction
<source lang="java">
import java.awt.BorderLayout; import java.awt.event.AdjustmentEvent; import java.awt.event.AdjustmentListener; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollBar; public class Main extends JPanel {
JLabel label = new JLabel(); public Main() { setLayout(new BorderLayout()); JScrollBar hbar = new JScrollBar(JScrollBar.HORIZONTAL, 30, 20, 0, 300); JScrollBar vbar = new JScrollBar(JScrollBar.VERTICAL, 30, 40, 0, 300); hbar.setUnitIncrement(2); hbar.setBlockIncrement(1); hbar.addAdjustmentListener(new MyAdjustmentListener()); vbar.addAdjustmentListener(new MyAdjustmentListener()); add(hbar, BorderLayout.SOUTH); add(vbar, BorderLayout.EAST); add(label, BorderLayout.CENTER); } public static void main(String s[]) { JFrame frame = new JFrame("Scroll Bar Example"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setContentPane(new Main()); frame.setSize(200, 200); frame.setVisible(true); }
} class MyAdjustmentListener implements AdjustmentListener {
public void adjustmentValueChanged(AdjustmentEvent e) { System.out.println(" New Value is " + e.getValue() + " "); }
}
</source>
Variations on a text and icon label
<source lang="java">
import java.awt.Color; import java.awt.Container; import java.awt.FlowLayout; import javax.swing.BorderFactory; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.SwingConstants; public class ImageLabelExample {
private static Icon icon = new ImageIcon("1.gif"); public static void main(String[] args) { JLabel[] labels = new JLabel[9]; labels[0] = makeLabel(JLabel.TOP, JLabel.LEFT); labels[1] = makeLabel(JLabel.TOP, JLabel.CENTER); labels[2] = makeLabel(JLabel.TOP, JLabel.RIGHT); labels[3] = makeLabel(JLabel.CENTER, JLabel.LEFT); labels[4] = makeLabel(JLabel.CENTER, JLabel.CENTER); labels[5] = makeLabel(JLabel.CENTER, JLabel.RIGHT); labels[6] = makeLabel(JLabel.BOTTOM, JLabel.LEFT); labels[7] = makeLabel(JLabel.BOTTOM, JLabel.CENTER); labels[8] = makeLabel(JLabel.BOTTOM, JLabel.RIGHT); labels[0].setEnabled(false); labels[1].setDisabledIcon(new ImageIcon("2.gif")); labels[1].setEnabled(false); labels[2].setIconTextGap(15); labels[3].setIconTextGap(0); JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Container c = frame.getContentPane(); c.setLayout(new FlowLayout(FlowLayout.CENTER, 3, 3)); for (int i = 0; i < 9; i++) c.add(labels[i]); frame.setSize(350, 150); frame.setVisible(true); } protected static JLabel makeLabel(int vert, int horiz) { JLabel l = new JLabel("Smile", icon, SwingConstants.CENTER); l.setVerticalTextPosition(vert); l.setHorizontalTextPosition(horiz); l.setBorder(BorderFactory.createLineBorder(Color.black)); return l; }
}
</source>
Vertical Alignment: BOTTOM
<source lang="java">
import java.awt.Color; import java.awt.Dimension; import java.awt.FlowLayout; import javax.swing.BorderFactory; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.border.Border; public class Main {
public static void main(String args[]) { JFrame f = new JFrame("Label Demo"); f.setLayout(new FlowLayout()); f.setSize(200, 360); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JLabel label= new JLabel("asdf"); Border border = BorderFactory.createLineBorder(Color.BLACK); label.setBorder(border); label.setPreferredSize(new Dimension(150, 100)); label.setText("Bottom Right"); label.setHorizontalAlignment(JLabel.RIGHT); label.setVerticalAlignment(JLabel.BOTTOM); f.add(label); f.setVisible(true); }
}
</source>
Vertical Alignment: CENTER
<source lang="java">
import java.awt.Color; import java.awt.Dimension; import java.awt.FlowLayout; import javax.swing.BorderFactory; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.border.Border; public class Main {
public static void main(String args[]) { JFrame f = new JFrame("Label Demo"); f.setLayout(new FlowLayout()); f.setSize(200, 360); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JLabel label= new JLabel("asdf"); Border border = BorderFactory.createLineBorder(Color.BLACK); label.setBorder(border); label.setPreferredSize(new Dimension(150, 100)); label.setText("Centered"); label.setHorizontalAlignment(JLabel.CENTER); label.setVerticalAlignment(JLabel.CENTER); f.add(label); f.setVisible(true); }
}
</source>
Vertical Alignment: TOP
<source lang="java">
import java.awt.Color; import java.awt.Dimension; import java.awt.FlowLayout; import javax.swing.BorderFactory; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.border.Border; public class Main {
public static void main(String args[]) { JFrame f = new JFrame("Label Demo"); f.setLayout(new FlowLayout()); f.setSize(200, 360); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JLabel label= new JLabel("asdf"); Border border = BorderFactory.createLineBorder(Color.BLACK); label.setBorder(border); label.setPreferredSize(new Dimension(150, 100)); label.setText("Top Left"); label.setHorizontalAlignment(JLabel.LEFT); label.setVerticalAlignment(JLabel.TOP); f.add(label); f.setVisible(true); }
}
</source>