当前位置: 首页 > 知识库问答 >
问题:

JPanel&组件自动改变位置

邴修远
2023-03-14

嗨,我正在开发swing应用程序,但我面临一个问题。

当我第一次运行applicationJPanel时,它位于我决定设置组件的适当位置。但问题发生在

我最小化&再次最大化框架窗口jpanel自动更改它的位置。

jpanel_addPurchase = new JPanel();
jpanel_addPurchase.setLayout(null);
jpanel_addPurchase.setBounds(400, 0, 500, 500);
jpanel_addPurchase.setBackground(Color.white);
JLabel lbl_title = new JLabel("Purchase Form");
lbl_title.setBounds(90, 20, 100, 100);
jpanel_addPurchase.add(lbl_title);
setContentPane(getJPanel());

我哪里出错了?

共有1个答案

周辉
2023-03-14

我认为原始的(非破损的)布局看起来很奇怪,会使最终用户很难跟踪行和标签/字段。我建议使用grouplayout右对齐标签,左对齐包含值的字段。像这样:

import java.awt.*;
import java.util.HashMap;
import java.util.Map;
import javax.swing.*;

class TwoColumnLayoutWithHeader {

    /**
     * Provides a JPanel with two columns (labels & fields) laid out using
     * GroupLayout. The arrays must be of equal size.
     *
     * Typical fields would be single line textual/input components such as
     * JTextField, JPasswordField, JFormattedTextField, JSpinner, JComboBox,
     * JCheckBox.. & the multi-line components wrapped in a JScrollPane -
     * JTextArea or (at a stretch) JList or JTable.
     *
     * @param labels The first column contains labels.
     * @param fields The last column contains fields.
     * @param addMnemonics Add mnemonic by next available letter in label text.
     * @return JComponent A JPanel with two columns of the components provided.
     */
    public static JComponent getTwoColumnLayout(
            JLabel[] labels,
            JComponent[] fields,
            boolean addMnemonics) {
        if (labels.length != fields.length) {
            String s = labels.length + " labels supplied for "
                    + fields.length + " fields!";
            throw new IllegalArgumentException(s);
        }
        JComponent panel = new JPanel();
        GroupLayout layout = new GroupLayout(panel);
        panel.setLayout(layout);
        // Turn on automatically adding gaps between components
        layout.setAutoCreateGaps(true);
        // Create a sequential group for the horizontal axis.
        GroupLayout.SequentialGroup hGroup = layout.createSequentialGroup();
        GroupLayout.Group yLabelGroup = layout.createParallelGroup(GroupLayout.Alignment.TRAILING);
        hGroup.addGroup(yLabelGroup);
        GroupLayout.Group yFieldGroup = layout.createParallelGroup();
        hGroup.addGroup(yFieldGroup);
        layout.setHorizontalGroup(hGroup);
        // Create a sequential group for the vertical axis.
        GroupLayout.SequentialGroup vGroup = layout.createSequentialGroup();
        layout.setVerticalGroup(vGroup);

        int p = GroupLayout.PREFERRED_SIZE;
        // add the components to the groups
        for (JLabel label : labels) {
            yLabelGroup.addComponent(label);
        }
        for (Component field : fields) {
            yFieldGroup.addComponent(field, p, p, p);
        }
        for (int ii = 0; ii < labels.length; ii++) {
            vGroup.addGroup(layout.createParallelGroup().
                    addComponent(labels[ii]).
                    addComponent(fields[ii], p, p, p));
        }

        if (addMnemonics) {
            addMnemonics(labels, fields);
        }

        return panel;
    }

    private final static void addMnemonics(
            JLabel[] labels,
            JComponent[] fields) {
        Map<Character, Object> m = new HashMap<Character, Object>();
        for (int ii = 0; ii < labels.length; ii++) {
            labels[ii].setLabelFor(fields[ii]);
            String lwr = labels[ii].getText().toLowerCase();
            for (int jj = 0; jj < lwr.length(); jj++) {
                char ch = lwr.charAt(jj);
                if (m.get(ch) == null && Character.isLetterOrDigit(ch)) {
                    m.put(ch, ch);
                    labels[ii].setDisplayedMnemonic(ch);
                    break;
                }
            }
        }
    }

    /**
     * Provides a JPanel with two columns (labels & fields) laid out using
     * GroupLayout. The arrays must be of equal size.
     *
     * @param labelStrings Strings that will be used for labels.
     * @param fields The corresponding fields.
     * @return JComponent A JPanel with two columns of the components provided.
     */
    public static JComponent getTwoColumnLayout(
            String[] labelStrings,
            JComponent[] fields) {
        JLabel[] labels = new JLabel[labelStrings.length];
        for (int ii = 0; ii < labels.length; ii++) {
            labels[ii] = new JLabel(labelStrings[ii]);
        }
        return getTwoColumnLayout(labels, fields);
    }

