Java的JTextField的不尊重给定的列宽

库洛一簇簇:

我试图做一个表格和数据输入面板都会有一个标签,然后各自对用户输入数据文本框。

所以我发现的GridBagLayout是做到这一点的最好办法,但我真的不知道如何使用它。

在这里输入图像描述

到目前为止,这是结果。我的整个形式是BorderLayout,但我们只打算把重点放在它的北部,在那里用户将输入的数据。

This north part container holds a GridLayout with 4 rows and 2 columns. Inside (0,0) of this GridLayout, I created another panel with a GridBagLayout, with a JLabel and a JTextfield. The idea is for this container to be responsive and fill the whole remaining area that now shows gray, I would like it all to be textfield.

If anyone can help me learn how to do this using GridBagLayout I would much appreciate it. I know what I'm doing might not be optimal, so I'd listen to better suggestions.

Thanks.

import java.awt.*;
import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellRenderer;
import java.awt.Insets;
import java.awt.event.*;

@SuppressWarnings("serial")

public class UserForm extends JFrame {

    public UserForm() {

        // Miscelaneous
        Font font0 = new Font("Tahoma", Font.PLAIN, 12);
        Font font1 = new Font("Tahoma", Font.BOLD, 11);
        Font font2 = new Font("Tahoma", Font.BOLD, 12);

        // Frame layout -> north: data-in form, center: Jtable displayed, south:
        // buttons.
        JPanel mainP = new JPanel(new BorderLayout(5, 25));
        JPanel dataIn = new JPanel(new GridLayout(4, 2, 60, 3));
        JPanel displayT = new JPanel(new BorderLayout(0, 20));
        JPanel buttons = new JPanel(new GridLayout(0, 3, 10, 5));

        // Data-In Form Components
        JLabel idl = new JLabel("Id:");
        JLabel namel = new JLabel("Name:");
        JLabel ln1l = new JLabel("First Lastname:");
        JLabel ln2l = new JLabel("Second Lastname:");
        JLabel agl = new JLabel("Age:");
        JLabel adl = new JLabel("Address:");
        JLabel pnl = new JLabel("Phone Number:");
        JLabel eml = new JLabel("E-Mail:");
        JTextField idtf = new JTextField("");
        JTextField nametf = new JTextField("");
        JTextField ln1tf = new JTextField("");
        JTextField ln2tf = new JTextField("");
        JTextField agtf = new JTextField("");
        JTextField adtf = new JTextField("");
        JTextField pntf = new JTextField("");
        JTextField emtf = new JTextField("");

        // Data-In Form Containers
        JPanel dataId = new JPanel(new GridBagLayout());
        JPanel dataName = new JPanel(new GridBagLayout());
        JPanel dataLN1 = new JPanel(new GridBagLayout());
        JPanel dataLN2 = new JPanel(new GridBagLayout());
        JPanel dataAg = new JPanel(new GridBagLayout());
        JPanel dataAd = new JPanel(new GridBagLayout());
        JPanel dataPN = new JPanel(new GridBagLayout());
        JPanel dataEM = new JPanel(new GridBagLayout());

        // Components into individual containers
        // GridBagLayout Constraints label
        GridBagConstraints c1 = new GridBagConstraints();
        c1.gridx = 0;
        c1.gridy = 0;
        c1.gridwidth = 1; 
        c1.gridheight = 1;
        c1.weightx = 0.5;
        c1.anchor = GridBagConstraints.FIRST_LINE_START;
        c1.insets = new Insets(3,10,0,0);

        // GridBagLayout Constraints tf
        GridBagConstraints c2 = new GridBagConstraints();
        c2.gridx = 1;
        c2.gridy = 0;
        //c2.gridwidth = 4; 
        c2.gridheight = 1;
        c2.weightx = 0.5;
        c2.anchor = GridBagConstraints.WEST;
        c2.insets = new Insets(3,0,0,10);
        c2.fill = GridBagConstraints.HORIZONTAL;

        dataId.add(idl, c1);
        dataId.add(idtf, c2);
        dataName.add(namel, c1);
        dataName.add(nametf, c2);
        dataLN1.add(ln1l, c1);
        dataLN1.add(ln1tf, c2);
        dataLN2.add(ln2l, c1);
        dataLN2.add(ln2tf, c2);
        dataAg.add(agl, c1);
        dataAg.add(agtf, c2);
        dataAd.add(adl, c1);
        dataAd.add(adtf, c2);
        dataPN.add(pnl, c1);
        dataPN.add(pntf, c2);
        dataEM.add(eml, c1);
        dataEM.add(emtf, c2);

        // Miscelaneous
        idl.setFont(font2);
        idtf.setFont(font0);
        namel.setFont(font2);
        nametf.setFont(font0);
        ln1l.setFont(font2);
        ln1tf.setFont(font0);
        ln2l.setFont(font2);
        ln2tf.setFont(font0);
        agl.setFont(font2);
        agtf.setFont(font0);
        adl.setFont(font2);
        adtf.setFont(font0);
        pnl.setFont(font2);
        pntf.setFont(font0);
        eml.setFont(font2);
        emtf.setFont(font0);

        // Set tf editable
        idtf.setEditable(true);
        nametf.setEditable(true);
        ln1tf.setEditable(true);
        ln2tf.setEditable(true);
        agtf.setEditable(true);
        adtf.setEditable(true);
        pntf.setEditable(true);
        emtf.setEditable(true);

        dataIn.add(dataId);
        dataIn.add(dataAg);
        dataIn.add(dataName);
        dataIn.add(dataAd);
        dataIn.add(dataLN1);
        dataIn.add(dataPN);
        dataIn.add(dataLN2);
        dataIn.add(dataEM);

        // JTable Creation
        String[] headline = { "Id", "Name", "First Lastname", "Second Lastname", "Age", "Address", "Phone Number",
                "E-Mail" };
        String[][] data = { { "", "", "", "", "", "", "", "" }, { "", "", "", "", "", "", "", "" } };
        JTable dataShow = new JTable(data, headline);

        // Table Personalization
        dataShow.getTableHeader().setFont(font1);
        new HeaderRenderer(dataShow);

        // Add to container
        JPanel tableP = new JPanel(new BorderLayout(1, 1));
        tableP.add(dataShow.getTableHeader(), BorderLayout.NORTH);
        tableP.add(dataShow, BorderLayout.CENTER);
        JScrollPane sP = new JScrollPane();
        sP.setViewportView(tableP);
        displayT.add(sP, BorderLayout.CENTER);

        // buttons Components and Cointainers
        JButton save = new JButton("Save");
        JButton del = new JButton("Delete");
        JButton edit = new JButton("Edit");
        JLabel empty = new JLabel("");

        // Add to button panel
        buttons.add(save);
        buttons.add(del);
        buttons.add(edit);
        buttons.add(empty);

        // Miscelaneous
        save.setFont(font2);
        del.setFont(font2);
        edit.setFont(font2);

        // Add subpanels to main panel
        mainP.add(dataIn, BorderLayout.NORTH);
        mainP.add(displayT, BorderLayout.CENTER);
        mainP.add(buttons, BorderLayout.SOUTH);

        // set content pane
        setContentPane(mainP);
        setVisible(true);
        setTitle("User Form");
        setSize(900, 500);
        setResizable(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // For future table filling
        /*
         * String ids = idtf.getText(); String names = nametf.getText(); String ln1s =
         * ln1tf.getText(); String ln2s = ln2tf.getText(); String ags = agtf.getText();
         * String ads = adtf.getText(); String pns = pntf.getText(); String ems =
         * emtf.getText();
         */

    }

    public static void main(String[] args) {

        // invoke runnable for thread safety
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new UserForm();
            }
        });

    }

    // LEFT alignment renderer
    private class HeaderRenderer implements TableCellRenderer {

        DefaultTableCellRenderer renderer;

        public HeaderRenderer(JTable table) {
            renderer = (DefaultTableCellRenderer) table.getTableHeader().getDefaultRenderer();
            renderer.setHorizontalAlignment(JLabel.LEFT);
        }

        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus,
                int row, int col) {
            return renderer.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col);
        }

    }

}
Gilbert Le Blanc :

