java 如何以像素为单位设置 JTextField 的大小
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13848709/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to set size of JTextField in pixels
提问by Tom
Hey I was just wondering if there is a way to set JTextField width for example 50% of the screen size. I know how to get the dimensions of screen just JTextField sets it to number of characters not pixels
嘿,我只是想知道是否有办法将 JTextField 宽度设置为屏幕大小的 50%。我知道如何获取屏幕尺寸只是 JTextField 将其设置为字符数而不是像素数
textfield = new JTextField("Way hello there", 20);
textfield = new JTextField("你好", 20);
is there a way to do this ?
有没有办法做到这一点 ?
回答by Reimeus
Setting the size of JTextField
in pixels leads you down the path of using absolute positioning which is generally not advisable. From Doing Without a Layout Manager
设置JTextField
以像素为单位的大小会使您走上使用绝对定位的道路,这通常是不可取的。从没有布局管理器做起
Although it is possible to do without a layout manager, you should use a layout manager if at all possible. Layout managers also can be reused easily by other containers, as well as other programs.
尽管可以不使用布局管理器,但您应该尽可能使用布局管理器。布局管理器也可以很容易地被其他容器以及其他程序重用。
Have a look at the functionality offered by existing layout managersand avoid using the setXXXSize()component methods. For example, GridLayout
( or even GridBagLayout
) can be used to size a JTextField
width to 50% of a frame client area.
查看现有布局管理器提供的功能并避免使用setXXXSize()组件方法。例如,GridLayout
( 甚至GridBagLayout
) 可用于将JTextField
宽度调整为框架客户区的 50%。
回答by Viral Patel
You may use setSize() method to set the size of JTextField component.
您可以使用 setSize() 方法来设置 JTextField 组件的大小。
public void setSize(int width,
int height)
Resizes this component so that it has width width and height height. Parameters: width- the new width of this component in pixels height- the new height of this component in pixels
调整此组件的大小,使其具有宽度宽度和高度高度。参数: width- 此组件的新宽度(以像素为单位) height- 此组件的新高度(以像素为单位)
Javadoc: http://docs.oracle.com/javase/1.4.2/docs/api/java/awt/Component.html#setSize(int, int)
Javadoc:http: //docs.oracle.com/javase/1.4.2/docs/api/java/awt/Component.html#setSize(int , int)
Edit:Any component added to the GridLayout will be resized to the same size as the largest component added. If you want a component to remain at its preferred size, then wrap that component in a JPanel and then the panel will be resized:
编辑:添加到 GridLayout 的任何组件都将调整为与添加的最大组件相同的大小。如果您希望组件保持其首选大小,则将该组件包装在 JPanel 中,然后面板将调整大小:
Also use setPreferredSize
instead of setSize
.
也使用setPreferredSize
代替setSize
.