JButtons 没有获得正确的大小和位置
您好,我对某些按钮有疑问,
我想使用 JButtons 创建一个简单的 GUI,但是当我启动应用程序时,按钮位置和大小每次启动应用程序时都会发生变化。 我使用这个代码:
usr_in.setSize(120,40);
usr_in.setLocation(10,40); JButton
usr_in 是一个像这样创建的
JButton usr_ro = new JButton("Users");
:在这里我设置它们:
menu.setLayout(new GridLayout(1, 1, 0, 3));
menu.add(usr_ro);
我使用库:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import java.beans.*;
import java.applet.*;
import java.*;
感谢帮助
Hello I have a Problem with some Buttons
I would like to create a simple GUI with JButtons but when I start the App the Buttons Positions and Size changes every Time when i start the App.
I use this Code:
usr_in.setSize(120,40);
usr_in.setLocation(10,40);
usr_in is a JButton
Created Like this:
JButton usr_ro = new JButton("Users");
and here I set them:
menu.setLayout(new GridLayout(1, 1, 0, 3));
menu.add(usr_ro);
I use the Libs:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import java.beans.*;
import java.applet.*;
import java.*;
thanks for help
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先,有两个问题:
menu
的类型是什么?usr_in
与usr_ro
相同吗?名称显然不相同,但您的措辞暗示它们应该是相同的。从您到目前为止提供的内容来看,问题似乎是您试图以两种不同的方式设置按钮的位置。在一个地方,您使用的是
setLocation()
,它“由该组件父级的坐标空间中的 x 和 y 参数指定”。 (来源)随后,您将使用
GridLayout
,它以自己的方式设置位置:使它们适合网格。 (来源)我不知道如果您同时应用两者,则认为该行为不是明确定义的,尽管我有点惊讶的是您每次都没有得到相同的不需要的行为。First off, two questions: what is the type of
menu
? And isusr_in
the same asusr_ro
? The names obviously aren't the same, but your wording implies that they are meant to be the same.From what you've provided so far, the problem seems to be that you're trying to set the location of the button(s) in two different ways. In one place, you're using
setLocation()
, which "is specified by the x and y parameters in the coordinate space of this component's parent." (source)Later, you're using a
GridLayout
, which sets locations in its own way: fitting them to the grid. (source) I don't think the behavior is well-defined if you apply both, though I am a little surprised that you're not getting the same unwanted behavior every time.我发现最好的做法是将按钮放在 JPanel 中,它使用 FlowLayout。如果您没有过多地调整父容器布局,则按钮的大小不应变化。
I find the best practice is to put your button(s) in a JPanel, which uses a FlowLayout. Your button shouldn't varies in size if you're not fiddling too much with the parent container layout.