使用 AbsoluteLayout 的 JFrame 边缘是否可以有一些额外的空间?当我将一个按钮作为 JFrame 最下方的组件时,它会直接定位在 JFrame 窗口的底部边缘上,而且看起来很糟糕。我想知道是否有办法在使用 AbsoluteLayout 时在组件和 JFrame 边缘之间添加一点额外的空间。
最佳答案
建议:
- 当您将组件添加到 JFrame 时,您实际上是将其添加到 JFrame 的 contentPane 中。要为 contentPane 提供“缓冲区”边框,请考虑为其提供一个 EmptyBorder(...) ,其参数为 int 常量,表示组件周围所需的边框数量。
- 避免对任何内容使用“绝对”布局,尤其是将组件放置在布局管理器易于放置的位置,例如 GUI 的底部。
例如,请注意在下面的代码中创建的 GUI 中,由于空边框,中心和底部的 JPanel 不会延伸到 GUI 的边缘:
import java.awt.BorderLayout;
import java.awt.Dimension;
import javax.swing.*;
public class ButtonAtBottom {
private static void createAndShowGui() {
JPanel bottomPanel = new JPanel();
bottomPanel.add(new JButton("Bottom Button"));
bottomPanel.setBorder(BorderFactory.createTitledBorder("Bottom Panel"));
JPanel centerPanel = new JPanel();
centerPanel.setBorder(BorderFactory.createTitledBorder("Center Panel"));
JPanel mainPanel = new JPanel(new BorderLayout());
mainPanel.add(centerPanel, BorderLayout.CENTER);
mainPanel.add(bottomPanel, BorderLayout.PAGE_END);
// **** here I add the border to the mainPanel which I'll
// make into the contentPane
int eb = 25;
mainPanel.setBorder(BorderFactory.createEmptyBorder(eb, eb, eb, eb));
// don't set the preferredSize per Kleopatra, but am doing it
// here simply to make code shorter for this sscce
mainPanel.setPreferredSize(new Dimension(500, 400));
JFrame frame = new JFrame("ButtonAtBottom");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
关于Java:AbsoluteLayout 中的额外空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9507310/