Abdul Jabbar
Abdul Jabbar

Reputation: 5931

Auto adjust component size in java

I have JFrame with different components like buttons and labels. I want my labels to auto adjust its height when screen resolution changes. I mostly work with NetBeans GUI components (drag and drop).

enter image description here

When the height resolution increases then every component height increases like this

enter image description here

Is there any way of doing so with some kind of layout etc or I have to manually get screen resolution and then repaint each component?

I am not a really manually coding for each component because mostly I just drag and drop in NetBeans.

Upvotes: 2

Views: 2925

Answers (2)

splungebob
splungebob

Reputation: 5415

One way to detect changes to the screen resolution is to register an AWTEventListener.

When fired, you can check the resolution against the last known value and adjust your frame size accordingly. This is where your choice of LayoutManager comes into play.

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;

public class ResolutionChangedDemo implements Runnable
{
  private Dimension lastScreenSize;
  private JFrame frame;

  public static void main(String[] args)
  {
    SwingUtilities.invokeLater(new ResolutionChangedDemo());
  }

  public void run()
  {
    lastScreenSize = Toolkit.getDefaultToolkit().getScreenSize();

    AWTEventListener listener = new AWTEventListener()
    {
      @Override
      public void eventDispatched(AWTEvent event)
      {
        Dimension actualScreenSize = Toolkit.getDefaultToolkit().getScreenSize();

        if (! lastScreenSize.equals(actualScreenSize))
        {
          System.out.println("resolution changed");
          lastScreenSize = actualScreenSize;

          // Here is where you would resize your frame appropriately
          // and the LayoutManager would do the rest
        }
      }
    };

    Toolkit.getDefaultToolkit().addAWTEventListener(listener, AWTEvent.PAINT_EVENT_MASK);

    frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(400, 400);
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
  }
}

Upvotes: 2

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285405

The left side should be a JPanel that uses a GridLayout(0, 1) that then holds the 4 JLabels. The whole thing can be placed into a GridBagLayout-using JPanel or perhaps a BoxLayout.

I am not a really manually coding for each component because mostly I just drag and drop in NetBeans.

and don't do this. If you want this functionality, read up on and use the layout managers rather than blindly dragging and dropping. You know that you can also create JPanels with NetBeans code generation tools and tell the JPanels what specific layouts to use.

Upvotes: 4

Related Questions