Java 如何设置swing组件的大小

Java 如何设置swing组件的大小,java,swing,customization,jtextfield,Java,Swing,Customization,Jtextfield,我想自定义JTextField对象的高度和宽度。我尝试过使用setSize方法,将宽度和高度作为尺寸和int传递。但它们似乎都不起作用。我是否遗漏了一些东西,比如面板上的一些强制方法调用,或者一些使尺寸定制有效的东西?请帮忙。提前谢谢 编辑:下面是一些代码: public class WestPanel extends JPanel{ private JLabel dateL; private JTextField date; public WestPanel(){ setBackground(

我想自定义JTextField对象的高度和宽度。我尝试过使用setSize方法,将宽度和高度作为尺寸和int传递。但它们似乎都不起作用。我是否遗漏了一些东西,比如面板上的一些强制方法调用,或者一些使尺寸定制有效的东西?请帮忙。提前谢谢

编辑:下面是一些代码:

public class WestPanel extends JPanel{
private JLabel dateL;
private JTextField date;
public WestPanel(){
setBackground(Color.white);
setLayout(new GridLayout(1,2,0,0));
dateL=new JLabel("Date: ");
date=new JTextField("dd/mm/yyyy");
date.setSize(60,10);
add(dateL);
add(date);
//....remaining code....//

Swing中组件的大小取决于您使用的布局管理器的类型。如果您想完全控制UI,可以使用Freeflow布局

请在此处阅读完整故事:

Swing中组件的大小取决于您使用的布局管理器的类型。如果您想完全控制UI,可以使用Freeflow布局

请在此处阅读完整故事:
只有在将布局管理器设置为空时,
setSize()
方法才起作用。

只有在将布局管理器设置为空时,
setSize()
方法才起作用。

让布局管理器处理回转组件的尺寸,但如果您必须这样做,将
setPreferredSize
与尊重该属性的布局管理器结合使用。

让布局管理器负责Swing组件的尺寸,但如果您必须这样做,请将
setPreferredSize
与尊重该属性的布局管理器结合使用。

JTextField无法设置大小,实际上,您应该使用JTextArea。

如注释中所建议,在文本字段构造函数中使用大小提示,并使用适当的布局管理器

import java.awt.*;
import javax.swing.*;

public class WestPanel extends JPanel {

    private JLabel dateL;
    private JTextField date;

    public WestPanel(){
        setBackground(Color.white);
        setLayout(new FlowLayout());
        dateL=new JLabel("Date: ");
        date=new JTextField("dd/mm/yyyy",6);
        add(dateL);
        add(date);
    }

    public static void main(String[] args) {
        Runnable r = new Runnable() {
            @Override
            public void run() {
                JPanel gui = new JPanel(new BorderLayout());
                gui.add(new WestPanel(), BorderLayout.LINE_START);
                gui.setBackground(Color.ORANGE);
                JOptionPane.showMessageDialog(null, gui);
            }
        };
        SwingUtilities.invokeLater(r);
    }
}


按照注释中的建议,在文本字段构造函数中使用大小提示,并使用适当的布局管理器

import java.awt.*;
import javax.swing.*;

public class WestPanel extends JPanel {

    private JLabel dateL;
    private JTextField date;

    public WestPanel(){
        setBackground(Color.white);
        setLayout(new FlowLayout());
        dateL=new JLabel("Date: ");
        date=new JTextField("dd/mm/yyyy",6);
        add(dateL);
        add(date);
    }

    public static void main(String[] args) {
        Runnable r = new Runnable() {
            @Override
            public void run() {
                JPanel gui = new JPanel(new BorderLayout());
                gui.add(new WestPanel(), BorderLayout.LINE_START);
                gui.setBackground(Color.ORANGE);
                JOptionPane.showMessageDialog(null, gui);
            }
        };
        SwingUtilities.invokeLater(r);
    }
}


我不确定这是否回答了原始海报上的问题,但希望它能对其他Swing开发人员有所帮助

大多数人希望标签和组件对齐,就像我创建的下面的对话框一样

我使用Swing布局管理器GridBagLayout创建这种类型的布局。下面是创建此对话框的代码,而不是大量的解释

package com.ggl.business.planner.view;

import java.awt.Component;
import java.awt.Container;
import java.awt.Dialog;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.SpinnerNumberModel;
import javax.swing.SwingConstants;

import com.ggl.business.planner.model.BusinessPlannerModel;
import com.ggl.business.planner.view.extended.EscapeDialog;
import com.ggl.business.planner.view.extended.JFontChooser;

public class OptionsDialog {

    protected static final Insets entryInsets = new Insets(0, 10, 4, 10);
    protected static final Insets spaceInsets = new Insets(10, 10, 4, 10);
    protected static final Insets noInsets    = new Insets(0, 0, 0, 0);
    protected static final Insets iconInsets  = new Insets(0, 4, 0, 0);

    protected BusinessPlannerFrame frame;

    protected BusinessPlannerModel model;

    protected EscapeDialog dialog;

    protected JButton activityTextFontButton;
    protected JButton connectorTextFontButton;

    protected JSpinner borderSizeSpinner;

    protected SpinnerNumberModel spinnerNumberModel;

    protected boolean okPressed;

    public OptionsDialog(BusinessPlannerModel model, BusinessPlannerFrame frame) {
        this.model = model;
        this.frame = frame;
        createPartControl();
    }

    protected void createPartControl() {
        dialog = new EscapeDialog();
        dialog.setTitle("Business Planner Options");
        dialog.setLayout(new GridBagLayout());

        int gridy = 0;
        gridy = createBorderFields(gridy);
        gridy = createFontFields(gridy);
        gridy = createButtonFields(gridy);

        dialog.pack();
        dialog.setBounds(dialogBounds());
        dialog.setModalityType(Dialog.ModalityType.APPLICATION_MODAL);
        dialog.setVisible(true);
    }

    protected int createBorderFields(int gridy) {
        JLabel borderSizeLabel = new JLabel("Border size:");
        borderSizeLabel.setHorizontalAlignment(SwingConstants.LEFT);
        addComponent(dialog, borderSizeLabel, 0, gridy, 1, 1, spaceInsets,
                GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL);

        spinnerNumberModel = new SpinnerNumberModel(model.getActivityBorder(), 1, 5, 1);
        borderSizeSpinner = new JSpinner(spinnerNumberModel);
        addComponent(dialog, borderSizeSpinner, 1, gridy++, 4, 1, spaceInsets,
                GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL);

        return gridy;
    }

    protected int createFontFields(int gridy) {
        JLabel boxtextFontLabel = new JLabel("Activity text font:");
        boxtextFontLabel.setHorizontalAlignment(SwingConstants.LEFT);
        addComponent(dialog, boxtextFontLabel, 0, gridy, 1, 1, spaceInsets,
                GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL);

        Font font = model.getActivityFont();
        activityTextFontButton = new JButton(getFontText(font));
        activityTextFontButton.setFont(font);
        activityTextFontButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent event) {
                JFontChooser fontChooser = new JFontChooser();
                fontChooser.setSelectedFont(model.getActivityFont());
                int result = fontChooser.showDialog(dialog);
                if (result == JFontChooser.OK_OPTION) {
                    Font font = fontChooser.getSelectedFont();
                    String text = getFontText(font);
                    model.setActivityFont(font);
                    activityTextFontButton.setText(text);
                    activityTextFontButton.setFont(font);
                    JButton dummy = new JButton(text);
                    setButtonSizes(activityTextFontButton, 
                            connectorTextFontButton, dummy);
                    dialog.validate();
                    dialog.pack();
                }
            }
        });
        addComponent(dialog, activityTextFontButton, 1, gridy++, 4, 1, spaceInsets,
                GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL);

        JLabel connectortextFontLabel = new JLabel("Connector text font:");
        connectortextFontLabel.setHorizontalAlignment(SwingConstants.LEFT);
        addComponent(dialog, connectortextFontLabel, 0, gridy, 1, 1, spaceInsets,
                GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL);

        font = model.getConnectorFont();
        connectorTextFontButton = new JButton(getFontText(font));
        connectorTextFontButton.setFont(font);
        connectorTextFontButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent event) {
                JFontChooser fontChooser = new JFontChooser();
                fontChooser.setSelectedFont(model.getConnectorFont());
                int result = fontChooser.showDialog(dialog);
                if (result == JFontChooser.OK_OPTION) {
                    Font font = fontChooser.getSelectedFont();
                    String text = getFontText(font);
                    model.setConnectorFont(font);
                    connectorTextFontButton.setText(text);
                    connectorTextFontButton.setFont(font);
                    JButton dummy = new JButton(text);
                    setButtonSizes(activityTextFontButton, 
                            connectorTextFontButton, dummy);
                    dialog.validate();
                    dialog.pack();
                }
            }
        });
        addComponent(dialog, connectorTextFontButton, 1, gridy++, 4, 1, spaceInsets,
                GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL);

        setButtonSizes(activityTextFontButton, connectorTextFontButton);

        return gridy;
    }

    protected String getFontText(Font font) {
        StringBuilder builder = new StringBuilder();

        builder.append(font.getName());
        builder.append(", ");
        builder.append(font.getSize());
        builder.append(" points, ");

        if (font.isPlain()) {
            builder.append("plain");
        } else if (font.isBold()) {
            builder.append("bold ");
        } else if (font.isItalic()) {
            builder.append("italic");
        } 

        return builder.toString();
    }

    protected int createButtonFields(int gridy) {
        JPanel buttondrawingPanel = new JPanel();
        buttondrawingPanel.setLayout(new FlowLayout());

        JButton okButton = new JButton("OK");
        okButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent event) {
                //TODO Add edits to make sure fields are filled correctly
                setModel();
                okPressed = true;
                dialog.setVisible(false);
            }       
        });
        dialog.setOkButton(okButton);
        buttondrawingPanel.add(okButton);

        JButton cancelButton = new JButton("Cancel");
        cancelButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent event) {
                okPressed = false;
                dialog.setVisible(false);
            }
        });
        buttondrawingPanel.add(cancelButton);

        setButtonSizes(okButton, cancelButton);

        addComponent(dialog, buttondrawingPanel, 0, gridy++, 5, 1, spaceInsets,
                GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL);

        return gridy;
    }

    protected 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.0D, 1.0D, anchor, fill, insets, 0, 0);
        container.add(component, gbc);
    }

    protected void setButtonSizes(JButton ... buttons) {
        Dimension preferredSize = new Dimension();
        for (JButton button : buttons) {
            Dimension d = button.getPreferredSize();
            preferredSize = setLarger(preferredSize, d);
        }
        for (JButton button : buttons) {
            button.setPreferredSize(preferredSize);
        }
    }

    protected Dimension setLarger(Dimension a, Dimension b) {
        Dimension d = new Dimension();
        d.height = Math.max(a.height, b.height);
        d.width = Math.max(a.width, b.width);
        return d;
    }

    protected void setModel() {
        model.setActivityBorder(spinnerNumberModel.getNumber().intValue()); 
    }

    protected Rectangle dialogBounds() {
        int margin = 200;
        Rectangle bounds = dialog.getBounds();
        Rectangle f = frame.getFrame().getBounds();

        bounds.x = f.x + margin;
        bounds.y = f.y + margin;

        return bounds;
    }

    public boolean isOkPressed() {
        return okPressed;
    }

}
我扩展的EscapeDialog类只允许我使用Esc键关闭对话框,就像我左键单击了Cancel按钮一样

