简体   繁体   English

Java-GridBagLayout位置JLabel

[英]Java - GridBagLayout position JLabel

I use a GridBagLayout and place a JLabel on it as the picture shows. 如图所示,我使用了GridBagLayout并在其上放置了一个JLabel I managed to set the size of the JLabel to the desired one via ipadx and ipady but I don't seem to work with the position of it. 我设法通过ipadxipadyJLabel的大小设置为所需的大小,但是我似乎ipady它的位置。 It seems it is always centered on the middle while I'd like to start from the red dot and don't reposition itself as I resize the window. 似乎总是在中间居中,而我想从红点开始,并且在调整窗口大小时不要重新定位自身。 What should I do? 我该怎么办?

在此处输入图片说明

Thanks. 谢谢。 The code I use is also: 我使用的代码也是:

GridBagLayout gbl = new GridBagLayout();
setLayout(gbl);
GridBagConstraints gbc = new GridBagConstraints();

JLabel jl = new JLabel("This is a jlabel!", SwingConstants.CENTER);
jl.setBorder(BorderFactory.createLineBorder(Color.black));
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.ipadx = 87;
gbc.ipady = 220;
add(jl, gbc);

I improved it... now you can work with insets to position that label around JFrame , but after some research I would recommend to choose different layout manager . 我改进了它...现在您可以使用inset将标签定位在JFrame周围,​​但是经过研究后,我建议选择其他布局管理器

So your code would look like: 因此您的代码如下所示:

Dimension d = new Dimension(350, 400);
GridBagLayout gbl = new GridBagLayout();
JFrame frame = new JFrame("Heloo");
frame.setLayout(gbl);
GridBagConstraints gbc = new GridBagConstraints();

JLabel jl = new JLabel("This is a jlabel!", SwingConstants.CENTER);
jl.setBorder(BorderFactory.createLineBorder(Color.black));
gbc.ipadx = 87;
gbc.ipady = 220;
gbc.insets = new Insets(0, 0, 360, 340);// here work with JFrame size!!

Hope this code will help you :) 希望这段代码对您有所帮助:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM