我有一个非常简单的任务,就是想要在另一个 JPanel
内有一个漂亮的居中 JPanel
。父级设置为 900, 550
,子级应约为 200,400
左右。
为此,我想给父级一个 BorderLayout
,然后设置子级的 setPreferredSize(200, 400)
。这个 child 将位于CENTER
。两个空 JPanel 将位于 EAST
和 WEST
上。当然这没有用。当然,给两个侧面板设置一个setPreferredSize()
确实有效。问题是缩小框架会导致中心 Pane 消失。
这里有一些示例代码应该可以显示问题:
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Component;
import java.awt.Dimension;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Temporary {
public static Temporary myObj = null;
private JFrame mainFrame;
public void go(){
mainFrame = new JFrame("Swing");
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setPreferredSize(new Dimension(900,550));
JPanel mainCards = new JPanel(new CardLayout());
mainCards.add(loginLayer(), "Login");
mainFrame.setContentPane(mainCards);
mainFrame.pack();
mainFrame.setLocationRelativeTo(null);
mainFrame.setVisible(true);
}
public JPanel loginLayer(){
JPanel masterPane = new JPanel(new BorderLayout());
JPanel centerPane = new JPanel();
centerPane.setLayout(new BoxLayout(centerPane, BoxLayout.Y_AXIS));
centerPane.setPreferredSize(new Dimension(100,200));
JLabel label = new JLabel("Swing is overly");
label.setAlignmentX(Component.CENTER_ALIGNMENT);
centerPane.add(label);
JButton button = new JButton("complicated");
button.setAlignmentX(Component.CENTER_ALIGNMENT);
centerPane.add(button);
JTextField textField = new JTextField(10);
centerPane.add(textField);
JPanel filler = new JPanel();
JPanel filler2 = new JPanel();
masterPane.add(filler, BorderLayout.WEST);
masterPane.add(centerPane, BorderLayout.CENTER);
masterPane.add(filler2, BorderLayout.EAST);
return masterPane;
}
public static void main(String[] args){
myObj = new Temporary();
myObj.go();
}
}
最佳答案
BorderLayout
本质上会为 CENTER
组件提供尽可能多的可用空间。这就是它的设计方式。
如果您希望组件在父容器中居中,但保持其首选大小,则应考虑使用 GridBagLayout
。没有任何额外的限制,这应该可以达到您想要的结果
例如...
public JPanel loginLayer(){
JPanel masterPane = new JPanel(new GridBagLayout);
JPanel centerPane = new JPanel();
centerPane.setLayout(new BoxLayout(centerPane, BoxLayout.Y_AXIS));
JLabel label = new JLabel("Swing is overly");
label.setAlignmentX(Component.CENTER_ALIGNMENT);
centerPane.add(label);
JButton button = new JButton("complicated");
button.setAlignmentX(Component.CENTER_ALIGNMENT);
centerPane.add(button);
JTextField textField = new JTextField(10);
centerPane.add(textField);
masterPane.add(centerPane);
// Add additional borders to providing padding around the center pane
// as you need
return masterPane;
}
我也会避免以这种方式主动设置组件的首选大小,因为您添加到其中的组件可能会超出您的预期,而是使用 EmptyBorder
之类的东西(例如)在组件及其内容周围添加额外的空白
关于Java Swing简单中心的JPanel在其他JPanel中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20913632/