有两件事我要记下来。第一种是addComponent方法,它简化了向GridBagLayout添加组件的过程


第二种方法是setButtonSizes方法,它使所有按钮大小一致。即使它们是JButton组件,而不是JTextField组件,如果希望使JTextField组件具有相同的大小,也可以执行类似的操作

我不确定这是否回答了原始海报的问题,但希望它能对其他Swing开发人员有所帮助

大多数人希望标签和组件对齐,就像我创建的下面的对话框一样

我使用Swing布局管理器GridBagLayout创建这种类型的布局。下面是创建此对话框的代码,而不是大量的解释

package com.ggl.business.planner.view;

import java.awt.Component;
import java.awt.Container;
import java.awt.Dialog;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.SpinnerNumberModel;
import javax.swing.SwingConstants;

import com.ggl.business.planner.model.BusinessPlannerModel;
import com.ggl.business.planner.view.extended.EscapeDialog;
import com.ggl.business.planner.view.extended.JFontChooser;

public class OptionsDialog {

    protected static final Insets entryInsets = new Insets(0, 10, 4, 10);
    protected static final Insets spaceInsets = new Insets(10, 10, 4, 10);
    protected static final Insets noInsets    = new Insets(0, 0, 0, 0);
    protected static final Insets iconInsets  = new Insets(0, 4, 0, 0);

