Java 小GUI问题我无法解决。JTextFields

Java 小GUI问题我无法解决。JTextFields,java,user-interface,jlabel,jtextfield,gridbaglayout,Java,User Interface,Jlabel,Jtextfield,Gridbaglayout,这个小错误我做不到。现在我的程序GUI如下所示: 现在在“标记”列下有一个文本字段,用户可以输入他们的数据。如果我想在“权重”列的正下方插入一个文本字段,我还希望权重部分也有相同的内容 但是,当我尝试输入一个文本字段时,当窗口很小时,两个文本字段都会像这样旋转: 当窗口被放大时: 如何设置标记和权重下的文本字段? 代码: 公共类Gradeanalysis实现ActionListener{ 已执行的公共无效操作(操作事件e){ GridBagConstraints gbc=新的GridBag

这个小错误我做不到。现在我的程序GUI如下所示:

现在在“标记”列下有一个文本字段,用户可以输入他们的数据。如果我想在“权重”列的正下方插入一个文本字段,我还希望权重部分也有相同的内容

但是,当我尝试输入一个文本字段时,当窗口很小时,两个文本字段都会像这样旋转:

当窗口被放大时:

如何设置标记和权重下的文本字段?

代码:

公共类Gradeanalysis实现ActionListener{
已执行的公共无效操作(操作事件e){
GridBagConstraints gbc=新的GridBagConstraints();
//添加JPanels.Panel以获取说明
JPanel面板=新的JPanel();
panel.setLayout(新的GridBagLayout());
//JLabel以获取说明。
JLabel标签=新的JLabel标签(“说明:键入您收到的成绩,以及它们在确定总体平均值时的权重。
按“计算”后,结果将显示您迄今为止的平均值。
您输入的每个成绩必须是非负数,输入的每个百分比/权重必须是正数:”; gbc.fill=GridBagConstraints.HORIZONTAL; gbc.gridwidth=2; gbc.gridy=0; 面板。添加(标签,gbc); //JLabel1用于分配/等级/重量(百分比) JLabel label1=新的JLabel(“Assingment\t\t\t\t Mark\t\t\t\t\tWeight”); gbc.fill=GridBagConstraints.HORIZONTAL; gbc.gridx=0; gbc.gridy=1; gbc.anchor=gridbag.NORTH; 面板。添加(标签1,gbc); //JLabel编号用于侧面的辅助设备编号列表。 JLabel编号=新JLabel(“1”); gbc.gridx=0; gbc.gridy=2; gbc.anchor=gridbag.NORTH; gbc.weighty=1; 面板。添加(编号,gbc); //标记的JTextfield JTextField标记=新的JTextField(2); gbc.fill=GridBagConstraints.NONE; gbc.gridy=2; 面板。添加(标记,gbc); //用于权重的JTextfield JTextField权重=新的JTextField(2); gbc.gridx=2; 面板。添加(重量,gbc); //新帧集 JFrame frame=新JFrame(“坡度计算器--”); frame.setVisible(true); 框架。设置尺寸(750700); frame.setDefaultCloseOperation(关闭时退出); 框架。添加(面板); }
}


感谢阅读。

您可以为每个JTextField设置最小、预期和最大大小,如下所示:

package com.ggl.testing;

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

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

public class GradeAnalysis implements Runnable {

    private static final Insets normalInsets = new Insets(10, 10, 0, 10);
    private static final Insets finalInsets = new Insets(10, 10, 10, 10);

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new GradeAnalysis());
    }

    @Override
    public void run() {
        JFrame frame = new JFrame("Grade Calculator");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(createMainPanel());
        frame.pack();
        frame.setVisible(true);
    }

    private JPanel createMainPanel() {
        GridBagConstraints gbc = new GridBagConstraints();

        // Adding the JPanels. Panel for instructions
        JPanel panel = new JPanel();
        panel.setLayout(new GridBagLayout());

        int gridy = 0;

        // JLabel for the Instructions.
        JTextArea instructionTextArea = new JTextArea(5, 30);
        instructionTextArea.setEditable(false);
        instructionTextArea.setLineWrap(true);
        instructionTextArea.setWrapStyleWord(true);
        instructionTextArea.setText(getInstructions());
        JScrollPane instructionScrollPane = new JScrollPane(instructionTextArea);
        addComponent(panel, instructionScrollPane, 0, gridy++, 3, 1,
                finalInsets, GridBagConstraints.CENTER,
                GridBagConstraints.HORIZONTAL);

        // JLabels for Assignment/Grade/Weight(Percent)
        JLabel label1 = new JLabel("Assignment");
        label1.setHorizontalAlignment(JLabel.CENTER);
        addComponent(panel, label1, 0, gridy, 1, 1, finalInsets,
                GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL);

        JLabel label2 = new JLabel("Mark");
        label2.setHorizontalAlignment(JLabel.CENTER);
        addComponent(panel, label2, 1, gridy, 1, 1, finalInsets,
                GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL);

        JLabel label3 = new JLabel("Weight");
        label3.setHorizontalAlignment(JLabel.CENTER);
        addComponent(panel, label3, 2, gridy++, 1, 1, finalInsets,
                GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL);

        // JLabel Numbers for the number list of assignments at the side.
        JLabel number = new JLabel("1");
        number.setHorizontalAlignment(JLabel.CENTER);
        addComponent(panel, number, 0, gridy, 1, 1, normalInsets,
                GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL);

        // JTextfield for Mark
        JTextField mark = new JTextField(20);
        mark.setHorizontalAlignment(JLabel.CENTER);
        addComponent(panel, mark, 1, gridy, 1, 1, normalInsets,
                GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL);

        // JTextfield for Weight
        JTextField weight = new JTextField(20);
        weight.setHorizontalAlignment(JLabel.CENTER);
        addComponent(panel, weight, 2, gridy++, 1, 1, normalInsets,
                GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL);

        return panel;
    }

    private String getInstructions() {
        return "Instructions: Type in the grades you’ve received, along with the weights "
                + "they’ll have in the determination of your overall average. After you "
                + "press ‘Calculate’, the results will show your average so far. Every "
                + "grade you enter must be a non-negative number, and every "
                + "percentage/weight you enter must be a positive number :)";
    }

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

}

其中MIN和MAX是一个维度对象,设置边界的输入是
int

,您可以为每个JTextField设置最小、预期和最大大小,如下所示:

package com.ggl.testing;

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

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

public class GradeAnalysis implements Runnable {

    private static final Insets normalInsets = new Insets(10, 10, 0, 10);
    private static final Insets finalInsets = new Insets(10, 10, 10, 10);

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new GradeAnalysis());
    }

    @Override
    public void run() {
        JFrame frame = new JFrame("Grade Calculator");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(createMainPanel());
        frame.pack();
        frame.setVisible(true);
    }

    private JPanel createMainPanel() {
        GridBagConstraints gbc = new GridBagConstraints();

        // Adding the JPanels. Panel for instructions
        JPanel panel = new JPanel();
        panel.setLayout(new GridBagLayout());

        int gridy = 0;

        // JLabel for the Instructions.
        JTextArea instructionTextArea = new JTextArea(5, 30);
        instructionTextArea.setEditable(false);
        instructionTextArea.setLineWrap(true);
        instructionTextArea.setWrapStyleWord(true);
        instructionTextArea.setText(getInstructions());
        JScrollPane instructionScrollPane = new JScrollPane(instructionTextArea);
        addComponent(panel, instructionScrollPane, 0, gridy++, 3, 1,
                finalInsets, GridBagConstraints.CENTER,
                GridBagConstraints.HORIZONTAL);

        // JLabels for Assignment/Grade/Weight(Percent)
        JLabel label1 = new JLabel("Assignment");
        label1.setHorizontalAlignment(JLabel.CENTER);
        addComponent(panel, label1, 0, gridy, 1, 1, finalInsets,
                GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL);

        JLabel label2 = new JLabel("Mark");
        label2.setHorizontalAlignment(JLabel.CENTER);
        addComponent(panel, label2, 1, gridy, 1, 1, finalInsets,
                GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL);

        JLabel label3 = new JLabel("Weight");
        label3.setHorizontalAlignment(JLabel.CENTER);
        addComponent(panel, label3, 2, gridy++, 1, 1, finalInsets,
                GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL);

        // JLabel Numbers for the number list of assignments at the side.
        JLabel number = new JLabel("1");
        number.setHorizontalAlignment(JLabel.CENTER);
        addComponent(panel, number, 0, gridy, 1, 1, normalInsets,
                GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL);

        // JTextfield for Mark
        JTextField mark = new JTextField(20);
        mark.setHorizontalAlignment(JLabel.CENTER);
        addComponent(panel, mark, 1, gridy, 1, 1, normalInsets,
                GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL);

        // JTextfield for Weight
        JTextField weight = new JTextField(20);
        weight.setHorizontalAlignment(JLabel.CENTER);
        addComponent(panel, weight, 2, gridy++, 1, 1, normalInsets,
                GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL);

        return panel;
    }

    private String getInstructions() {
        return "Instructions: Type in the grades you’ve received, along with the weights "
                + "they’ll have in the determination of your overall average. After you "
                + "press ‘Calculate’, the results will show your average so far. Every "
                + "grade you enter must be a non-negative number, and every "
                + "percentage/weight you enter must be a positive number :)";
    }

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

}

