简体   繁体   English

JTextfield位置不会改变

[英]JTextfield location won't change

I've been trying to set the location of my text field but it seems that it is only being generated the the middle of the JFrame . 我一直在尝试设置文本字段的位置,但似乎它只是在JFrame的中间生成。

I want it in the north left corner, how do I do that? 我想在左上角,我该怎么做? I've add the code of my program. 我添加了我的程序代码。

     private static void createAndShowGUI() {
    //Create and set up the window.
    JFrame frame = new JFrame("Atarim");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //Create and set up the content pane.
    JComponent newContentPane = new Atarim(frame);
    newContentPane.setOpaque(true);
    frame.setContentPane(newContentPane);
    frame.setLocationRelativeTo(null);
    frame.setSize(352, 950);
    JTextField textfield = new JTextField("search...");
    textfield.setLocation(0, 0);
    textfield.setSize(150,20);
    textfield.setVisible(true);
    newContentPane.add(textfield);
    frame.setVisible(true);
}

The first thing I would do is try a get over this need for absolute control, it will make your life easier in the long run. 我要做的第一件事就是尝试克服绝对控制的需要,从长远来看,它会让你的生活更轻松。

Swing employees a system know as layout managers to facilitate the positioning of UI elements on the screen. Swing员工将系统称为布局管理器,以便于UI元素在屏幕上的定位。 The layout manager API is fundamental to how Swing works. 布局管理器API是Swing工作原理的基础。 It makes developing UIs for different systems easier and quicker as you don't need to continuously calculate the difference in font metrics and screen resolutions for all the various systems that your UI may run on (having developed for both MacOS, Windows 7 and Windows XP simultaneously, I can ensure you this is a God send) 它使得为不同系统开发UI变得更加容易和快捷,因为您不需要连续计算UI可能运行的所有各种系统的字体度量和屏幕分辨率的差异(针对MacOS,Windows 7和Windows XP开发)同时,我可以确保你这是一个神派)

You could try something like... 你可以试试像......

newContentPane.setLayout(new GridBagLayout());
GridBagConstraintss gbc = new GridBagConstraintss();
gbc.weightx = 1;
gbc.weighty = 1;
gbc.anchor = GridBagConstraints.NORTHWEST;
newContentPane.add(textfield);

Take a closer look at Using Layout !anagers and A visual guide to layout managers for more details 仔细查看使用布局!anagers布局管理器的可视指南,了解更多详细信息

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

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