    protected BusinessPlannerFrame frame;

    protected BusinessPlannerModel model;

    protected EscapeDialog dialog;

    protected JButton activityTextFontButton;
    protected JButton connectorTextFontButton;

    protected JSpinner borderSizeSpinner;

    protected SpinnerNumberModel spinnerNumberModel;

    protected boolean okPressed;

    public OptionsDialog(BusinessPlannerModel model, BusinessPlannerFrame frame) {
        this.model = model;
        this.frame = frame;
        createPartControl();
    }

    protected void createPartControl() {
        dialog = new EscapeDialog();
        dialog.setTitle("Business Planner Options");
        dialog.setLayout(new GridBagLayout());

        int gridy = 0;
        gridy = createBorderFields(gridy);
        gridy = createFontFields(gridy);
        gridy = createButtonFields(gridy);

        dialog.pack();
        dialog.setBounds(dialogBounds());
        dialog.setModalityType(Dialog.ModalityType.APPLICATION_MODAL);
        dialog.setVisible(true);
    }

    protected int createBorderFields(int gridy) {
        JLabel borderSizeLabel = new JLabel("Border size:");
        borderSizeLabel.setHorizontalAlignment(SwingConstants.LEFT);
        addComponent(dialog, borderSizeLabel, 0, gridy, 1, 1, spaceInsets,
                GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL);

        spinnerNumberModel = new SpinnerNumberModel(model.getActivityBorder(), 1, 5, 1);
        borderSizeSpinner = new JSpinner(spinnerNumberModel);
        addComponent(dialog, borderSizeSpinner, 1, gridy++, 4, 1, spaceInsets,
                GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL);

        return gridy;
    }

