简体   繁体   中英

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 ).

在此处输入图片说明

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

在此处输入图片说明

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.

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.

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);
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM