我有一个 GridBagLayout
JPanel
包含在 BorderLayout
JPanel
中。我希望 GridBagLayout 能够根据其内部网格调整自身大小。相反,它会根据 BorderLayout
调整自身大小,并在内部网格的两侧添加空白(GridBagLayout
中的所有权重均为 0)。
这个想法是我希望 BorderLayout
提供空白(用胶水)。相反,GridBagLayout 提供空白;您可以通过查看我添加的 TitleBorder
看到这一点。
原因是当我将 GridBagLayout
发送到打印机时,我不希望包含所有空白。
import java.awt.*;
import javax.swing.*;
public class GBLDemo {
public static void main (String[] args) {
JFrame jframe = new JFrame("GridBagLayout Demo");
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container contentPane = new JPanel(new BorderLayout());
jframe.setContentPane(contentPane);
GridBagConstraints gbc = new GridBagConstraints();
JPanel gb = new JPanel(new GridBagLayout());
contentPane.add(gb);
gbc.gridx = gbc.gridy = 0;
gb.add(new JLabel("Look "), gbc);
gbc.gridx = 1;
gb.add(new JLabel("at"), gbc);
gbc.gridx = 0;
gbc.gridy = 1;
gb.add(new JLabel("the "), gbc);
gbc.gridx = 1;
gb.add(new JLabel("border"), gbc);
gb.setBorder(BorderFactory.createTitledBorder("Border"));
jframe.pack();
jframe.setVisible(true);
jframe.setSize(640, 480);
} // main(args)
} // GBLDemo
这是我想要的 ASCII 模型:
+-------------------------------------------+ | | | | | +Border-----+ | | |Look at | | | | the border| | | +-----------+ | | | | | +-------------------------------------------+
这是上面代码生成的显示:
最佳答案
将组件以其首选大小(例如问题代码中的 contentPane
)居中的一个好技巧是将其作为单个组件添加到具有网格包布局的容器中,而不需要指定约束。
这是上面的代码,经过修改可以做到这一点。
import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class GBLDemo {
private JComponent ui = null;
GBLDemo() {
initUI();
}
private Container getContentPanel() {
Container contentPane = new JPanel(new BorderLayout());
GridBagConstraints gbc = new GridBagConstraints();
JPanel gb = new JPanel(new GridBagLayout());
contentPane.add(gb);
gbc.gridx = gbc.gridy = 0;
gb.add(new JLabel("Look "), gbc);
gbc.gridx = 1;
gb.add(new JLabel("at"), gbc);
gbc.gridx = 0;
gbc.gridy = 1;
gb.add(new JLabel("the "), gbc);
gbc.gridx = 1;
gb.add(new JLabel("border"), gbc);
gb.setBorder(BorderFactory.createTitledBorder("Border"));
return contentPane;
}
public void initUI() {
if (ui!=null) return;
// A single object added to a grid bag layout with no constraint,
// will be centered within the available space.
ui = new JPanel(new GridBagLayout());
ui.setBorder(new EmptyBorder(4,4,4,4));
ui.add(getContentPanel());
}
public JComponent getUI() {
return ui;
}
public static void main(String[] args) {
Runnable r = new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception useDefault) {
}
GBLDemo o = new GBLDemo();
JFrame f = new JFrame(o.getClass().getSimpleName());
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
f.setContentPane(o.getUI());
f.pack();
f.setMinimumSize(f.getSize());
f.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
}
}
关于java - 使 GridBagLayout JPanel 大小适合内容,而不是容器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44615774/