简体   繁体   中英

Rescale JFrame content

I am creating a JFrame , and when the window is expanded I want the content to stay centered, instead of staying the same distance away from the side. I am using WindowBuilder on Eclipse.

Is there a quick way to do this?

One way, have the container use a GridBagLayout and add the single content to the container without constraints.

For example:

import java.awt.GridBagLayout;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;

import javax.imageio.ImageIO;
import javax.swing.*;

public class CenteredContent extends JPanel {
   public static final String IMG_PATH = "https://duke.kenai.com/iconSized/duke.gif";

   public CenteredContent() throws IOException {
      URL imgUrl = new URL(IMG_PATH);
      BufferedImage img = ImageIO.read(imgUrl);
      Icon imgIcon = new ImageIcon(img);
      JLabel label = new JLabel(imgIcon);

      setLayout(new GridBagLayout());
      add(label);
   }

   private static void createAndShowGui() {
      CenteredContent mainPanel = null;
      try {
         mainPanel = new CenteredContent();
      } catch (IOException e) {
         e.printStackTrace();
         System.exit(-1);
      }

      JFrame frame = new JFrame("CenteredContent");
      frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

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

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