我正在寻找一种方法来设置JTextField的显示,使其占据包含它的JPanel的整个宽度。

我能够找到的唯一方法是在调用setColumns()getWidth()方法之后,将JPanel方法与在pack()上调用的setVisible()方法结合使用。但是,当我这样做时,JTextField最终比包围它的JPanel大得多。我对为什么发生这种情况的假设是,getWidth()返回像素中JPanel的大小,并且JTextField中的列都大于一个像素。

我什至没有在寻找要动态调整大小的字段,只是要与程序开始时的JPanel一样宽

任何帮助,不胜感激

最佳答案

使用适当的布局管理器...

请记住,决定组件的大小不是组件的责任,而是布局管理器的责任,组件只能提供有关组件的大小的提示...

例如,您可以使用GridBagLayout ...



import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        public TestPane() {

            JTextField field = new JTextField(10);
            setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.weightx = 1;
            gbc.fill = GridBagConstraints.HORIZONTAL;
            add(field, gbc);

        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 200);
        }

    }

}


查看Laying Out Components Within a Container了解更多详细信息

关于java - 设置JTextField宽度以匹配JPanel的宽度,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26395747/

10-11 22:52
查看更多