其中MIN和MAX是一个维度对象,设置边界的输入是
int

,您可以为每个JTextField设置最小、预期和最大大小,如下所示:

package com.ggl.testing;

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

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

public class GradeAnalysis implements Runnable {

    private static final Insets normalInsets = new Insets(10, 10, 0, 10);
    private static final Insets finalInsets = new Insets(10, 10, 10, 10);

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new GradeAnalysis());
    }

    @Override
    public void run() {
        JFrame frame = new JFrame("Grade Calculator");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(createMainPanel());
        frame.pack();
        frame.setVisible(true);
    }

    private JPanel createMainPanel() {
        GridBagConstraints gbc = new GridBagConstraints();

        // Adding the JPanels. Panel for instructions
        JPanel panel = new JPanel();
        panel.setLayout(new GridBagLayout());

        int gridy = 0;

        // JLabel for the Instructions.
        JTextArea instructionTextArea = new JTextArea(5, 30);
        instructionTextArea.setEditable(false);
        instructionTextArea.setLineWrap(true);
        instructionTextArea.setWrapStyleWord(true);
        instructionTextArea.setText(getInstructions());
        JScrollPane instructionScrollPane = new JScrollPane(instructionTextArea);
        addComponent(panel, instructionScrollPane, 0, gridy++, 3, 1,
                finalInsets, GridBagConstraints.CENTER,
                GridBagConstraints.HORIZONTAL);

        // JLabels for Assignment/Grade/Weight(Percent)
        JLabel label1 = new JLabel("Assignment");
        label1.setHorizontalAlignment(JLabel.CENTER);
        addComponent(panel, label1, 0, gridy, 1, 1, finalInsets,
                GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL);

        JLabel label2 = new JLabel("Mark");
        label2.setHorizontalAlignment(JLabel.CENTER);
        addComponent(panel, label2, 1, gridy, 1, 1, finalInsets,
                GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL);

        JLabel label3 = new JLabel("Weight");
        label3.setHorizontalAlignment(JLabel.CENTER);
        addComponent(panel, label3, 2, gridy++, 1, 1, finalInsets,
                GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL);

        // JLabel Numbers for the number list of assignments at the side.
        JLabel number = new JLabel("1");
        number.setHorizontalAlignment(JLabel.CENTER);
        addComponent(panel, number, 0, gridy, 1, 1, normalInsets,
                GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL);

        // JTextfield for Mark
        JTextField mark = new JTextField(20);
        mark.setHorizontalAlignment(JLabel.CENTER);
        addComponent(panel, mark, 1, gridy, 1, 1, normalInsets,
                GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL);

        // JTextfield for Weight
        JTextField weight = new JTextField(20);
        weight.setHorizontalAlignment(JLabel.CENTER);
        addComponent(panel, weight, 2, gridy++, 1, 1, normalInsets,
                GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL);

        return panel;
    }

    private String getInstructions() {
        return "Instructions: Type in the grades you’ve received, along with the weights "
                + "they’ll have in the determination of your overall average. After you "
                + "press ‘Calculate’, the results will show your average so far. Every "
                + "grade you enter must be a non-negative number, and every "
                + "percentage/weight you enter must be a positive number :)";
    }

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

}