Here's the GUI I created using a grid bag layout.

用户表单

Here are the major changes I made.

  1. I used a JFrame. There's no reason to extend a Swing component unless you're going to override one of the class methods.

  2. I arranged the JFrame methods in the proper order. The JFrame methods must be called in the order that I put in the code.

  3. I grouped all of the JComponent methods together for each JComponent and created the JComponents in the order they appear on the JFrame. For the love of all developers, always create the JComponents in row, column order.

  4. I removed all sizing, except for the prefered viewpoint size of the JTable.

  5. I defined grid bag constraints for each and every JComponent. That way, you can adjust the constraints for each JComponent. Besides, I don't remember defaults.

There are two JPanels in this GUI. The main JPanel holds all the JComponents except for the JButtons. The second JPanel holds the JButtons. This is because there are 3 buttons, and I divided the grid bag layout into 4 columns.

网格包布局采用4列。JTable中占据了所有4列,以及按钮的JPanel。

下面的代码。

package com.ggl.testing;

import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellRenderer;

public class UserForm {

    // top, left, bottom, right
    private static final Insets topInsets = new Insets(10, 10, 10, 10);
    private static final Insets topCenterInsets = new Insets(10, 0, 10, 10);
    private static final Insets middleInsets = new Insets(0, 10, 10, 10);
    private static final Insets middleCenterInsets = new Insets(0, 0, 10, 10);

