GridBagLayout对齐textField?

bab*_*eps 2 java swing awt layout-manager gridbaglayout

我想缩短我的文本字段,因此它不会延伸到我的jframe的末尾,所以这就是它现在的样子: 在此输入图像描述

如何控制文本字段的宽度,以便它不像我尝试setPreferedSize()和setSize()那样streatch他们没有工作?

@Override
        public void run() {

            JFrame frame = new JFrame("Test Calculator");
            frame.setVisible(true);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setLocationRelativeTo(null);
            frame.setSize(500, 500);

            JPanel panel = new JPanel(new GridBagLayout());
            frame.getContentPane().add(panel, BorderLayout.NORTH);
            GridBagConstraints c = new GridBagConstraints();

            JLabel testLabel = new JLabel("Enter Score For Test 1: ");  
            c.gridx = 0;
            c.gridy = 0;
            c.anchor = GridBagConstraints.WEST;
            c.fill = GridBagConstraints.BOTH;
            c.insets = new  Insets(40, 15, 15, 0);
            panel.add(testLabel , c);


            JTextField txtField1 = new JTextField("TextField");
            c.gridx = 1;
            c.gridy = 0;
            c.fill = GridBagConstraints.HORIZONTAL;
            c.weightx = .5; 
            panel.add(txtField1 , c);
        }
Run Code Online (Sandbox Code Playgroud)

JB *_*zet 5

你告诉布局文本字段必须水平填充,这就是它的作用.更换

c.fill = GridBagConstraints.HORIZONTAL;
Run Code Online (Sandbox Code Playgroud)

通过

c.fill = GridBagConstraints.NONE;
Run Code Online (Sandbox Code Playgroud)