其中MIN和MAX是一个维度对象,设置边界的输入是
int

,您可以为每个JTextField设置最小、预期和最大大小,如下所示:

package com.ggl.testing;

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

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

public class GradeAnalysis implements Runnable {

    private static final Insets normalInsets = new Insets(10, 10, 0, 10);
    private static final Insets finalInsets = new Insets(10, 10, 10, 10);

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new GradeAnalysis());
    }

    @Override
    public void run() {
        JFrame frame = new JFrame("Grade Calculator");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(createMainPanel());
        frame.pack();
        frame.setVisible(true);
    }

    private JPanel createMainPanel() {
        GridBagConstraints gbc = new GridBagConstraints();

        // Adding the JPanels. Panel for instructions
        JPanel panel = new JPanel();
        panel.setLayout(new GridBagLayout());

        int gridy = 0;

        // JLabel for the Instructions.
        JTextArea instructionTextArea = new JTextArea(5, 30);
        instructionTextArea.setEditable(false);
        instructionTextArea.setLineWrap(true);
        instructionTextArea.setWrapStyleWord(true);
        instructionTextArea.setText(getInstructions());
        JScrollPane instructionScrollPane = new JScrollPane(instructionTextArea);
        addComponent(panel, instructionScrollPane, 0, gridy++, 3, 1,
                finalInsets, GridBagConstraints.CENTER,
                GridBagConstraints.HORIZONTAL);

        // JLabels for Assignment/Grade/Weight(Percent)
        JLabel label1 = new JLabel("Assignment");
        label1.setHorizontalAlignment(JLabel.CENTER);
        addComponent(panel, label1, 0, gridy, 1, 1, finalInsets,
                GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL);

        JLabel label2 = new JLabel("Mark");
        label2.setHorizontalAlignment(JLabel.CENTER);
        addComponent(panel, label2, 1, gridy, 1, 1, finalInsets,
                GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL);

        JLabel label3 = new JLabel("Weight");
        label3.setHorizontalAlignment(JLabel.CENTER);
        addComponent(panel, label3, 2, gridy++, 1, 1, finalInsets,
                GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL);

        // JLabel Numbers for the number list of assignments at the side.
        JLabel number = new JLabel("1");
        number.setHorizontalAlignment(JLabel.CENTER);
        addComponent(panel, number, 0, gridy, 1, 1, normalInsets,
                GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL);

        // JTextfield for Mark
        JTextField mark = new JTextField(20);
        mark.setHorizontalAlignment(JLabel.CENTER);
        addComponent(panel, mark, 1, gridy, 1, 1, normalInsets,
                GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL);

        // JTextfield for Weight
        JTextField weight = new JTextField(20);
        weight.setHorizontalAlignment(JLabel.CENTER);
        addComponent(panel, weight, 2, gridy++, 1, 1, normalInsets,
                GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL);

        return panel;
    }

    private String getInstructions() {
        return "Instructions: Type in the grades you’ve received, along with the weights "
                + "they’ll have in the determination of your overall average. After you "
                + "press ‘Calculate’, the results will show your average so far. Every "
                + "grade you enter must be a non-negative number, and every "
                + "percentage/weight you enter must be a positive number :)";
    }

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

}

