JTextField宽度在GridBagConstraints java中不起作用

时间:2017-10-30 10:07:45

标签: java swing

我想减少用户名和密码旁边的文本字段的宽度,使它们不是100%宽度,但我不知所措。
用户名和密码TextField会添加到以下代码中的GridBagConstraints内:

public class LoginPage extends JPanel {
    private ActionListener action;
    private JLabel scanningJLabel;
    private JLabel loginJLabel;
    private JLabel passwordJLabel;
    private JTextField usernameJTextField;
    private JPasswordField passwordJPasswordField;
    private JButton configureJButton;

    public LoginPage() {
        init();
    }

    private void init() {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch(ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
            ex.printStackTrace();
        }

        JPanel content = new JPanel(new GridBagLayout());
        content.setBorder(new EmptyBorder(20, 20, 20, 20));
        setLayout(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridx = 0;
        gbc.gridy = 0;

        scanningJLabel = new JLabel();
        loginJLabel = new JLabel();
        passwordJLabel = new JLabel();
        usernameJTextField = new JTextField();
        passwordJPasswordField = new JPasswordField();
        configureJButton = new JButton();

        scanningJLabel.setHorizontalAlignment(SwingConstants.CENTER);
        scanningJLabel.setForeground(new Color(0, 0, 255));
        scanningJLabel.setText("Scanning");

        loginJLabel.setFont(loginJLabel.getFont().deriveFont(18.0f));
        loginJLabel.setHorizontalAlignment(SwingConstants.LEFT);
        loginJLabel.setForeground(new Color(0, 0, 255));
        loginJLabel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
        loginJLabel.setText("User Name");

        passwordJLabel.setFont(passwordJLabel.getFont().deriveFont(18.0f));
        passwordJLabel.setHorizontalAlignment(SwingConstants.LEFT);
        passwordJLabel.setForeground(new Color(0, 0, 255));
        passwordJLabel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
        passwordJLabel.setText("Password");

        usernameJTextField.setFont(loginJLabel.getFont().deriveFont(18.0f));
        usernameJTextField.setHorizontalAlignment(SwingConstants.LEFT);
        usernameJTextField.setForeground(new Color(0, 0, 255));
        usernameJTextField.setToolTipText("Enter your username");
        usernameJTextField.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                jTextField1_actionPerformed(e);
            }
        });

        passwordJPasswordField.setFont(passwordJLabel.getFont().deriveFont(18.0f));
        passwordJPasswordField.setHorizontalAlignment(SwingConstants.LEFT);
        passwordJPasswordField.setForeground(new Color(0, 0, 255));
        passwordJPasswordField.setToolTipText("Enter your password");
        passwordJPasswordField.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                jPasswordField1_actionPerformed(e);
            }
        });

        usernameJTextField.setBounds(70, 30, 150, 20);
        passwordJPasswordField.setBounds(70, 65, 150, 20);

        configureJButton.setPreferredSize(new Dimension(140, 40));
        configureJButton.setBackground(new Color(204, 204, 204));
        configureJButton.setForeground(new Color(0, 0, 255));
        configureJButton.setFont(loginJLabel.getFont().deriveFont(16.0f));
        configureJButton.setText("Configure");
        configureJButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                jButton1_actionPerformed(e);
            }
        });

        add(loginJLabel, gbc);
        gbc.gridy++;
        add(passwordJLabel, gbc);

        gbc.gridx++;
        gbc.gridy = 0;
        gbc.gridwidth = 2;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.weightx = 1;
        add(usernameJTextField, gbc);
        gbc.gridy++;
        add(passwordJPasswordField, gbc);

        gbc.gridx = 1;
        gbc.gridy++;
        gbc.gridwidth = 1;
        gbc.weightx = 0;
        gbc.fill = GridBagConstraints.NONE;
        add(configureJButton, gbc);
    }
    protected void jButton1_actionPerformed(ActionEvent e) {
        String username = new String(usernameJTextField.getText());
        String password = new String(passwordJPasswordField.getText());
        if (username.isEmpty()) {
            JOptionPane.showMessageDialog(null, "Username should not be empty", "InfoBox: " + "warning", JOptionPane.INFORMATION_MESSAGE);
            return;
        }

        if (password.isEmpty()) {
            JOptionPane.showMessageDialog(null, "Password should not be empty", "InfoBox: " + "warning", JOptionPane.INFORMATION_MESSAGE);
            return;
        }

        if (username.equals("admin") && password.equals("admin")) {
            JPanel parent = (JPanel) getParent();
            CardLayout cardLayout = (CardLayout) parent.getLayout();
            cardLayout.next(parent);
        } else {
            System.out.println("enter the valid username and password");
            JOptionPane.showMessageDialog(null, "Username and Password are not correct, please try again", "InfoBox: " + "warning", JOptionPane.INFORMATION_MESSAGE);
        }
    }

    protected void jTextField1_actionPerformed(ActionEvent e) {
        System.out.println("user name given");
    }

    protected void jPasswordField1_actionPerformed(ActionEvent e) {
        System.out.println("password given");
    }
}