    public UserForm() {

        JFrame frame = new JFrame("User Form");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // Miscelaneous
        Font plain = new Font("Tahoma", Font.PLAIN, 12);
        Font bold11 = new Font("Tahoma", Font.BOLD, 11);
        Font bold12 = new Font("Tahoma", Font.BOLD, 12);

        JPanel mainPanel = new JPanel();
        mainPanel.setLayout(new GridBagLayout());

        int gridy = 0;

        // Data-In Form Components
        JLabel idl = new JLabel("Id:");
        idl.setFont(bold12);
        addComponent(mainPanel, idl, 0, gridy, 1, 1, topInsets, GridBagConstraints.LINE_START,
                GridBagConstraints.NONE);

        JTextField idtf = new JTextField(40);
        idtf.setFont(plain);
        addComponent(mainPanel, idtf, 1, gridy, 1, 1, topCenterInsets, GridBagConstraints.LINE_START,
                GridBagConstraints.HORIZONTAL);

        JLabel agl = new JLabel("Age:");
        agl.setFont(bold12);
        addComponent(mainPanel, agl, 2, gridy, 1, 1, topCenterInsets, GridBagConstraints.LINE_START,
                GridBagConstraints.NONE);

        JTextField agtf = new JTextField(40);
        agtf.setFont(plain);
        addComponent(mainPanel, agtf, 3, gridy++, 1, 1, topCenterInsets, GridBagConstraints.LINE_START,
                GridBagConstraints.HORIZONTAL);

        JLabel namel = new JLabel("Name:");
        namel.setFont(bold12);
        addComponent(mainPanel, namel, 0, gridy, 1, 1, middleInsets, GridBagConstraints.LINE_START,
                GridBagConstraints.NONE);

        JTextField nametf = new JTextField(40);
        nametf.setFont(plain);
        addComponent(mainPanel, nametf, 1, gridy, 1, 1, middleCenterInsets, GridBagConstraints.LINE_START,
                GridBagConstraints.HORIZONTAL);

        JLabel adl = new JLabel("Address:");
        adl.setFont(bold12);
        addComponent(mainPanel, adl, 2, gridy, 1, 1, middleCenterInsets, GridBagConstraints.LINE_START,
                GridBagConstraints.NONE);

        JTextField adtf = new JTextField(40);
        adtf.setFont(plain);
        addComponent(mainPanel, adtf, 3, gridy++, 1, 1, middleCenterInsets, GridBagConstraints.LINE_START,
                GridBagConstraints.HORIZONTAL);

        JLabel pnl = new JLabel("Phone Number:");
        pnl.setFont(bold12);
        addComponent(mainPanel, pnl, 0, gridy, 1, 1, middleInsets, GridBagConstraints.LINE_START,
                GridBagConstraints.NONE);

        JTextField pntf = new JTextField(40);
        pntf.setFont(plain);
        addComponent(mainPanel, pntf, 1, gridy, 1, 1, middleCenterInsets, GridBagConstraints.LINE_START,
                GridBagConstraints.HORIZONTAL);

        JLabel ln1l = new JLabel("First Lastname:");
        ln1l.setFont(bold12);
        addComponent(mainPanel, ln1l, 2, gridy, 1, 1, middleCenterInsets, GridBagConstraints.LINE_START,
                GridBagConstraints.NONE);

        JTextField ln1tf = new JTextField(40);
        ln1tf.setFont(plain);
        addComponent(mainPanel, ln1tf, 3, gridy++, 1, 1, middleCenterInsets, GridBagConstraints.LINE_START,
                GridBagConstraints.HORIZONTAL);

        JLabel ln2l = new JLabel("Second Lastname:");
        ln2l.setFont(bold12);
        addComponent(mainPanel, ln2l, 0, gridy, 1, 1, middleInsets, GridBagConstraints.LINE_START,
                GridBagConstraints.NONE);

        JTextField ln2tf = new JTextField(40);
        ln2tf.setFont(plain);
        addComponent(mainPanel, ln2tf, 1, gridy, 1, 1, middleCenterInsets, GridBagConstraints.LINE_START,
                GridBagConstraints.HORIZONTAL);

        JLabel eml = new JLabel("E-Mail:");
        eml.setFont(bold12);
        addComponent(mainPanel, eml, 2, gridy, 1, 1, middleCenterInsets, GridBagConstraints.LINE_START,
                GridBagConstraints.NONE);

        JTextField emtf = new JTextField(40);
        emtf.setFont(plain);
        addComponent(mainPanel, emtf, 3, gridy++, 1, 1, middleCenterInsets, GridBagConstraints.LINE_START,
                GridBagConstraints.HORIZONTAL);

        // JTable Creation
        String[] headline = { "Id", "Name", "First Lastname", "Second Lastname", "Age", "Address", "Phone Number",
                "E-Mail" };
        String[][] data = { { "", "", "", "", "", "", "", "" }, { "", "", "", "", "", "", "", "" } };
        JTable dataShow = new JTable(data, headline);
        dataShow.setPreferredScrollableViewportSize(new Dimension(900, 300));
        dataShow.setFillsViewportHeight(true);
        JScrollPane scrollPane = new JScrollPane(dataShow);
        addComponent(mainPanel, scrollPane, 0, gridy++, 4, 1, middleInsets, GridBagConstraints.LINE_START,
                GridBagConstraints.HORIZONTAL);


        // Table Personalization
        dataShow.getTableHeader().setFont(bold11);
        new HeaderRenderer(dataShow);

        // buttons Components 
        JPanel buttonPanel = new JPanel();
        buttonPanel.setLayout(new GridBagLayout());
        JButton save = new JButton("Save");
        save.setFont(bold12);
        addComponent(buttonPanel, save, 0, 0, 1, 1, topInsets, GridBagConstraints.CENTER,
                GridBagConstraints.HORIZONTAL);

        JButton del = new JButton("Delete");
        del.setFont(bold12);
        addComponent(buttonPanel, del, 1, 0, 1, 1, topInsets, GridBagConstraints.CENTER,
                GridBagConstraints.HORIZONTAL);

        JButton edit = new JButton("Edit");
        edit.setFont(bold12);
        addComponent(buttonPanel, edit, 2, 0, 1, 1, topInsets, GridBagConstraints.CENTER,
                GridBagConstraints.HORIZONTAL);

        addComponent(mainPanel, buttonPanel, 0, gridy++, 4, 1, middleInsets, GridBagConstraints.LINE_START,
                GridBagConstraints.HORIZONTAL);

        // set content pane
        frame.add(mainPanel);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);

        // For future table filling
        /*
         * String ids = idtf.getText(); String names = nametf.getText(); String ln1s =
         * ln1tf.getText(); String ln2s = ln2tf.getText(); String ags = agtf.getText();
         * String ads = adtf.getText(); String pns = pntf.getText(); String ems =
         * emtf.getText();
         */

    }

    private void addComponent(Container container, Component component, int gridx, int gridy, int gridwidth,
            int gridheight, Insets insets, int anchor, int fill) {
        GridBagConstraints gbc = new GridBagConstraints(gridx, gridy, gridwidth, gridheight, 1.0, 1.0, anchor, fill,
                insets, 0, 0);
        container.add(component, gbc);
    }

    public static void main(String[] args) {

        // invoke runnable for thread safety
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new UserForm();
            }
        });

    }

    // LEFT alignment renderer
    private class HeaderRenderer implements TableCellRenderer {

        DefaultTableCellRenderer renderer;

        public HeaderRenderer(JTable table) {
            renderer = (DefaultTableCellRenderer) table.getTableHeader().getDefaultRenderer();
            renderer.setHorizontalAlignment(JLabel.LEFT);
        }

        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus,
                int row, int col) {
            return renderer.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col);
        }

    }

}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章