gpt4 book ai didi

java - 为什么按钮/标签/文本未在我的背景上显示/居中?

转载 作者:行者123 更新时间:2023-11-30 04:19:22 24 4
gpt4 key购买 nike

我正在使用 Java Swing 为我的程序编写 GUI。我使用以下 link 编写了一个类来扩展我的 JFrame 。我的问题是我的按钮根本不在背景的中心。也就是说,像这样:

--------------------------------------
| | |
| | |
| my picture | |
--------------------------------------
| | | |
| | Label | |
| | text | |
| | button | |
--------------------------------------

我在下面包含了一些伪代码:

    public class demo extends JFrame implements ActionListener
{
class demo()
{

CustomJFrame frame = new CustomJFrame();
JPanel pane = new JPanel(new GridBagLayout());

GridBagConstraints c = new GridBagConstraints();
JTextField dummyText = new JTextField("I'm some text");
JLabel dummyLabel = new JLabel("I'm a label);

JButton dummyButton = new JButton("I'm a button");

c.fill = GridBagConstraints.BOTH;
c.gridx = 0;
c.gridy = 0;
pane.add(dummyText, c);

c.fill = GridBagConstraints.BOTH;
c.gridx = 1;
c.gridy = 0;
pane.add(dummyLabel, c);

c.fill = GridBagConstraints.BOTH;
c.gridx = 0;
c.gridy = 2;
pane.add(dummyButton, c);

frame.add(pane);

}

}

这是我基于链接的自定义 JFrame 类。

public class CustomJFrame extends JFrame
{
private ImageIcon background = new ImageIcon("mypicture.png");
private JLabel label = new JLabel(background);

public CustomJFrame()
{
this.SetDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Traffic Alert Demo");
setSize(800,480); //specific to my picture though
add(label, BorderLayout.CENTER);
setVisible(true);
}
}

所以我想要某种方式能够让按钮位于我的图片的中心,或者至少能够让我将按钮移动到图片上我喜欢的任何地方。到目前为止我还没有发现任何可以帮助我的东西,有什么想法吗?或者是我的图片,因为我把它作为标签,与 GridBag 交互得很差?请帮忙。

问候,极客

最佳答案

我能够通过将我的 Pane 视为玻璃对象来解决这个问题。因此,我们有以下伪代码:

public class demo extends JFrame implements ActionListener
{
class demo()
{

CustomJFrame frame = new CustomJFrame();
JPanel pane = new JPanel(new GridBagLayout());

GridBagConstraints c = new GridBagConstraints();
JTextField dummyText = new JTextField("I'm some text");
JLabel dummyLabel = new JLabel("I'm a label);

JButton dummyButton = new JButton("I'm a button");

c.fill = GridBagConstraints.BOTH;
c.gridx = 0;
c.gridy = 0;
pane.add(dummyText, c);

c.fill = GridBagConstraints.BOTH;
c.gridx = 1;
c.gridy = 0;
pane.add(dummyLabel, c);

c.fill = GridBagConstraints.BOTH;
c.gridx = 0;
c.gridy = 2;
pane.add(dummyButton, c);

pane.setOpaque(false);
frame.setGlassPane(pane);
pane.setVisible(true);

}

}

关键是下面这个想法。如果你想要一个前面有按钮和东西的背景。告诉 JFrame 这是一 block 玻璃板。然后,您可以设置与此 Pane 关联的按钮和对象不透明和可见。这里的所有都是它的。

关于java - 为什么按钮/标签/文本未在我的背景上显示/居中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17494985/

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