簡體   English   中英

如何在JFrame中正確居中JPanel(FIXED SIZE)?

[英]How can I properly center a JPanel ( FIXED SIZE ) inside a JFrame?

大家好! 我正在嘗試解決一個很明顯的問題,但我無法解決它。 我正在使用Java / Swing庫開發示例應用程序; 我有一個JFrame和一個JPanel。 我只想達到以下目標:

  1. JPanel 必須在JFrame內部居中。

  2. JPanel 必須 始終具有指定的大小
    setPreferredSize()方法。 它不能在這個尺寸下調整大小。

我嘗試使用GridBagLayout:這是我能做到的唯一方式。

請參閱以下示例:

/* file StackSample01.java */

import java.awt.*;
import javax.swing.*;

public class StackSample01 {
    public static void main(String [] args) {

        JFrame frame = new JFrame();
        JPanel panel = new JPanel();
        panel.setPreferredSize(new Dimension(100, 100));
        panel.setBackground(Color.RED);  

        frame.setLayout(new GridBagLayout());
        frame.add(panel, new GridBagConstraints());
        frame.setSize(new Dimension(200, 200));
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);

    }
}

是一個截圖:

我不會使用GridBagLayout做一件太簡單的事情。 我嘗試了一個最簡單的解決方案,使用Box,但這不起作用:

示例代碼:

/* file StackSample02.java */

import java.awt.*;
import javax.swing.*;

public class StackSample02 {
    public static void main(String [] args) {

        JFrame frame = new JFrame();
        JPanel panel = new JPanel();
        panel.setPreferredSize(new Dimension(100, 100));
        panel.setBackground(Color.RED); // for debug 

        panel.setAlignmentX(JComponent.CENTER_ALIGNMENT); // have no effect

        Box box = new Box(BoxLayout.Y_AXIS);

        box.add(Box.createVerticalGlue());
        box.add(panel);     
        box.add(Box.createVerticalGlue()); // causes a deformation

        frame.add(box);
        frame.setSize(new Dimension(200, 200));
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);

    }
}

是一個截圖,

有任何想法嗎? 謝謝大家 :-)

BoxLayout可以很好地保存你的setXxxSize(),然后只需添加panel.setMaximumSize(new Dimension(100, 100));

你的輸出就是

由setMinimumSize刪除如果Container的大小更大,則注意...)

在此輸入圖像描述在此輸入圖像描述在此輸入圖像描述

import java.awt.*;
import javax.swing.*;

public class CustomComponent12 extends JFrame {

    private static final long serialVersionUID = 1L;

    public CustomComponent12() {
        Box box = new Box(BoxLayout.Y_AXIS);
        box.setAlignmentX(JComponent.CENTER_ALIGNMENT);
        box.add(Box.createVerticalGlue());
        box.add(new CustomComponents12());
        box.add(Box.createVerticalGlue());
        add(box);
        pack();
        setTitle("Custom Component Test / BoxLayout");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setMaximumSize(getMinimumSize());
        setMinimumSize(getMinimumSize());
        setPreferredSize(getPreferredSize());
        setLocation(150, 150);
        setVisible(true);
    }

    public static void main(String[] args) {
        Runnable r = new Runnable() {

            @Override
            public void run() {
                CustomComponent12 main = new CustomComponent12();
            }
        };
        javax.swing.SwingUtilities.invokeLater(r);
    }
}

class CustomComponents12 extends JPanel {

    private static final long serialVersionUID = 1L;

    @Override
    public Dimension getMinimumSize() {
        return new Dimension(100, 100);
    }

    @Override
    public Dimension getMaximumSize() {
        return new Dimension(100, 100);
    }

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(100, 100);
    }

    @Override
    public void paintComponent(Graphics g) {
        int margin = 10;
        Dimension dim = getSize();
        super.paintComponent(g);
        g.setColor(Color.red);
        g.fillRect(margin, margin, dim.width - margin * 2, dim.height - margin * 2);
    }
}

首先,感謝大家。

我又回答了我自己的問題,向大家展示了我的選擇。 請參閱下面的示例代碼; 如您所見,我只包含了實現目標絕對必要的最小步驟。

/* file StackResponse.java */

import java.awt.*;
import javax.swing.*;

public class StackResponse {
    public static void main(String [] args) {

        JPanel panel = new JPanel();
        Dimension expectedDimension = new Dimension(100, 100);

        panel.setPreferredSize(expectedDimension);
        panel.setMaximumSize(expectedDimension);
        panel.setMinimumSize(expectedDimension);

        panel.setBackground(Color.RED); // for debug only

        Box box = new Box(BoxLayout.Y_AXIS);

        box.add(Box.createVerticalGlue());
        box.add(panel);     
        box.add(Box.createVerticalGlue());

        JFrame frame = new JFrame();
        frame.add(box);
        frame.setSize(new Dimension(200, 200));
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame.setMinimumSize(frame.getMinimumSize());   // cannot be resized-

        frame.setVisible(true);

    }
}

在這里你可以看到截圖。

問題解決了。 非常感謝所有人。

使用GridBagLayout創建一個名為“FixedPanel”的面板,並將首選大小設置為幀大小,然后將您的幀添加到FixedPanel中。

Frame = new JFrame("CenterFrame");         
Frame.setLocation(0, 0);
Frame.setSize(new Dimension(400,400));//dim

JPanel FixedPanel = new JPanel(new GridBagLayout());
FixedPanel.setPreferredSize(Frame.getSize());

JPanel myPanel = new JPanel();
myPanel.setPreferredSize(new Dimension(100,100));
myPanel.setBackground(Color.BLACK);

FixedPanel.add(myPanel);
Frame.add(FixedPanel);
Frame.setVisible(true);  

你可以這樣做。 我不得不做一個國際象棋比賽,我希望棋子片總是進入一個JlayeredPane的細胞中心:

private void formMouseReleased(java.awt.event.MouseEvent evt) {
    // TODO add your handling code here:
    if (jl != null)
    {
        jl.setLocation(evt.getX()+10, evt.getY()+10);
        Component com = findComponentAt(evt.getPoint());
        if (com instanceof JPanel)
        {
            // System.out.println("Yes, it's a jpanel");
            ((JPanel)com).add(jl);
            ((JPanel)com).validate();
        }
    }
}

它剛剛擁有

jPanel.setBounds(x,y,1046,503);

其中x是右側空間,y是左側空間。 你必須根據屏幕的高度和寬度計算兩側的空間

使用

panel.setMaximumSize(new Dimension(200,200));
panel.setResizable(false)

代替?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM