65718

How to make jLabels stay attached to the corners of a window form, despite resizing the form in java

Question:

I have 4 jLabels in my java program, which i placed in 4 corners I want them to stay there despite user resizing the window. I have written the code for the labels, but cannot seem to figure out how to keep them glued to each corner.

here is my code for the jLabels

JLabel label_1 = new JLabel(""); label_1.setEnabled(false); label_1.setBounds(0, 0, 19, 19); contentPane.add(label_1); JLabel label_2 = new JLabel(""); label_2.setEnabled(false); label_2.setBounds(0, 242, 19, 19); contentPane.add(label_2); JLabel label_3 = new JLabel(""); label_3.setEnabled(false); label_3.setBounds(549, 242, 19, 19); contentPane.add(label_3); JLabel label_4 = new JLabel(""); label_4.setEnabled(false); label_4.setBounds(549, 0, 19, 19); contentPane.add(label_4);

Thanks

Answer1:

<ol><li>Don't use null layouts </li> <li>Don't use setBounds(...)</li> <li>Do use proper layout managers. Read the <a href="http://docs.oracle.com/javase/tutorial/uiswing/layout/index.html" rel="nofollow">Layout Manager Tutorials</a> for all the gory details.</li> </ol>

Note that by using a null layout and setBounds, you ham-string your application's layout to being very rigid, very difficult to debug, enhance, and modify, and you also create a GUI that might look good on your box, but likely will not look good on another box using a different OS, or even the same OS with a slightly different screen resolution.

For example, using a GridBagLayout:

import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import javax.swing.*; import static java.awt.GridBagConstraints.*; public class LabelLayout extends JPanel { private static final int[] ANCHORS = {NORTHWEST, SOUTHWEST, NORTHEAST, SOUTHEAST}; public LabelLayout() { setLayout(new GridBagLayout()); for (int i = 0; i < ANCHORS.length; i++) { GridBagConstraints gbc = new GridBagConstraints(); gbc.gridx = i / 2; gbc.gridy = i % 2; gbc.gridheight = 1; gbc.gridwidth = 1; gbc.weightx = 1.0; gbc.weighty = 1.0; gbc.anchor = ANCHORS[i]; add(new JLabel("Label " + (i + 1)), gbc); } } private static void createAndShowGui() { JFrame frame = new JFrame("Labels"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().add(new LabelLayout()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGui(); } }); } }

A couple other notes:

<ul><li>I try to avoid using GridBagLayouts since they are one of the more complex layouts, but for your problem, they work nicely and simply.</li> <li>Your problem can also be solved by using nested JPanels each using a simpler layout such as a BorderLayout.</li> </ul><hr />

Demo program, iteration number 2 that shows two GUI's, one using GridBagLayout and the other using nested JPanels, each using BorderLayout:

import java.awt.BorderLayout; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import javax.swing.*; import static java.awt.GridBagConstraints.*; public class LabelLayout { private static final int[] ANCHORS = { NORTHWEST, NORTHEAST, SOUTHWEST, SOUTHEAST }; private JPanel gridBagPanel = new JPanel(new GridBagLayout()); private JPanel borderPanel = new JPanel(new BorderLayout()); public LabelLayout() { for (int i = 0; i < ANCHORS.length; i++) { GridBagConstraints gbc = new GridBagConstraints(); gbc.gridx = i % 2; gbc.gridy = i / 2; gbc.gridheight = 1; gbc.gridwidth = 1; gbc.weightx = 1.0; gbc.weighty = 1.0; gbc.anchor = ANCHORS[i]; gridBagPanel.add(new JLabel("Label " + (i + 1)), gbc); } JPanel northPanel = new JPanel(new BorderLayout()); JPanel southPanel = new JPanel(new BorderLayout()); northPanel.add(new JLabel("Label 1"), BorderLayout.WEST); northPanel.add(new JLabel("Label 2"), BorderLayout.EAST); southPanel.add(new JLabel("Label 3"), BorderLayout.WEST); southPanel.add(new JLabel("Label 4"), BorderLayout.EAST); borderPanel.add(northPanel, BorderLayout.NORTH); borderPanel.add(southPanel, BorderLayout.SOUTH); } public JPanel getGridBagPanel() { return gridBagPanel; } public JPanel getBorderPanel() { return borderPanel; } private static void createAndShowGui() { LabelLayout labelLayout = new LabelLayout(); JFrame frame = new JFrame("Label GridBagLayout"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().add(labelLayout.getGridBagPanel()); frame.pack(); frame.setLocationByPlatform(true); frame.setVisible(true); frame = new JFrame("Label BorderLayout"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().add(labelLayout.getBorderPanel()); frame.pack(); frame.setLocationByPlatform(true); frame.setVisible(true); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGui(); } }); } }

Recommend

  • cannot cast array data when a saved classifier is called
  • Disallow dynamic URL in robots.txt
  • Assign a Series to several Rows of a Pandas DataFrame
  • Java: do methods inherit a JRE super class, like classes inherit Object?
  • Ruby YAML write without aliases
  • 'cannot filter palette images' error when doing a ImageEnhance.Sharpness()
  • Is it possible to change backround color of editor and autocomplete tooltips in Visual Studio?
  • FIR filter in CUDA (as a 1D convolution)
  • Launching a new command window from Golang in Windows
  • Can't access Tomcat 7 Manager app when running from Eclipse
  • Is there a way to call library thread-local init/cleanup on thread creation/destruction?
  • Classic ASP URL Rewriting
  • Efficient User-Agent Regex to find Safari in Python
  • Exception gevent.hub.LoopExit: LoopExit('This operation would block forever',)
  • How to autopopulate a field in SugarCRM form
  • Can I programmatically choose the Android layout folder?
  • Ajax calls do not work in IE unless you fiddle with security settings
  • OOP Javascript - Is “get property” method necessary?
  • Keep this build forever option - Jenkins
  • Master page gives error
  • Different response to non-authenticated users and AJAX calls
  • C# - Serializing and deserializing static member
  • Java applet as stand-alone Windows application?
  • Incrementing object id automatically JS constructor (static method and variable)
  • How to set my toolbar fixed while scrolling android
  • How to show dropdown in excel using jrxml (jasper api)?
  • Redux, normalised entities and lodash merge
  • Do create extension work in single-user mode in postgres?
  • Apache 2.4 - remove | delete | uninstall
  • AT Commands to Send SMS not working in Windows 8.1
  • Cannot Parse HTML Data Using Android / JSOUP
  • Comma separated Values
  • Windows forms listbox.selecteditem displaying “System.Data.DataRowView” instead of actual value
  • Error creating VM instance in Google Compute Engine
  • Hits per day in Google Big Query
  • How do you join a server to an Active Directory (domain)?
  • Understanding cpu registers
  • how does django model after text[] in postgresql [duplicate]
  • apache spark aggregate function using min value
  • Sorting a 2D array using the second column C++