gpt4 book ai didi

Java:Swing:设置JButton的位置

转载 作者:行者123 更新时间:2023-12-02 07:53:39 29 4
gpt4 key购买 nike

我想实现以下布局:

--------------------------------------------
| |
| |
| |
| |
| |
| ---------- |
| | OK | |
| ---------- |
| |
--------------------------------------------

我想设置按钮的大小,它应该在 JFrame 的南边位置居中,但它不应该具有 JFrame 的完整宽度,也不应该完全位于 JFrame 的底部,它应该有一个“边距”。还可以设置按钮的绝对像素位置,因为 JFrame 具有固定的宽度/高度。目前该按钮具有完整的 JFrame 宽度/高度。请注意,JFrame 有背景图像。我的代码:

JFrame j = new JFrame("Foobar");
BufferedImage myImage = null;
try {
myImage = ImageIO.read(new File("background.png"));
} catch (Exception ex) {}

JPanel p = new ImagePanel(myImage);
p.setLayout(new BorderLayout());

JButton button = new JButton("OK");
button.setSize(80, 200);
button.setFont(new Font("Arial", 1, 40));
p.add(button);
f.add(p);
<小时/>
class ImagePanel extends JPanel {
private Image image;
public ImagePanel(Image image) {
this.image = image;
}
@Override
protected void paintComponent(Graphics g) {
g.drawImage(image, 0, 0, null);
}
}

最佳答案

简单的布局管理器的组合应该可以解决问题。例如,主 JPanel 可能有一个 EmptyBorder,您可以在其中添加适当的边距,并且可以使用 BorderLayout。然后添加一个使用FlowLayout布置的SouthPanel JPanel FlowLayout.CENTER(默认),并且您可以将您的JButton添加到这个southPanel。不要忘记调用 pack 并确保所有 JPanel 都调用 setOpaque(false)。例如:

  JFrame f = new JFrame("Foobar");
BufferedImage myImage = null;
try {
myImage = ImageIO.read(new File("background.png"));
} catch (Exception ex) {}

JPanel p = new ImagePanel(myImage);
p.setLayout(new BorderLayout());
int gap = 15;
p.setBorder(BorderFactory.createEmptyBorder(gap, gap, gap, gap));

JPanel southPanel = new JPanel(new FlowLayout(FlowLayout.CENTER)); // new FlowLayout not needed
southPanel.setOpaque(false);
JButton button = new JButton("OK");
//button.setSize(80, 200);
button.setPreferredSize(new Dimension(80, 200)); // ?? I don't like this.
button.setFont(new Font("Arial", 1, 40));

southPanel.add(button);
p.add(southPanel, BorderLayout.SOUTH);
f.add(p);
f.pack(); // call after everything has been added
f.setLocationRelativeTo(null); // to center
f.setVisible(true);

关于Java:Swing:设置JButton的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4478021/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com