但它像这样填充整个屏幕宽度:

TextFields filling 100% width.

此屏幕的主页面如下,

public class HomePage {
    private static final String CARD_LOGIN = "Card login";
    private static final String CARD_CONFIGURE_BRANCH = "Card configure branch";
    private static final String CARD_CONFIGURE_SYSTEM = "Card configure system";
    private static final String CARD_CONFIGURE_CUSTOMER = "Card configure customer";
    private static final String CARD_CONFIGURE_EXPINCONTAINER = "Card configure expin";
    private static final String CARD_MAINPAGE = "Card main page";

    private static void createAndShowGUI() {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);

        // This JPanel is the base for CardLayout for other JPanels.
        JPanel contentPane = new JPanel();
        contentPane.setLayout(new CardLayout(20, 20));

        /* Here we be making objects of the Window Series classes
         * so that, each one of them can be added to the JPanel 
         * having CardLayout. 
         */
        LoginPage login = new LoginPage();
        contentPane.add(login, CARD_LOGIN);
        ConfigueBranch configureBranch = new ConfigueBranch();
        contentPane.add(configureBranch, CARD_CONFIGURE_BRANCH);
        ConfigureSystem configureSystem = new ConfigureSystem();
        contentPane.add(configureSystem, CARD_CONFIGURE_SYSTEM);
        ConfigureCustomer configureCustomer = new ConfigureCustomer();
        contentPane.add(configureCustomer, CARD_CONFIGURE_CUSTOMER);
        ConfigureExpincontainer configureExpinContainer = new ConfigureExpincontainer();
        contentPane.add(configureExpinContainer, CARD_CONFIGURE_EXPINCONTAINER);
        MainPage mainPage = new MainPage();
        contentPane.add(mainPage, CARD_MAINPAGE);

        /* We need two JButtons to go to the next Card
         * or come back to the previous Card, as and when
         * desired by the User.
         */
        JPanel buttonPanel = new JPanel();
        ImageIcon icon = new ImageIcon("images/expd_logo.png");

        Image image = icon.getImage(); // transform it
        Image newimg = image.getScaledInstance(230, 100, java.awt.Image.SCALE_SMOOTH); // scale it the smooth way 
        icon = new ImageIcon(newimg); // transform it back
        JLabel label = new JLabel("", icon, JLabel.LEFT);
        label.setFont(new java.awt.Font("Arial", Font.BOLD, 24));
        label.setOpaque(true);
        label.setForeground(Color.BLACK);
        label.setBounds(0, 60, 300, 200);
        buttonPanel.add(label);

        // Adding the contentPane (JPanel) and buttonPanel to JFrame.
        frame.add(contentPane, BorderLayout.CENTER);
        frame.add(buttonPanel, BorderLayout.PAGE_START);
        frame.pack();
        frame.setSize(1000, 700);
        frame.setVisible(true);
    }

    public static void main(String...args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }

2 个答案:

答案 0 :(得分:1)

gbc.fill = GridBagConstraints.HORIZONTAL;控制以填充所有水平区域。

这是一个在GridBagLayout中放置文本框的示例,其中包含固定(以列为单位)的长度

public class MainFrame extends JFrame {

    public MainFrame() throws HeadlessException {
        super("Test Frame");
        createGUI();
    }

    private void createGUI() {
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setLayout(new GridBagLayout());

        JLabel userNameLabel = new JLabel("User Name");
        JLabel passwordLabel = new JLabel("Password");

        JTextField userNameTextField = new JTextField(20);
        JPasswordField passwordField = new JPasswordField(20);

        JButton configureButton = new JButton("Configure");

        GridBagConstraints c = new GridBagConstraints();
        c.insets = new Insets(5, 5, 5, 5);
        c.gridx = 0;
        c.gridy = 0;

        c.weightx = 0.0;
        add(userNameLabel, c);

        c.gridy++;
        add(passwordLabel, c);

        c.weightx = 1.0;
        c.gridx++;
        c.gridy = 0;
        c.anchor = GridBagConstraints.LINE_START;
        add(userNameTextField, c);

        c.gridy++;
        add(passwordField, c);

        c.gridy++;
        add(configureButton, c);

        pack();
        setLocationRelativeTo(null);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new MainFrame().setVisible(true));
    }
}

答案 1 :(得分:-1)

为什么不构建使用指定文本和列

初始化的TextField
JTextField textField = new JTextField("",20);

用于计算首选宽度的列数。如果列设置为零,则首选宽度将是组件实现自然产生的任何宽度。

修改:
您也可以使用setBounds

textField.setBounds(int x, int y, int width,int height);

x是该组件的新x坐标 y是该组件的新y坐标 width是此组件的新宽度
height是此组件的新高度