    /**
     * Provides a JPanel with two columns (labels & fields) laid out using
     * GroupLayout. The arrays must be of equal size.
     *
     * @param labels The first column contains labels.
     * @param fields The last column contains fields.
     * @return JComponent A JPanel with two columns of the components provided.
     */
    public static JComponent getTwoColumnLayout(
            JLabel[] labels,
            JComponent[] fields) {
        return getTwoColumnLayout(labels, fields, true);
    }

    public static String getProperty(String name) {
        return name + ": \t"
                + System.getProperty(name)
                + System.getProperty("line.separator");
    }

    public static void main(String[] args) {
        Runnable r = new Runnable() {

            @Override
            public void run() {
                JComponent[] components = {
                    new JTextField(15),
                    new JTextField(10),
                    new JTextField(8),
                    new JSpinner(new SpinnerNumberModel(1,0,10,1)),
                    new JSpinner(new SpinnerNumberModel(9.95,0d,100d,.01)),
                    new JSpinner(new SpinnerNumberModel(9.95,0d,1000d,.01)),
                    new JSpinner(new SpinnerNumberModel(9.95,0d,100d,.01)),
                    new JSpinner(new SpinnerNumberModel(9.95,0d,1000d,.01)),
                    new JSpinner(new SpinnerNumberModel(9.95,0d,100d,.01)),
                    new JSpinner(new SpinnerNumberModel(9.95,0d,1000d,.01))
                };

                String[] labels = {
                    "Product Name:",
                    "Product Unit Name:",
                    "Purchase Date:",
                    "Quantity:",
                    "Price Per Unit:",
                    "Total Price:",
                    "Discount:",
                    "Total:",
                    "VAT:",
                    "Grand Total:"
                };

                JComponent labelsAndFields = getTwoColumnLayout(labels,components);
                JComponent orderForm = new JPanel(new BorderLayout(5,5));
                orderForm.add(new JLabel("Purchase Form", SwingConstants.CENTER),
                    BorderLayout.PAGE_START);
                orderForm.add(labelsAndFields, BorderLayout.CENTER);

                JOptionPane.showMessageDialog(null, orderForm);
            }
        };
        // Swing GUIs should be created and updated on the EDT
        // http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html
        SwingUtilities.invokeLater(r);
    }
}
 类似资料:
  • 因此,我创建了2个 但后来我意识到2不是一个好主意,所以我添加了,然后尝试以的形式添加不同的选项卡。但是我不能像在中那样定位组件,它看起来是这样的。 但我希望它是这样的 我怎么能这么做?

  • 但是,我的程序稍后尝试将一个新的JPanel添加到类的扩展JPanel中,方法是: 这个新的JPanel以正确的BorderLayout格式显示内容,但是JPanel本身将保持在扩展JPanel的顶部中心,我知道这是因为默认布局设置为FlowLayout,但是将其设置为BorderLayout只会导致面板占用整个屏幕。将布局设置为null将完全破坏框架,除了框架的最小化和关闭按钮之外,什么也没有出

  • 问题内容: 如何在jpanel中动态添加组件?当我单击按钮时,我应该有添加按钮,组件应该添加到JPanel。 我的问题是,当我单击添加按钮时,将文本字段和按钮添加到jpanel时,用户可以根据需要将它们添加到jpanel中的任意次数单击添加按钮。我已将scrollerpane添加到我的jpanel,并且jpanel布局管理器设置为null。 问题答案: 像往常一样,除了必须调用: 完成后,因为容器

  • 我目前创建了一个动态的身体,并且用Vector2()以恒定的速度移动。我想要的是当身体离开屏幕边缘时,立即从当前点回到原点。我该怎么做?

  • 是否可以更改Apache使用的的位置?当我做时,结果是: 路径= 已加载配置文件 但是的结果是 配置文件(php.ini)路径: /etc 我可以将从复制到,但是可以更改php.ini文件夹吗? 我使用自制软件安装PHP,我使用的是OS X Snow Leopard。

  • 我试图设置一个系统,当我按下按钮时,JLabel文本会改变,但我似乎无法使其工作。我已经测试了操作监听器通过执行system.out.println(test);来工作。它工作正常,但是当试图更改JComponent文本时,它不工作。我已经搜索了答案,但没有找到任何有用的答案。 主要类别: JFrame和JPanel类: ActionListener类: