我目前正试图正确对齐我框架内的一些组件。我正在使用GridBagLayout,但看起来这条线路正在制造麻烦:
private Image image;
public MainClass(Image image){
this.image = image;
GridBagConstraints c = new GridBagConstraints();
this.setOpaque(false);
this.setLayout(new GridBagLayout());
c.gridx = 0;
c.gridy = 0;
this.add(new JButton("1"), c);
c.gridx = 0;
c.gridy = 1;
this.add(new JButton("2"), c);
c.gridx = 0;
c.gridy = 2;
this.add(new JButton("3", c);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, this);
}
public static void main(String[] args) throws IOException {
BufferedImage myImage = ImageIO.read(new File("images/city.png"));
JFrame frame = new JFrame();
frame.setContentPane(new MainClass(myImage));
frame.setSize(600, 375);
frame.setUndecorated(true);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
我想把按钮放在中间,但它不起作用。如果我评论它,一切都很好。还尝试使用BorderLayout和CENTER创建另一个面板但它的结果相同。我想要一个背景图像到我的JFrame。我该怎么办 ?或者我做错了什么?
Webservice.Authenticate.Credential credential = new Webservice.Authenticate.Credential
{
Username = "myUserName",
Password = GetMD5("myPassword"), // See below for a MD5 encoding example method
ApplicationId = new Guid("00000000-0000-0000-0000-000000000000"), //YOUR ID HERE
IdentityId = new Guid("00000000-0000-0000-0000-000000000000") //Default is empty guid (no need to edit this)
};
//编辑:我刚刚意识到我正在尝试将面板添加到我的框架中......初看起来效果非常好。
答案 0 :(得分:1)
frame.setContentPane(new ImagePanel(myImage));
frame.add(new MainClass());
首先将ImagePanel设置为内容窗格即可。然后你将MainClass()添加到框架,这可能是好的。这意味着MainClass将被添加到ImagePanel。
如果我评论它,一切都很好。
默认情况下,JPanel使用FlowLayout
,因此MainClass将位于面板顶部的中心位置。
您需要将ImagePanel的布局设置为BorderLayout
。然后它应该像将MainClass直接添加到框架一样。
答案 1 :(得分:0)
JLabel background = new JLabel(new ImageIcon(ImageIO.read(...))); setContentPane(背景)
...
添加所有其他按钮
答案 2 :(得分:-1)
最直接和最残忍的答案是 - 不要使用在大多数情况下难以使用的Java Swings布局管理器。尝试一些第三方
我强烈建议来自http://www.miglayout.com/的MIG布局。它是一个非常强大,灵活,易于使用的旅行经理,拥有不错的文档和示例。