Java jbutton事件ActionListener

Java jbutton事件ActionListener,java,swing,jbutton,Java,Swing,Jbutton,您好,我有一个正在实施的项目,对于这个类NewPatient(),我有3个按钮,我想触发事件,但不幸的是,我到目前为止能够触发两个按钮的事件,这两个按钮是返回并清除的。但是提交一个不会触发任何我不理解的事件。我不知道我错过了什么。我已经发布了下面的m 3课程 in short that is how I refined it import javax.swing.JFrame; public class MyCare { publi

您好,我有一个正在实施的项目,对于这个类NewPatient(),我有3个按钮,我想触发事件,但不幸的是,我到目前为止能够触发两个按钮的事件,这两个按钮是返回并清除的。但是提交一个不会触发任何我不理解的事件。我不知道我错过了什么。我已经发布了下面的m 3课程

    in short that is how I refined it 

    import javax.swing.JFrame;

    public class MyCare 
    {   

        public static void main(String[] args) 
        {

                NewPatient application = new NewPatient();

            application.setVisible(true);

            application.setLocation(500,150);
            //application.setLocationRelativeTo(null);
            application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

          }
    }

    /**
     * @(#)NewPatient.java
     *
     *
     * @author 
     * @version 1.00 2014/9/8
     */

        import javax.swing.JFrame;
        import javax.swing.JOptionPane;
        import javax.swing.JLabel;
        import javax.swing.JTextField;
        import javax.swing.JPanel;
        import javax.swing.BorderFactory;
        import javax.swing.border.TitledBorder;
        import javax.swing.border.LineBorder;
        import javax.swing.border.Border;
        import java.awt.Color;
        import javax.swing.JPasswordField;
        import javax.swing.JButton;
        import javax.swing.Icon;
        import javax.swing.ImageIcon;
        import java.awt.event.ActionEvent;
        import java.awt.event.ActionListener;
        import java.awt.event.ItemListener;
        import java.awt.event.ItemEvent;
        import javax.swing.JTabbedPane;
        import java.awt.Font;
        import javax.swing.JComboBox;
        import java.util.Random;
        import javax.swing.JRadioButton;
        import javax.swing.ButtonGroup;
        import javax.swing.JTextArea;
        import javax.swing.Box;
        import javax.swing.JScrollPane;

        public class NewPatient extends JFrame implements ActionListener
        {
            //////////////////////// new patient labels

            private JLabel name;
            private JLabel sname;
            private JLabel initial;

            /////////////////////////////// new patient textfields

            private JTextField nameField;
            private JTextField snameField;
            private JTextField initialField;
        //          
            /////// buttons

            private JButton back;
            private JButton clear;
            private JButton send;

            ///// container

            private JPanel container;

            public NewPatient() 
            {
                super("NEW PATIENT");   

                this.setSize(600,580);
                this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
                this.setResizable(false);       


                //////////////// initializing and setting the main panel

                container = new JPanel();


                Border titleBorder = new TitledBorder(new LineBorder(Color.BLACK),"REGISTER");
                container.setBorder(titleBorder);
                container.setLayout(null);

                //////////////////////// folder 


                name = new JLabel("NAME(S):");
                name.setBounds(10,85,80,15);
    //    name.setFont(labeNameFont);

                nameField = new JTextField();
                nameField.setBounds(80,80,150,27);
    //          nameField.setFont(labeNameFont);


                initialField = new JTextField(15);
                initialField.setBounds(407,80,60,27);
    //          initialField.setFont(labeNameFont);


                ///////////////// surname

                sname = new JLabel("SURNAME:");
                sname.setBounds(10,119,80,15);
    //          sname.setFont(labeNameFont);

                snameField = new JTextField(15);
                snameField.setBounds(80,115,150,27);
    //          snameField.setFont(labeNameFont);


                //////////////////////////////      back

                back = new JButton("BACK");
    //          back.setFont(labeNameFont);
                back.setBounds(80,490,80,27);

                ///////////////////////// clear

                clear = new JButton("CLEAR");
    //          clear.setFont(labeNameFont);
                clear.setBounds(280,490,80,27);

                ///////////////////////// Proceed

                send = new JButton("SUBMIT");
    //          send.setFont(labeNameFont);
                send.setBounds(480,490,80,27);

                ////////////////add components to panel

                registerPatient();

                ///////////////// register button events

                back.addActionListener(this);
                clear.addActionListener(this);
                send.addActionListener(this);
    ////            countryBox.addItemListener(this);

                ////////////adding panel


                add(container);

            }

                   public void registerPatient()
           {

                container.add(name);
                container.add(nameField);
                container.add(sname);
                container.add(snameField);



                ////////// add buttons

                container.add(back);
                container.add(clear);
                container.add(send);


                this.setVisible(true);
                this.setLocation(500,80);
           }


           /////////////////// clear fields

           public void clearFields()
           {

                nameField.setText("");

                snameField.setText("");


           }

           //////////////////////// triggering events



           public void actionPerformed(ActionEvent event)
           {
                if(event.getActionCommand().equals("BACK"))
                {
    //              

                    this.dispose();
                }


                if(event.getActionCommand().equals("CLEAR"))
                {
                    clearFields();
                }


                if(event.getActionCommand().equals("SUBMIT"))
                {
                    //ValidateInput validateData = new ValidateInput(); //// input validation

                    FullDetails mydetails = new FullDetails();

                    System.out.println("gtmtfsgsdg");

                    try
                    {
                        if(!ValidateInput.validateFirstName(nameField.getText()))
                        {
                            System.out.println("youtube");

                                            String message = String.format("Invalid Format!!! NAME must only be one word");  

                                            JOptionPane.showMessageDialog(null,message, "ERROR", JOptionPane.ERROR_MESSAGE);
                        }

                        else 
                        {
                            mydetails.setFirstName(nameField.getText()) ;

                            if(!ValidateInput.validateSurName(snameField.getText()))
                            {
                                String msg = String.format("Invalid Format!!! SURNAME must only be one word");  

                                JOptionPane.showMessageDialog(null, msg, "ERROR", JOptionPane.ERROR_MESSAGE);
                            }

                            else{

                                mydetails.setSurname(snameField.getText());
                            }

                        }


                    }

                catch(Exception e)
                    {


                         String msg = String.format("Invalid input. Please make sure that you have filled every text fields!!! Please enter a correct one");  

                        JOptionPane.showMessageDialog(null, msg, "ERROR", JOptionPane.ERROR_MESSAGE);
                    }
                }

           }

        } 


    /**
         * @(#)ValidateInput.java
         */

        public class ValidateInput 
        {
            public static boolean validateFirstName(String firstName)
            {
                return firstName.matches("[a-zA-Z]*");
            }

            public static boolean validateSurName(String surname)
            {
                return surname.matches("[A-zA-z]+(['-][a-zA-Z]+)*");
            }
            public static boolean validateInitial(String initial)
            {
                return initial.matches("[A-Z]*");
            }
         }


    public class FullDetails 
        {


            private static String firstName;

            private static String surname;

             public void setFirstName(String firstName)
            {
                this.firstName = firstName;
            }

            public String getFirstName()
            {
                return firstName;
            }

            public void setSurname(String surname)
            {
                this.surname = surname;
            }
            public String getSurname()
            {
                return surname;
            }
            public static String getSurnam()
            {
                return surname;
            }

        }

在actionPerformed方法的SUBMIT部分中创建一个FullDetails对象,将其分配给mydetails变量,并向其中添加一些数据,包括名称信息,但之后您似乎不会对该对象及其数据执行任何操作。您将需要对该对象执行一些操作,可能需要在GUI的某个位置显示其内容,以便它执行任何操作

另外,请注意,您的FullDetails类存在静态字段使用不当的问题。大多数字段都应该是非静态实例字段。通过这样做,每个FullDetails实例将共享所有相同的数据,这有可能产生严重的副作用,包括FullDetails对象的集合,这些对象都不是唯一的。您将需要修复此问题

其他不太重要的问题:

  • 您的GUI主要使用空布局和
    设置边界
    ,这是您希望避免的,因为使用空布局会导致非常不灵活的GUI,虽然它们在一个平台上看起来不错,但在大多数其他平台或屏幕分辨率上看起来很糟糕,并且很难更新和维护
  • 如果您仍然需要帮助,那么根据我对您原始帖子的评论,您将需要创建并发布一个。我看到您已经将发布的代码缩短了一些,但它仍然有非核心对象,如JDateChooser,它仍然引用您的其他类,如PatientPanel,并且仍然没有主方法,这意味着我们无法编译、运行或测试它

编辑
我试图为您的代码创建一个可编译版本,但当我运行它时,SUBMIT部分中的System.out.println可以工作:

import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.Random;

import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.border.Border;
import javax.swing.border.LineBorder;
import javax.swing.border.TitledBorder;

//!! import com.toedter.calendar.*; //!! we don't have this package

public class NewPatient extends JFrame implements ActionListener, ItemListener {
   // ////////////////////// new patient labels
   // !! enter code here //!! WTF??? this shouldn't be here, non commented
   private JLabel name;
   private JLabel sname;
   private JLabel initial;
   private JLabel gender;
   private JLabel address;
   private JLabel confirm;
   private JLabel phone;
   private JLabel email;
   private JLabel dob;
   private JLabel country;
   private JLabel city;
   private JLabel province;
   private JLabel balance;
   private JLabel userName;
   private JLabel password;
   private JLabel mail;
   private JLabel folderLabel;
   private JLabel idLabel;
   private JLabel label;
   private JLabel label1;
   // ///////////////////////////// new patient textfields
   private JTextField nameField;
   private JTextField snameField;
   private JTextField initialField;
   // private JTextField dobField;
   private JTextField provinceField;
   private JTextField phoneField;
   private JTextField emailField;
   private JTextField balanceField;
   private JTextField userNameField;
   private JTextField folderField;
   private JTextField idField;
   private JTextField cityField;
   private JTextField mailField;
   // /////////////////// state province combo box
   private JComboBox countryBox;
   // private JComboBox cityBox;
   // private JComboBox provinceBox;
   // ////////////// password fields
   private JPasswordField passwordField;
   private JPasswordField confirmField;
   // /////////////// radio buttons
   private JRadioButton maleBtn;
   private JRadioButton femaleBtn;
   // ///////////// radio button group
   private ButtonGroup groupSex;
   // //////////////panel to containt components
   private JPanel container;
   // ///////////// fonts
   Font labeNameFont = null;
   // //////////// text area
   private JTextArea addressArea;
   // ///////////// box
   private Box boxArea;
   // /////////////////////// variables
   private static final String[] countryNames = { "", "BOTSWANA", "CONGO",
         "DR CONGO", "SOUTH AFRICA", "RWANDA", "ZIMBABWE" };
   // //////////////////// buttons
   private JButton back;
   private JButton clear;
   private JButton send;

   // ///////////// calendar
   // !! private JDateChooser chooser;
   public NewPatient() {
      super("NEW PATIENT");
      this.setSize(600, 580);
      this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      this.setResizable(false);
      // /////////////////// labels fonts
      labeNameFont = new Font("SansSerif", Font.BOLD, 12);
      // ////////////// initializing and setting the main panel
      container = new JPanel();
      Border titleBorder = new TitledBorder(new LineBorder(Color.BLACK),
            "REGISTER");
      container.setBorder(titleBorder);
      container.setLayout(null);
      // ////////////////////// folder
      folderLabel = new JLabel("FOLDER NUMBER:");
      folderLabel.setBounds(140, 30, 110, 25);
      folderLabel.setFont(labeNameFont);
      folderField = new JTextField(15);
      folderField.setBounds(250, 30, 90, 27);
      folderField.setEditable(false);
      folderField.setBackground(Color.YELLOW);
      folderField.setText(patientNum());
      folderField.setFont(labeNameFont);
      // ////////////////// name
      name = new JLabel("NAME(S):");
      name.setBounds(10, 85, 80, 15);
      name.setFont(labeNameFont);
      nameField = new JTextField();
      nameField.setBounds(80, 80, 150, 27);
      nameField.setFont(labeNameFont);
      // //////////////////// initial
      initial = new JLabel("INITIAL:");
      initial.setFont(labeNameFont);
      initial.setBounds(347, 82, 80, 20);
      initialField = new JTextField(15);
      initialField.setBounds(407, 80, 60, 27);
      initialField.setFont(labeNameFont);
      // /////////////// surname
      sname = new JLabel("SURNAME:");
      sname.setBounds(10, 119, 80, 15);
      sname.setFont(labeNameFont);
      snameField = new JTextField(15);
      snameField.setBounds(80, 115, 150, 27);
      snameField.setFont(labeNameFont);
      // //////////////////////////// gender radio and group button
      gender = new JLabel("GENDER:");
      gender.setBounds(347, 117, 80, 15);
      gender.setFont(labeNameFont);
      maleBtn = new JRadioButton("MALE");
      maleBtn.setBounds(407, 114, 80, 20);
      maleBtn.setFont(labeNameFont);
      femaleBtn = new JRadioButton("FEMALE");
      femaleBtn.setFont(labeNameFont);
      femaleBtn.setBounds(490, 114, 80, 20);
      groupSex = new ButtonGroup();
      groupSex.add(maleBtn);
      groupSex.add(femaleBtn);
      // ////////////////// id
      idLabel = new JLabel("ID NUM:");
      idLabel.setBounds(10, 154, 80, 15);
      idLabel.setFont(labeNameFont);
      idField = new JTextField(15);
      idField.setBounds(80, 150, 150, 27);
      idField.setFont(labeNameFont);
      // /////////////////// address
      address = new JLabel("Address:");
      address.setBounds(347, 154, 70, 15);
      address.setFont(labeNameFont);
      boxArea = Box.createHorizontalBox();
      addressArea = new JTextArea(10, 10);
      addressArea.setLineWrap(true);
      addressArea.setFont(labeNameFont);
      boxArea.setBounds(407, 150, 150, 80);
      boxArea.setFont(labeNameFont);
      boxArea.add(new JScrollPane(addressArea));
      // /////////// date of birth
      dob = new JLabel("D.O.B:");
      dob.setBounds(10, 190, 50, 15);
      dob.setFont(labeNameFont);
      /*
       * dobField = new JTextField(15); dobField.setBounds(80,185,150,27);
       * dobField.setFont(labeNameFont);
       */
      // !! chooser = new JDateChooser();
      // chooser.setFont(labeNameFont);
      // chooser.setBounds(80,185,150,27);
      // ///////////////////////// country
      country = new JLabel("COUNTRY:");
      country.setBounds(10, 230, 70, 15);
      country.setFont(labeNameFont);
      countryBox = new JComboBox(countryNames);
      countryBox.setBounds(80, 225, 150, 27);
      countryBox.setFont(labeNameFont);
      countryBox.setMaximumRowCount(3);
      // /////////////////////////////////// city
      city = new JLabel("CITY:");
      city.setFont(labeNameFont);
      city.setBounds(347, 248, 70, 15);
      // city.setVisible(false);
      cityField = new JTextField(15);
      cityField.setFont(labeNameFont);
      cityField.setBounds(407, 242, 150, 27);
      // cityField.setVisible(false);
      cityField.setEditable(false);
      // //////////////////// province
      province = new JLabel("PROVINCE:");
      province.setBounds(10, 271, 80, 15);
      province.setFont(labeNameFont);
      provinceField = new JTextField(15);
      provinceField.setFont(labeNameFont);
      provinceField.setBounds(80, 267, 150, 27);
      provinceField.setEditable(false);
      // /////////////////////// phone
      phone = new JLabel("PHONE:");
      phone.setBounds(10, 313, 70, 15);
      phone.setFont(labeNameFont);
      phoneField = new JTextField(15);
      phoneField.setBounds(80, 306, 150, 27);
      phoneField.setFont(labeNameFont);
      // /////////////////////// email
      email = new JLabel("EMAIL:");
      email.setBounds(347, 288, 70, 15);
      email.setFont(labeNameFont);
      emailField = new JTextField(15);
      emailField.setBounds(409, 282, 150, 27);
      emailField.setFont(labeNameFont);
      mail = new JLabel("CONFIRM EMAIL:");
      mail.setBounds(347, 335, 100, 15);
      mail.setFont(labeNameFont);
      mailField = new JTextField(15);
      mailField.setBounds(410, 360, 150, 27);
      mailField.setFont(labeNameFont);
      label1 = new JLabel("\" name@kalilinux.org \"");
      label1.setFont(new Font("SansSerif", Font.BOLD + Font.ITALIC, 12));
      label1.setBounds(420, 300, 150, 27);
      // ///////////// phone formaat label
      // Font font = null;
      label = new JLabel("(0XX-XXX-XXXX)");
      label.setFont(new Font("SansSerif", Font.BOLD + Font.ITALIC, 12));
      label.setBounds(100, 325, 150, 27);
      // ////////////// address
      balance = new JLabel("BALANCE:");
      balance.setBounds(10, 360, 70, 15);
      balance.setFont(labeNameFont);
      balanceField = new JTextField(15);
      balanceField.setBounds(80, 357, 150, 27);
      balanceField.setFont(labeNameFont);
      // /////// username and password
      userName = new JLabel("USER NAME:");
      userName.setBounds(10, 395, 100, 15);
      userName.setFont(labeNameFont);
      userNameField = new JTextField(15);
      userNameField.setBounds(80, 392, 150, 27);
      userNameField.setFont(labeNameFont);
      password = new JLabel("PASSWORD:");
      password.setBounds(10, 435, 80, 15);
      password.setFont(labeNameFont);
      passwordField = new JPasswordField(15);
      passwordField.setBounds(80, 432, 150, 27);
      passwordField.setFont(labeNameFont);
      confirm = new JLabel("CONFIRM PASSWORD:");
      confirm.setBounds(347, 403, 150, 15);
      confirm.setFont(labeNameFont);
      confirmField = new JPasswordField(15);
      confirmField.setBounds(410, 425, 150, 27);
      confirmField.setFont(labeNameFont);
      // //////////////////////////// back
      back = new JButton("BACK");
      back.setFont(labeNameFont);
      back.setBounds(80, 490, 80, 27);
      // /////////////////////// clear
      clear = new JButton("CLEAR");
      clear.setFont(labeNameFont);
      clear.setBounds(280, 490, 80, 27);
      // /////////////////////// Proceed
      send = new JButton("SUBMIT");
      send.setFont(labeNameFont);
      send.setBounds(480, 490, 80, 27);
      // //////////////add components to panel
      registerPatient();
      // /////////////// register button events
      back.addActionListener(this);
      clear.addActionListener(this);
      send.addActionListener(this);
      countryBox.addItemListener(this);
      // //////////adding panel
      add(container);
   }

   public String patientNum() {
      Random numberGenerated = new Random();
      String myNumGen = " MKW - ";
      int starter;
      starter = 473 + numberGenerated.nextInt(9528);
      String start = String.format("%d", starter);
      return myNumGen + " " + start;
   }

   public void registerPatient() {
      container.add(folderLabel);
      container.add(folderField);
      container.add(name);
      container.add(nameField);
      container.add(sname);
      container.add(snameField);
      container.add(idLabel);
      container.add(idField);
      container.add(dob);
      // container.add(dobField);
      // !! container.add(chooser);
      container.add(initial);
      container.add(initialField);
      container.add(gender);
      container.add(maleBtn);
      container.add(femaleBtn);
      container.add(address);
      container.add(boxArea);
      container.add(country);
      container.add(countryBox);
      container.add(city);
      container.add(cityField);
      container.add(province);
      container.add(provinceField);
      container.add(phone);
      container.add(phoneField);
      container.add(label);
      container.add(label1);
      container.add(email);
      container.add(emailField);
      container.add(balance);
      container.add(balanceField);
      container.add(mail);
      container.add(mailField);
      container.add(userName);
      container.add(userNameField);
      container.add(password);
      container.add(passwordField);
      container.add(confirm);
      container.add(confirmField);
      // //////// add buttons
      container.add(back);
      container.add(clear);
      container.add(send);
      this.setVisible(true);
      this.setLocation(500, 80);
   }

   // ///////////////// clear fields
   public void clearFields() {
      folderField.setText(patientNum());
      folderField.setFont(labeNameFont);
      nameField.setText("");
      initialField.setText("");
      snameField.setText("");
      idField.setText("");
      // !! chooser.setCalendar(null);
      provinceField.setText("");
      cityField.setText("");
      emailField.setText("");
      confirmField.setText("");
      passwordField.setText("");
      mailField.setText("");
      userNameField.setText("");
      balanceField.setText("");
      addressArea.setText("");
      phoneField.setText("");
      countryBox.setSelectedIndex(0);
      groupSex.clearSelection();
      // femaleBtn.setSelected(false);
   }

   // ////////////////////// triggering events
   public void itemStateChanged(ItemEvent myevent) {
      Object selected = countryBox.getSelectedItem();
      if (selected.toString().equals("")) {
         provinceField.setText("");
         cityField.setText("");
      } else if (selected.toString().equals("BOTSWANA")) {
         provinceField.setText("SOUTH-EAST");
         cityField.setText("GABORONE");
      } else if (selected.toString().equals("CONGO")) {
         provinceField.setText("POOL");
         cityField.setText("BRAZAVILLE");
      } else if (selected.toString().equals("DR CONGO")) {
         provinceField.setText("KINSHASA");
         cityField.setText("KINSHASA");
      } else if (selected.toString().equals("SOUTH AFRICA")) {
         provinceField.setText("WESTERN CAPE");
         cityField.setText("CAPE TOWN");
      } else if (selected.toString().equals("RWANDA")) {
         provinceField.setText("KIGALI");
         cityField.setText("KIGALI CITY");
      } else if (selected.toString().equals("ZIMBABWE")) {
         provinceField.setText("HARARE");
         cityField.setText("HARARE");
      }
   }

   public void actionPerformed(ActionEvent event) {
      if (event.getActionCommand().equals("BACK")) {
         PatientPanel patient = new PatientPanel();
         patient.setVisible(true);
         patient.setLocation(500, 250);
         dispose();
      }
      if (event.getActionCommand().equals("CLEAR")) {
         clearFields();
      }
      if (event.getActionCommand().equals("SUBMIT")) {
         // ValidateInput validateData = new ValidateInput(); //// input
         // validation
         FullDetails mydetails = new FullDetails();
         System.out.println("gtmtfsgsdg");
         try {
            if (!ValidateInput.validateFirstName(nameField.getText())) {
               System.out.println("youtube");
               String message = String
                     .format("Invalid Format!!! NAME must only be one word");
               JOptionPane.showMessageDialog(null, message, "ERROR",
                     JOptionPane.ERROR_MESSAGE);
            } else {
               mydetails.setFirstName(nameField.getText());
               if (!ValidateInput.validateSurName(snameField.getText())) {
                  String msg = String
                        .format("Invalid Format!!! SURNAME must only be one word");
                  JOptionPane.showMessageDialog(null, msg, "ERROR",
                        JOptionPane.ERROR_MESSAGE);
               } else {
                  mydetails.setSurname(snameField.getText());
               }
            }
         } catch (Exception e) {
            String msg = String
                  .format("Invalid input. Please make sure that you have filled every text fields!!! Please enter a correct one");
            JOptionPane.showMessageDialog(null, msg, "ERROR",
                  JOptionPane.ERROR_MESSAGE);
         }
      }
   }

   private static void createAndShowGui() {
      NewPatient gui = new NewPatient();
      gui.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
      gui.setVisible(true);
   }

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

class ValidateInput {
   public static boolean validateFirstName(String firstName) {
      return firstName.matches("[a-zA-Z]*");
   }

   public static boolean validateSurName(String surname) {
      return surname.matches("[A-zA-z]+(['-][a-zA-Z]+)*");
   }

   public static boolean validateInitial(String initial) {
      return initial.matches("[A-Z]*");
   }
}

class FullDetails {
   // !! These fields should not be static
   private static String firstName;
   private static String surname;

   public void setFirstName(String firstName) {
      this.firstName = firstName;
   }

   public String getFirstName() {
      return firstName;
   }

   public void setSurname(String surname) {
      this.surname = surname;
   }

   public String getSurname() {
      return surname;
   }

   public static String getSurnam() {
      return surname;
   }
}

//!! a bare bones class to allow your code to compile
class PatientPanel extends JPanel {
   public PatientPanel() {
      add(new JLabel("Patient Panel"));
      setBorder(BorderFactory.createTitledBorder("Patient Panel"));
   }
}
这段代码没有以任何方式被“修复”,仍然存在我上面提到的问题


编辑
一个小的示例程序,展示了我已经讨论过的一些事情

import java.awt.GridLayout;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.*;
import javax.swing.text.JTextComponent;

@SuppressWarnings("serial")
// I try to gear my GUI's towards creation of JPanels, not JFrames
// I then can put the panel into a JFrame or into something else if desired
public class SimpleGui extends JPanel {
   private JTextField firstNameField = new JTextField(10);
   private JTextField lastNameField = new JTextField(10);
   private JTextComponent[] textComponents = {firstNameField, lastNameField};
   private DefaultListModel<SimpleDetails> detailsListModel = new DefaultListModel<>();
   private JList<SimpleDetails> detailsList = new JList<>(detailsListModel);

   public SimpleGui() {
      JPanel dataEntryPanel = new JPanel();
      dataEntryPanel.add(new JLabel("First Name:"));
      dataEntryPanel.add(firstNameField);
      dataEntryPanel.add(Box.createHorizontalStrut(15)); // add space
      dataEntryPanel.add(new JLabel("Last Name:"));
      dataEntryPanel.add(lastNameField);

      JPanel buttonPanel = new JPanel(new GridLayout(1, 0, 5, 0));
      buttonPanel.add(new JButton(new ClearAction("Clear", KeyEvent.VK_C)));
      buttonPanel.add(new JButton(new SubmitAction("Submit", KeyEvent.VK_S)));
      buttonPanel.add(new JButton(new ExitAction("Exit", KeyEvent.VK_X)));

      JPanel detailsPanel = new JPanel();
      detailsList.setPrototypeCellValue(new SimpleDetails("AAAAAAAAAAAA", "BBBBBBBBBBBB"));
      detailsList.setVisibleRowCount(12);
      JScrollPane detailsScrollPane = new JScrollPane(detailsList);
      detailsScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
      detailsPanel.add(detailsScrollPane);

      setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
      add(detailsPanel);
      add(dataEntryPanel);
      add(buttonPanel);
   }

   public void clearTextFields() {
      for (JTextComponent jTextComponent : textComponents) {
         jTextComponent.setText("");
      }
   }

   private class SubmitAction extends AbstractAction {
      public SubmitAction(String name, int mnemonic) {
         super(name);
         putValue(MNEMONIC_KEY, mnemonic);
      }

      @Override
      public void actionPerformed(ActionEvent e) {
         String firstName = firstNameField.getText();
         String lastName = lastNameField.getText();

         // validate input here or after creating details object
         // if valid, then 

         // create your details object
         SimpleDetails simpleDetails = new SimpleDetails(firstName, lastName);

         if (Validate.test(simpleDetails)) {
            // and then DO something with it. 
            // Here I add it to a JList
            detailsListModel.addElement(simpleDetails);
         } else {
            // notify user that data is bad
            // consider clearing the GUI
            clearTextFields();
         }

      }
   }

   private class ClearAction extends AbstractAction {

      public ClearAction(String name, int mnemonic) {
         super(name);
         putValue(MNEMONIC_KEY, mnemonic);
      }

      @Override
      public void actionPerformed(ActionEvent e) {
         clearTextFields();
      }
   }

   private class ExitAction extends AbstractAction {
      public ExitAction(String name, int mnemonic) {
         super(name);
         putValue(MNEMONIC_KEY, mnemonic);
      }

      @Override
      public void actionPerformed(ActionEvent e) {
         // clean up an problems
         Window win = SwingUtilities.getWindowAncestor(SimpleGui.this);
         win.dispose();
      }
   }

   private static void createAndShowGui() {
      SimpleGui mainPanel = new SimpleGui();

      JFrame frame = new JFrame("SimpleGui");
      frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      // so that the program runs on the Swing event thread
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

class SimpleDetails {
   private String firstName;
   private String lastName;

   public SimpleDetails(String firstName, String lastName) {
      this.firstName = firstName;
      this.lastName = lastName;
   }

   public String getFirstName() {
      return firstName;
   }

   public void setFirstName(String firstName) {
      this.firstName = firstName;
   }

   public String getLastName() {
      return lastName;
   }

   public void setLastName(String lastName) {
      this.lastName = lastName;
   }

   @Override
   public String toString() {
      return lastName + ", " + firstName;
   }

}

class Validate {
   public static boolean test(SimpleDetails simpleDetails) {
      if (simpleDetails.getFirstName().trim().isEmpty()) {
         return false;
      }
      if (simpleDetails.getLastName().trim().isEmpty()) {
         return false;
      }

      // default, has passed all tests
      return true;
   }
}
导入java.awt.GridLayout;
导入java.awt.Window;
导入java.awt.event.ActionEvent;
导入java.awt.event.KeyEvent;
导入javax.swing.*;
导入javax.swing.text.JTextComponent;
@抑制警告(“串行”)
//我试图让我的GUI面向创建JPanel,而不是JFrames
//然后,如果需要,我可以将面板放入JFrame或其他东西中
公共类SimpleGui扩展了JPanel{
私有JTextField firstNameField=新JTextField(10);
私有JTextField lastNameField=新JTextField(10);
私有JTextComponent[]textComponents={firstNameField,lastNameField};
private DefaultListModel detailsListModel=新的DefaultListModel();
私有JList detailsList=新JList(detailsListModel);
公共SimpleGui(){
JPanel dataEntryPanel=newjpanel();
添加(新的JLabel(“名字:”);
dataEntryPanel.add(firstNameField);
dataEntryPanel.add(Box.createHorizontalStruct(15));//添加空间
添加(新的JLabel(“姓氏”);
添加(lastNameField);
JPanel buttonPanel=新的JPanel(新的网格布局(1,0,5,0));
add(newjbutton(newclearaction(“Clear”,KeyEvent.VK_C));
add(newjbutton(newsubmitAction(“Submit”,KeyEvent.VK_));
add(newjbutton(newexitAction(“Exit”,KeyEvent.VK_X));
JPanel detailsPanel=新的JPanel();
detailsList.setPrototypeCellValue(新的SimpleDetails(“aaaaaaaaaa”,“bbbbbbbbbb”);
detailsList.setVisibleRowCount(12);
JScrollPane detailsScrollPane=新的JScrollPane(detailsList);
detailsScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL\u SCROLLBAR\u ALWAYS);
detailsPanel.add(detailsScrollPane);
setLayout(新的BoxLayout(这是BoxLayout.PAGE_轴));
添加(详细信息spanel);
添加(dataEntryPanel);
添加(按钮面板);
}
public void clearTextFields(){
for(JTextComponent JTextComponent:textComponents){
jTextComponent.setText(“”);
}
}
私有类SubmitAction扩展了AbstractAction{
公共提交(字符串名称,int助记符){
超级(姓名);
putValue(助记符键,助记符);
}
@凌驾
已执行的公共无效操作(操作事件e){
String firstName=firstNameField.getText();
字符串lastName=lastNameField.getText();
//在此处或创建详细信息对象后验证输入
//如果有效,则
//创建您的详细信息对象
SimpleDetails SimpleDetails=新的SimpleDetails(名字,姓氏);
if(Validate.test(simpleDetails)){
//然后用它做点什么。
//在这里,我将其添加到JList
detailsModel.addElement(simpleDetails);
}否则{
//通知用户数据已损坏
/考虑清除GUI
clearTextFields();
}
}
}
私有类ClearAction扩展了AbstractAction{
公共ClearAction(字符串名,int助记符){
超级(姓名);
putValue(助记符键,助记符);
}
@凌驾
已执行的公共无效操作(操作事件e){
clearTextFields();
}
}
私有类ExitAction扩展了AbstractAction{
公共ExitAction(字符串名,int助记符){
超级(姓名);
putValue(助记符键,助记符);
}
@凌驾
已执行的公共无效操作(操作事件e){
//解决问题
Window win=SwingUtilities.getWindow祖先(SimpleGui.this);
win.dispose();
}
}
私有静态void createAndShowGui(){
SimpleGui主面板=新SimpleG