    protected int createFontFields(int gridy) {
        JLabel boxtextFontLabel = new JLabel("Activity text font:");
        boxtextFontLabel.setHorizontalAlignment(SwingConstants.LEFT);
        addComponent(dialog, boxtextFontLabel, 0, gridy, 1, 1, spaceInsets,
                GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL);

        Font font = model.getActivityFont();
        activityTextFontButton = new JButton(getFontText(font));
        activityTextFontButton.setFont(font);
        activityTextFontButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent event) {
                JFontChooser fontChooser = new JFontChooser();
                fontChooser.setSelectedFont(model.getActivityFont());
                int result = fontChooser.showDialog(dialog);
                if (result == JFontChooser.OK_OPTION) {
                    Font font = fontChooser.getSelectedFont();
                    String text = getFontText(font);
                    model.setActivityFont(font);
                    activityTextFontButton.setText(text);
                    activityTextFontButton.setFont(font);
                    JButton dummy = new JButton(text);
                    setButtonSizes(activityTextFontButton, 
                            connectorTextFontButton, dummy);
                    dialog.validate();
                    dialog.pack();
                }
            }
        });
        addComponent(dialog, activityTextFontButton, 1, gridy++, 4, 1, spaceInsets,
                GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL);

        JLabel connectortextFontLabel = new JLabel("Connector text font:");
        connectortextFontLabel.setHorizontalAlignment(SwingConstants.LEFT);
        addComponent(dialog, connectortextFontLabel, 0, gridy, 1, 1, spaceInsets,
                GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL);

        font = model.getConnectorFont();
        connectorTextFontButton = new JButton(getFontText(font));
        connectorTextFontButton.setFont(font);
        connectorTextFontButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent event) {
                JFontChooser fontChooser = new JFontChooser();
                fontChooser.setSelectedFont(model.getConnectorFont());
                int result = fontChooser.showDialog(dialog);
                if (result == JFontChooser.OK_OPTION) {
                    Font font = fontChooser.getSelectedFont();
                    String text = getFontText(font);
                    model.setConnectorFont(font);
                    connectorTextFontButton.setText(text);
                    connectorTextFontButton.setFont(font);
                    JButton dummy = new JButton(text);
                    setButtonSizes(activityTextFontButton, 
                            connectorTextFontButton, dummy);
                    dialog.validate();
                    dialog.pack();
                }
            }
        });
        addComponent(dialog, connectorTextFontButton, 1, gridy++, 4, 1, spaceInsets,
                GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL);

        setButtonSizes(activityTextFontButton, connectorTextFontButton);

        return gridy;
    }

    protected String getFontText(Font font) {
        StringBuilder builder = new StringBuilder();

        builder.append(font.getName());
        builder.append(", ");
        builder.append(font.getSize());
        builder.append(" points, ");

        if (font.isPlain()) {
            builder.append("plain");
        } else if (font.isBold()) {
            builder.append("bold ");
        } else if (font.isItalic()) {
            builder.append("italic");
        } 

        return builder.toString();
    }

    protected int createButtonFields(int gridy) {
        JPanel buttondrawingPanel = new JPanel();
        buttondrawingPanel.setLayout(new FlowLayout());

        JButton okButton = new JButton("OK");
        okButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent event) {
                //TODO Add edits to make sure fields are filled correctly
                setModel();
                okPressed = true;
                dialog.setVisible(false);
            }       
        });
        dialog.setOkButton(okButton);
        buttondrawingPanel.add(okButton);

        JButton cancelButton = new JButton("Cancel");
        cancelButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent event) {
                okPressed = false;
                dialog.setVisible(false);
            }
        });
        buttondrawingPanel.add(cancelButton);

        setButtonSizes(okButton, cancelButton);

        addComponent(dialog, buttondrawingPanel, 0, gridy++, 5, 1, spaceInsets,
                GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL);

        return gridy;
    }

    protected 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.0D, 1.0D, anchor, fill, insets, 0, 0);
        container.add(component, gbc);
    }

    protected void setButtonSizes(JButton ... buttons) {
        Dimension preferredSize = new Dimension();
        for (JButton button : buttons) {
            Dimension d = button.getPreferredSize();
            preferredSize = setLarger(preferredSize, d);
        }
        for (JButton button : buttons) {
            button.setPreferredSize(preferredSize);
        }
    }

    protected Dimension setLarger(Dimension a, Dimension b) {
        Dimension d = new Dimension();
        d.height = Math.max(a.height, b.height);
        d.width = Math.max(a.width, b.width);
        return d;
    }

    protected void setModel() {
        model.setActivityBorder(spinnerNumberModel.getNumber().intValue()); 
    }

    protected Rectangle dialogBounds() {
        int margin = 200;
        Rectangle bounds = dialog.getBounds();
        Rectangle f = frame.getFrame().getBounds();

        bounds.x = f.x + margin;
        bounds.y = f.y + margin;

        return bounds;
    }

    public boolean isOkPressed() {
        return okPressed;
    }

}
我扩展的EscapeDialog类只允许我使用Esc键关闭对话框,就像我左键单击了Cancel按钮一样

