JLabel – Show longer text as multiple lines?

Just another example, showing that, with the right layout manager, text wrapped in HTML tags will automatically wrap to the available space… public class TestHTMLLabel { public static void main(String[] args) { new TestHTMLLabel(); } public TestHTMLLabel() { EventQueue.invokeLater(new Runnable() { @Override public void run() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | … Read more

JLabel images array

For comparison, I’ve re-factored @HFOE’s example so that Ground implements Icon and indexes the array returned by values(). As value is an implementation detail, int[][] MAP could instead be Ground[][] MAP. Update: This variation illustrates Ground[][] MAP and adds TexturePaint. import java.awt.Color; import java.awt.Component; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GridLayout; import java.awt.TexturePaint; import java.awt.geom.Rectangle2D; import … Read more

How to add hyperlink in JLabel?

You can do this using a JLabel, but an alternative would be to style a JButton. That way, you don’t have to worry about accessibility and can just fire events using an ActionListener. public static void main(String[] args) throws URISyntaxException { final URI uri = new URI(“http://java.sun.com”); class OpenUrlAction implements ActionListener { @Override public void … Read more

Centering a JLabel on a JPanel

Here are four ways to center a component: import java.awt.*; import javax.swing.*; import javax.swing.border.*; class CenterComponent { public static JLabel getLabel(String text) { return getLabel(text, SwingConstants.LEFT); } public static JLabel getLabel(String text, int alignment) { JLabel l = new JLabel(text, alignment); l.setBorder(new LineBorder(Color.RED, 2)); return l; } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() … Read more