我正在使用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严重交互?请帮忙。
此致 令人讨厌
答案 0 :(得分:2)
我能够通过将窗格视为玻璃对象来解决此问题。因此,我们有以下伪代码:
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是一个玻璃窗格。然后,您可以设置与此窗格关联的按钮和对象,并且不透明和可见。这里的所有都是它的。