有两件事我要记下来。第一种是addComponent方法,它简化了向GridBagLayout添加组件的过程


第二种方法是setButtonSizes方法,它使所有按钮大小一致。即使它们是JButton组件,而不是JTextField组件,如果希望使JTextField组件具有相同的大小,也可以执行类似的操作

更好地向我们展示一些代码,我们可能会帮助您。要更快地获得更好的帮助,请发布一条。更好地向我们展示一些代码,我们可能会帮助您。要更快地获得更好的帮助,请发布一条。您可以使用setPreferredSize和一个布局管理器(如GridBagLayout)设置JTextField组件的大小,该布局管理器考虑组件大小。您可以使用适当的JTextField构造函数设置JTextField的宽度。但是,您没有错,不能将JTextField的高度更改为多行文本。对于多行,您将使用JTextArea组件。您可以使用setPreferredSize和布局管理器(如GridBagLayout)设置JTextField组件的大小,该布局管理器考虑组件大小。您可以使用适当的JTextField构造函数设置JTextField的宽度。但是,您没有错,不能将JTextField的高度更改为多行文本。对于多行,您将使用JTextArea组件。+1。我还想补充一点:1)您可以设置JTextField的列数(这在某种程度上相当于设置preferredSize);2)GridLayout并不适合这种情况(我实际上发现该布局很少有用)。如果配置得当,GridBagLayout可能会为您提供最佳结果。还有其他可以帮助您的布局管理器(BorderLayout、FlowLayout、MigLayout等)+1。我还想补充一点:1)您可以设置JTextField的列数(这在某种程度上相当于设置preferredSize);2)GridLayout并不适合这种情况(我实际上发现该布局很少有用)。如果配置得当,GridBagLayout可能会为您提供最佳结果。还有其他可用的布局管理器可以帮助您(BorderLayout、FlowLayout、MigLayout,…)您如何找到
6
作为
date
JTextField?的列数?Stephan Drugs。您如何找到
6
作为
date
JTextField?Stephan Drugs。