其中MIN和MAX是一个维度对象,设置边界的输入是
int

这是我创建的GUI

  • 我不知道您的主方法在哪里,但是您必须始终通过调用SwingUtilities invokeLater方法启动Swing应用程序。invokeLater方法将Swing组件的创建和执行置于

  • 当我使用GridBagLayout时,我使用我创建的addComponent方法为每个Swing组件创建一个唯一的GridBagConstraints

  • JFrame方法的顺序非常重要。记住本例中JFrame方法的顺序

  • 我把指令放在JTextArea中。这样,指令文本根据JTextArea的大小进行分割。不需要用HTML硬编码换行符

  • 这是密码

    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.Font;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.event.ActionEvent;
    import java.util.List;
    
    import javax.swing.*;
    
    @SuppressWarnings("serial")
    public class GradeAnalysis2 extends JPanel {
       private static final int PREF_H = 400;
       private static final String DISPLAY_TEXT = "Instructions: "
             + "Type in the grades you’ve received, along with the "
             + "weights they’ll have in the determination of your "
             + "overall average.\n"
             + "After you press ‘Calculate’, the results will show "
             + "your average so far.\n"
             + "Every grade you enter must be a non-negative number, "
             + "and every percentage/weight you enter must be a "
             + "positive number :)";
       private JTextArea displayArea = new JTextArea(5, 50);
       private GradeTablePanel gradeTablePanel = new GradeTablePanel();
    
       public GradeAnalysis2() {
          displayArea.setText(DISPLAY_TEXT);
          displayArea.setWrapStyleWord(true);
          displayArea.setLineWrap(true);
          displayArea.setEditable(false);
          displayArea.setFocusable(false);
          displayArea.setBorder(null);
          displayArea.setBackground(null);
    
          JPanel centerPanel = new JPanel(new BorderLayout());
          centerPanel.add(gradeTablePanel, BorderLayout.PAGE_START);
          centerPanel.add(Box.createGlue(), BorderLayout.CENTER);
          JScrollPane scrollPane = new JScrollPane(centerPanel);
    
          JPanel btnPanel = new JPanel();
          btnPanel.add(new JButton(new AddAssignmentAction("Add")));
    
          setLayout(new BorderLayout());
          add(displayArea, BorderLayout.PAGE_START);
          add(scrollPane, BorderLayout.CENTER);
          add(btnPanel, BorderLayout.PAGE_END);
       }
    
       @Override
       public Dimension getPreferredSize() {
          Dimension sz = super.getPreferredSize();
          if (isPreferredSizeSet()) {
             return sz;
          }
          int height = Math.max(sz.height, PREF_H);
          return new Dimension(sz.width, height);
       }
    
       private class AddAssignmentAction extends AbstractAction {
          public AddAssignmentAction(String name) {
             super(name);
             int mnenomic = (int) name.charAt(0);
             putValue(MNEMONIC_KEY, mnenomic);
          }
    
          public void actionPerformed(ActionEvent e) {
             gradeTablePanel.addAssignment();
             gradeTablePanel.revalidate();
             gradeTablePanel.repaint();
          };
       }
    
       private class GradeTablePanel extends JPanel {
          private int count = 0;
    
          // parallel collections -- a bad kludge. 
          // a table model would make this much cleaner
          private List<JTextField> marks;
          private List<JTextField> weights;
    
          public GradeTablePanel() {
             setLayout(new GridBagLayout());
             JLabel assgmntLbl = new JLabel(Assignment.ASSIGNMENT, SwingConstants.CENTER);
             assgmntLbl.setFont(assgmntLbl.getFont().deriveFont(Font.BOLD));
             JLabel markLbl = new JLabel(Assignment.MARK, SwingConstants.CENTER);
             markLbl.setFont(markLbl.getFont().deriveFont(Font.BOLD));
             JLabel weightLbl = new JLabel(Assignment.WEIGHT, SwingConstants.CENTER);
             weightLbl.setFont(weightLbl.getFont().deriveFont(Font.BOLD));
    
             add(assgmntLbl, createGbc(0, 0));
             add(markLbl, createGbc(1, 0));
             add(weightLbl, createGbc(2, 0));
          }
    
          private GridBagConstraints createGbc(int x, int y) {
             GridBagConstraints gbc = new GridBagConstraints();
             gbc.gridx = x;
             gbc.gridy = y;
             gbc.gridwidth = 1;
             gbc.gridheight = 1;
             gbc.fill = GridBagConstraints.VERTICAL;
             gbc.weightx = 1.0;
             gbc.weighty = 1.0;
             gbc.anchor = GridBagConstraints.CENTER;
             return gbc;
          }
    
          public void addAssignment() {
             count++;
             JLabel countLabel = new JLabel(String.valueOf(count));
             JTextField markField = new JTextField(2);
             JTextField weightField = new JTextField(2);
    
             add(countLabel, createGbc(0, count));
             add(markField, createGbc(1, count));
             add(weightField, createGbc(2, count));
          }
    
       }
    
       private static void createAndShowGui() {
          JFrame frame = new JFrame("GradeAnalysis2");
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.getContentPane().add(new GradeAnalysis2());
          frame.pack();
          frame.setLocationRelativeTo(null);
          frame.setVisible(true);
       }
    
       public static void main(String[] args) {
          SwingUtilities.invokeLater(new Runnable() {
             public void run() {
                createAndShowGui();
             }
          });
       }
    }
    
    
    class Assignment {
       public static final String ASSIGNMENT = "Assignment";
       public static final String MARK = "Mark";
       public static final String WEIGHT = "Weight";
       private String assignment;
       private int mark;
       private double weight;
       public Assignment(String assignment, int mark, double weight) {
          this.assignment = assignment;
          this.mark = mark;
          this.weight = weight;
       }
       public String getAssignment() {
          return assignment;
       }
       public void setAssignment(String assignment) {
          this.assignment = assignment;
       }
       public int getMark() {
          return mark;
       }
       public void setMark(int mark) {
          this.mark = mark;
       }
       public double getWeight() {
          return weight;
       }
       public void setWeight(double weight) {
          this.weight = weight;
       }
    
    
    }
    

    这是我创建的GUI

  • 我不知道您的主方法在哪里,但是您必须始终通过调用SwingUtilities invokeLater方法启动Swing应用程序。invokeLater方法将Swing组件的创建和执行置于

  • 当我使用GridBagLayout时,我使用我创建的addComponent方法为每个Swing组件创建一个唯一的GridBagConstraints

  • JFrame方法的顺序非常重要。记住本例中JFrame方法的顺序

  • 我把指令放在JTextArea中。这样,指令文本根据JTextArea的大小进行分割。不需要用HTML硬编码换行符

  • 这是密码

    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.Font;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.event.ActionEvent;
    import java.util.List;
    
    import javax.swing.*;
    
    @SuppressWarnings("serial")
    public class GradeAnalysis2 extends JPanel {
       private static final int PREF_H = 400;
       private static final String DISPLAY_TEXT = "Instructions: "
             + "Type in the grades you’ve received, along with the "
             + "weights they’ll have in the determination of your "
             + "overall average.\n"
             + "After you press ‘Calculate’, the results will show "
             + "your average so far.\n"
             + "Every grade you enter must be a non-negative number, "
             + "and every percentage/weight you enter must be a "
             + "positive number :)";
       private JTextArea displayArea = new JTextArea(5, 50);
       private GradeTablePanel gradeTablePanel = new GradeTablePanel();
    
       public GradeAnalysis2() {
          displayArea.setText(DISPLAY_TEXT);
          displayArea.setWrapStyleWord(true);
          displayArea.setLineWrap(true);
          displayArea.setEditable(false);
          displayArea.setFocusable(false);
          displayArea.setBorder(null);
          displayArea.setBackground(null);
    
          JPanel centerPanel = new JPanel(new BorderLayout());
          centerPanel.add(gradeTablePanel, BorderLayout.PAGE_START);
          centerPanel.add(Box.createGlue(), BorderLayout.CENTER);
          JScrollPane scrollPane = new JScrollPane(centerPanel);
    
          JPanel btnPanel = new JPanel();
          btnPanel.add(new JButton(new AddAssignmentAction("Add")));
    
          setLayout(new BorderLayout());
          add(displayArea, BorderLayout.PAGE_START);
          add(scrollPane, BorderLayout.CENTER);
          add(btnPanel, BorderLayout.PAGE_END);
       }
    
       @Override
       public Dimension getPreferredSize() {
          Dimension sz = super.getPreferredSize();
          if (isPreferredSizeSet()) {
             return sz;
          }
          int height = Math.max(sz.height, PREF_H);
          return new Dimension(sz.width, height);
       }
    
       private class AddAssignmentAction extends AbstractAction {
          public AddAssignmentAction(String name) {
             super(name);
             int mnenomic = (int) name.charAt(0);
             putValue(MNEMONIC_KEY, mnenomic);
          }
    
          public void actionPerformed(ActionEvent e) {
             gradeTablePanel.addAssignment();
             gradeTablePanel.revalidate();
             gradeTablePanel.repaint();
          };
       }
    
       private class GradeTablePanel extends JPanel {
          private int count = 0;
    
          // parallel collections -- a bad kludge. 
          // a table model would make this much cleaner
          private List<JTextField> marks;
          private List<JTextField> weights;
    
          public GradeTablePanel() {
             setLayout(new GridBagLayout());
             JLabel assgmntLbl = new JLabel(Assignment.ASSIGNMENT, SwingConstants.CENTER);
             assgmntLbl.setFont(assgmntLbl.getFont().deriveFont(Font.BOLD));
             JLabel markLbl = new JLabel(Assignment.MARK, SwingConstants.CENTER);
             markLbl.setFont(markLbl.getFont().deriveFont(Font.BOLD));
             JLabel weightLbl = new JLabel(Assignment.WEIGHT, SwingConstants.CENTER);
             weightLbl.setFont(weightLbl.getFont().deriveFont(Font.BOLD));
    
             add(assgmntLbl, createGbc(0, 0));
             add(markLbl, createGbc(1, 0));
             add(weightLbl, createGbc(2, 0));
          }
    
          private GridBagConstraints createGbc(int x, int y) {
             GridBagConstraints gbc = new GridBagConstraints();
             gbc.gridx = x;
             gbc.gridy = y;
             gbc.gridwidth = 1;
             gbc.gridheight = 1;
             gbc.fill = GridBagConstraints.VERTICAL;
             gbc.weightx = 1.0;
             gbc.weighty = 1.0;
             gbc.anchor = GridBagConstraints.CENTER;
             return gbc;
          }
    
          public void addAssignment() {
             count++;
             JLabel countLabel = new JLabel(String.valueOf(count));
             JTextField markField = new JTextField(2);
             JTextField weightField = new JTextField(2);
    
             add(countLabel, createGbc(0, count));
             add(markField, createGbc(1, count));
             add(weightField, createGbc(2, count));
          }
    
       }
    
       private static void createAndShowGui() {
          JFrame frame = new JFrame("GradeAnalysis2");
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.getContentPane().add(new GradeAnalysis2());
          frame.pack();
          frame.setLocationRelativeTo(null);
          frame.setVisible(true);
       }
    
       public static void main(String[] args) {
          SwingUtilities.invokeLater(new Runnable() {
             public void run() {
                createAndShowGui();
             }
          });
       }
    }
    
    
    class Assignment {
       public static final String ASSIGNMENT = "Assignment";
       public static final String MARK = "Mark";
       public static final String WEIGHT = "Weight";
       private String assignment;
       private int mark;
       private double weight;
       public Assignment(String assignment, int mark, double weight) {
          this.assignment = assignment;
          this.mark = mark;
          this.weight = weight;
       }
       public String getAssignment() {
          return assignment;
       }
       public void setAssignment(String assignment) {
          this.assignment = assignment;
       }
       public int getMark() {
          return mark;
       }
       public void setMark(int mark) {
          this.mark = mark;
       }
       public double getWeight() {
          return weight;
       }
       public void setWeight(double weight) {
          this.weight = weight;
       }
    
    
    }
    

    这是我创建的GUI

  • 我不知道您的主方法在哪里,但是您必须始终通过调用SwingUtilities invokeLater方法启动Swing应用程序。invokeLater方法将Swing组件的创建和执行置于

  • 当我使用GridBagLayout时,我使用我创建的addComponent方法为每个Swing组件创建一个唯一的GridBagConstraints

  • JFrame方法的顺序非常重要。记住本例中JFrame方法的顺序

  • 我把指令放在JTextArea中。这样,指令文本根据JTextArea的大小进行分割。不需要用HTML硬编码换行符

  • 这是密码

    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.Font;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.event.ActionEvent;
    import java.util.List;
    
    import javax.swing.*;
    
    @SuppressWarnings("serial")
    public class GradeAnalysis2 extends JPanel {
       private static final int PREF_H = 400;
       private static final String DISPLAY_TEXT = "Instructions: "
             + "Type in the grades you’ve received, along with the "
             + "weights they’ll have in the determination of your "
             + "overall average.\n"
             + "After you press ‘Calculate’, the results will show "
             + "your average so far.\n"
             + "Every grade you enter must be a non-negative number, "
             + "and every percentage/weight you enter must be a "
             + "positive number :)";
       private JTextArea displayArea = new JTextArea(5, 50);
       private GradeTablePanel gradeTablePanel = new GradeTablePanel();
    
       public GradeAnalysis2() {
          displayArea.setText(DISPLAY_TEXT);
          displayArea.setWrapStyleWord(true);
          displayArea.setLineWrap(true);
          displayArea.setEditable(false);
          displayArea.setFocusable(false);
          displayArea.setBorder(null);
          displayArea.setBackground(null);
    
          JPanel centerPanel = new JPanel(new BorderLayout());
          centerPanel.add(gradeTablePanel, BorderLayout.PAGE_START);
          centerPanel.add(Box.createGlue(), BorderLayout.CENTER);
          JScrollPane scrollPane = new JScrollPane(centerPanel);
    
          JPanel btnPanel = new JPanel();
          btnPanel.add(new JButton(new AddAssignmentAction("Add")));
    
          setLayout(new BorderLayout());
          add(displayArea, BorderLayout.PAGE_START);
          add(scrollPane, BorderLayout.CENTER);
          add(btnPanel, BorderLayout.PAGE_END);
       }
    
       @Override
       public Dimension getPreferredSize() {
          Dimension sz = super.getPreferredSize();
          if (isPreferredSizeSet()) {
             return sz;
          }
          int height = Math.max(sz.height, PREF_H);
          return new Dimension(sz.width, height);
       }
    
       private class AddAssignmentAction extends AbstractAction {
          public AddAssignmentAction(String name) {
             super(name);
             int mnenomic = (int) name.charAt(0);
             putValue(MNEMONIC_KEY, mnenomic);
          }
    
          public void actionPerformed(ActionEvent e) {
             gradeTablePanel.addAssignment();
             gradeTablePanel.revalidate();
             gradeTablePanel.repaint();
          };
       }
    
       private class GradeTablePanel extends JPanel {
          private int count = 0;
    
          // parallel collections -- a bad kludge. 
          // a table model would make this much cleaner
          private List<JTextField> marks;
          private List<JTextField> weights;
    
          public GradeTablePanel() {
             setLayout(new GridBagLayout());
             JLabel assgmntLbl = new JLabel(Assignment.ASSIGNMENT, SwingConstants.CENTER);
             assgmntLbl.setFont(assgmntLbl.getFont().deriveFont(Font.BOLD));
             JLabel markLbl = new JLabel(Assignment.MARK, SwingConstants.CENTER);
             markLbl.setFont(markLbl.getFont().deriveFont(Font.BOLD));
             JLabel weightLbl = new JLabel(Assignment.WEIGHT, SwingConstants.CENTER);
             weightLbl.setFont(weightLbl.getFont().deriveFont(Font.BOLD));
    
             add(assgmntLbl, createGbc(0, 0));
             add(markLbl, createGbc(1, 0));
             add(weightLbl, createGbc(2, 0));
          }
    
          private GridBagConstraints createGbc(int x, int y) {
             GridBagConstraints gbc = new GridBagConstraints();
             gbc.gridx = x;
             gbc.gridy = y;
             gbc.gridwidth = 1;
             gbc.gridheight = 1;
             gbc.fill = GridBagConstraints.VERTICAL;
             gbc.weightx = 1.0;
             gbc.weighty = 1.0;
             gbc.anchor = GridBagConstraints.CENTER;
             return gbc;
          }
    
          public void addAssignment() {
             count++;
             JLabel countLabel = new JLabel(String.valueOf(count));
             JTextField markField = new JTextField(2);
             JTextField weightField = new JTextField(2);
    
             add(countLabel, createGbc(0, count));
             add(markField, createGbc(1, count));
             add(weightField, createGbc(2, count));
          }
    
       }
    
       private static void createAndShowGui() {
          JFrame frame = new JFrame("GradeAnalysis2");
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.getContentPane().add(new GradeAnalysis2());
          frame.pack();
          frame.setLocationRelativeTo(null);
          frame.setVisible(true);
       }
    
       public static void main(String[] args) {
          SwingUtilities.invokeLater(new Runnable() {
             public void run() {
                createAndShowGui();
             }
          });
       }
    }
    
    
    class Assignment {
       public static final String ASSIGNMENT = "Assignment";
       public static final String MARK = "Mark";
       public static final String WEIGHT = "Weight";
       private String assignment;
       private int mark;
       private double weight;
       public Assignment(String assignment, int mark, double weight) {
          this.assignment = assignment;
          this.mark = mark;
          this.weight = weight;
       }
       public String getAssignment() {
          return assignment;
       }
       public void setAssignment(String assignment) {
          this.assignment = assignment;
       }
       public int getMark() {
          return mark;
       }
       public void setMark(int mark) {
          this.mark = mark;
       }
       public double getWeight() {
          return weight;
       }
       public void setWeight(double weight) {
          this.weight = weight;
       }
    
    
    }
    

    这是我创建的GUI

  • 我不知道您的主方法在哪里,但是您必须始终通过调用SwingUtilities invokeLater方法启动Swing应用程序