简体   繁体   English

JTextField 的 setText 方法不更新 JTextField 实例

[英]JTextField's setText method does not update the JTextField instances

The below is part of code of a multi file project.以下是多文件项目的部分代码。 I am posting only this code since I am unclear why setText method is not working.我只发布此代码,因为我不清楚为什么 setText 方法不起作用。 Not all code for this project is included.并非包含此项目的所有代码。

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

        @SuppressWarnings("serial")

        public class Controller extends JFrame implements ActionListener,ListSelectionListener 
        {

            private JButton addButton;
            private JButton deleteButton;
            private JButton viewDetailsButton;
            private JPanel btnsPnl = new JPanel();
            private JPanel mainPnl = new JPanel();
            private JPanel dataPnl = new JPanel();
            private JPanel listPnl = new JPanel();
            private JLabel loanIdLabel = new JLabel("LoanId");
            private JLabel loanName = new JLabel("Loan Name");
            private JLabel loanLender = new JLabel("Lender");
            private JLabel loanAmount = new JLabel("Loan Amount");
            private JTextField loanIdFld = new JTextField(15);
            private JTextField loanNameFld = new JTextField(15);
            private JTextField lenderFld = new JTextField(15);
            private JTextField loanamountFld = new JTextField(15);
            private DefaultListModel dlm = new DefaultListModel();
            private JList jlst=new JList(dlm);

            private loansModel model;
            private loansView loansView;

            private int selectedListIndex;
            private ListSelectionModel listSelectionModel;


        public loansController(loansModel mo)
        {
           addButton = new JButton("Add Loan");
           deleteButton = new JButton("Delete Loan");
           viewDetailsButton = new JButton("View Details of all Loans");
           model = mo;
           loansView = new loansView(mo);   
        }

        /* Builds GUI for the controller component of the
         *  Model-View-Controller implementation
         */
        public void buildGUI()
        {
            GridBagLayout gbl = new GridBagLayout();
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridx=0;
            gbc.gridy=0;
            dataPnl.setLayout(new GridLayout(4,2));
            dataPnl.add(loanIdLabel);
            dataPnl.add(loanIdFld);
            dataPnl.add(loanName);
            dataPnl.add(lenderFld);
            dataPnl.add(authorLabel);
            dataPnl.add(authorFld);
            dataPnl.add(priceLabel);
            dataPnl.add(loanamountFld); 
            gbl.setConstraints(dataPnl, gbc);
            mainPnl.add(dataPnl);    
            Dimension listDim = new Dimension(50,90);
            jlst.setPreferredSize(listDim);
            gbc.gridx = 0;
            gbc.gridy = 1;
            gbl.setConstraints(listPnl,gbc);
            listPnl.add(jlst);
            listSelectionModel= jlst.getSelectionModel();
            listSelectionModel.addListSelectionListener(new loansController(model));
            gbc.gridx=1;
            gbc.gridy=1;
            gbc.gridwidth=2;
            gbl.setConstraints(btnsPnl,gbc);    
            addButton.addActionListener(this);
            deleteButton.addActionListener(this);
            viewDetailsButton.addActionListener(this);
            btnsPnl.add(addButton);
            btnsPnl.add(deleteButton);
            btnsPnl.add(viewDetailsButton);
            mainPnl.add(listPnl);
            mainPnl.add(btnsPnl);
            getContentPane().add(mainPnl);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setSize(800,400);
            setVisible(true);
        }

        /* Handles events coming from add,delete, and view Details 
         * buttons */
        public void actionPerformed(ActionEvent ae)
        {

            if (ae.getSource()==addButton)
            {
                String bId = loanIdFld.getText();
                String titFld = lenderFld.getText();
                String authFld = authorFld.getText();
                String priFld = loanamountFld.getText();
                boolean isAnumber;
                isAnumber = isNumeric(priFld);

                if (!isAnumber)
                {
                    JOptionPane.showMessageDialog(null, 
                        "Enter the correct loan amount",
                        "Error: Price entry",
                         JOptionPane.INFORMATION_MESSAGE);
                    priFld = loanamountFld.getText();
                    isAnumber = isNumeric(priFld);

                }

                else
                {           
                    Loan loanItem;
                    loanItem = new Loan(bId, titFld,
                    authFld,Double.parseDouble(priFld));
                    model.addLoan(loanItem);
                    dlm.addElement(bId);
                    setClearTextFld();
                }
            }

            else if (ae.getSource()== deleteButton)
            {
                model.deleteLoan(model.getSelectedListIndex());
                dlm.removeElementAt(model.getSelectedListIndex());
                setClearTextFld();
            } 

            else if (ae.getSource()==viewDetailsButton)
            {   
                loansView.buildGUI();

            }

        }




         /* This method clears the text field after the action Performed
          * method for the add and delete Buttons
          */
          public void setClearTextFld()
          {
               loanIdFld.setText("");
               lenderFld.setText("");
               authorFld.setText("");
               loanamountFld.setText("");
          }





          /* This value changed method gets the selected item in the JList
           * for performing the  
           */
          public void valueChanged(ListSelectionEvent e) 
          {

            listSelectionModel = (ListSelectionModel)e.getSource();

            int maxselectedListIndex = listSelectionModel.getMaxSelectionIndex();
            int minselectedListIndex = listSelectionModel.getMinSelectionIndex();

            System.out.println(selectedListIndex);  

            if (!listSelectionModel.isSelectionEmpty())
            {   
            for (int i = minselectedListIndex; i <= maxselectedListIndex; i++) {
                if (listSelectionModel.isSelectedIndex(i)) 
                {  
                   selectedListIndex=i;
                   System.out.println("inside valueChanged. selectedListIndex");
                   System.out.println(selectedListIndex);
                   model.setSelectedListIndex(i);
                   Loan selectedLoan = model.getLoan(i);
                   System.out.println(selectedLoan.getTitle().toString());
                   System.out.println(selectedLoan.getId());
                   System.out.println(selectedLoan.getAuthor());
                   System.out.println(selectedLoan.getTitle());
                   System.out.println((selectedLoan.getPrice()));   
        //             lenderFld.setText(selectedLoan.getTitle().toString());
          //           authorFld.setText(selectedLoan.getAuthor().toString());
            //     loanamountFld.setText(Double.toString(selectedLoan.getPrice()));


               loanIdFld.setText("1234");
               lenderFld.setText("Test LoaN NAME");
               authorFld.setText("Test lender");
               loanamountFld.setText("Test loan amount");


                }
            }
            }

          }

          }

What I want is when someone clicks on the GridBagLayout's loanid instances, details about the loan are displayed.我想要的是当有人点击 GridBagLayout 的 loanid 实例时,会显示有关贷款的详细信息。 I can see that valueChanged() is called as "inside valueChanged. selectedListIndex" is printed but loanIdFld.setText("1234") does not update the LoadId text field with 1234. 1234 is a random number I inserted to determine if something can be displayed but that also is not shown.我可以看到 valueChanged() 被称为“inside valueChanged.selectedListIndex”被打印但loanIdFld.setText(“1234”)没有用1234更新LoadId文本字段。1234是我插入的随机数以确定是否可以显示,但也没有显示。 Some functions are not defined here, but there is no syntax error.有些函数在这里没有定义,但是没有语法错误。

My guess: The loansController object that has the methods above called, that you set the text of its JTextFields, is not the same loansController object that is visualized by the user.我的猜测:具有上述方法的loansController object,您设置其JTextFields的文本,与用户可视化的loansController object不同。

But without more information, this is just a guess.但没有更多信息,这只是一个猜测。

Edit 1编辑 1
Here is evidence that I may be right:这里有证据证明我可能是对的:

listSelectionModel.addListSelectionListener(new loansController(model));

You are creating a new loansController object as the listener rather than using this :您正在创建一个的 loanController object 作为侦听器,而不是使用

listSelectionModel.addListSelectionListener(this);

Edit 2编辑 2
And now with the almost-SSCCE code below (too long to be a true SSCCE, but short enough), I have proven that my guess is in fact correct, that you are setting the text of the wrong object, of one that is not visualized.现在使用下面几乎是 SSCCE 的代码(太长而不能成为真正的 SSCCE,但足够短),我已经证明我的猜测实际上是正确的,您正在设置错误的 object 的文本,而不是可视化。 If you find the commented lines, comment out one line and uncomment the other to see the alteration in behavior:如果您找到注释行,请注释掉一行并取消注释另一行以查看行为变化:

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

@SuppressWarnings("serial")
public class loansController extends JFrame implements ActionListener,
         ListSelectionListener {
   private JButton addButton;
   private JButton deleteButton;
   private JButton viewDetailsButton;
   private JPanel btnsPnl = new JPanel();
   private JPanel mainPnl = new JPanel();
   private JPanel dataPnl = new JPanel();
   private JPanel listPnl = new JPanel();
   private JLabel loanIdLabel = new JLabel("LoanId");
   private JLabel loanName = new JLabel("Loan Name");
   private JTextField loanIdFld = new JTextField(15);
   private JTextField lenderFld = new JTextField(15);
   private JTextField loanamountFld = new JTextField(15);
   private DefaultListModel dlm = new DefaultListModel();
   private JList jlst = new JList(dlm);
   private int selectedListIndex;
   private ListSelectionModel listSelectionModel;

   public loansController() {
      addButton = new JButton("Add Loan");
      deleteButton = new JButton("Delete Loan");
      viewDetailsButton = new JButton("View Details of all Loans");
   }

   public void buildGUI() {
      String[] data = {"one", "two", "three", "four"};
      for (String datum : data) {
         dlm.addElement(datum);
      }
      GridBagLayout gbl = new GridBagLayout();
      GridBagConstraints gbc = new GridBagConstraints();
      gbc.gridx = 0;
      gbc.gridy = 0;
      dataPnl.setLayout(new GridLayout(4, 2));
      dataPnl.add(loanIdLabel);
      dataPnl.add(loanIdFld);
      dataPnl.add(loanName);
      dataPnl.add(lenderFld);
      dataPnl.add(loanamountFld);
      gbl.setConstraints(dataPnl, gbc);
      mainPnl.add(dataPnl);
      Dimension listDim = new Dimension(50, 90);
      jlst.setPreferredSize(listDim);
      gbc.gridx = 0;
      gbc.gridy = 1;
      gbl.setConstraints(listPnl, gbc);
      listPnl.add(jlst);
      listSelectionModel = jlst.getSelectionModel();


      // ****** here, comment one line and uncomment the other
      listSelectionModel.addListSelectionListener(new loansController());
      // !! listSelectionModel.addListSelectionListener(this);


      gbc.gridx = 1;
      gbc.gridy = 1;
      gbc.gridwidth = 2;
      gbl.setConstraints(btnsPnl, gbc);
      addButton.addActionListener(this);
      deleteButton.addActionListener(this);
      viewDetailsButton.addActionListener(this);
      btnsPnl.add(addButton);
      btnsPnl.add(deleteButton);
      btnsPnl.add(viewDetailsButton);
      mainPnl.add(listPnl);
      mainPnl.add(btnsPnl);
      getContentPane().add(mainPnl);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setSize(800, 400);
      setVisible(true);
   }

   public void actionPerformed(ActionEvent ae) {
      if (ae.getSource() == addButton) {
      } else if (ae.getSource() == deleteButton) {
      } else if (ae.getSource() == viewDetailsButton) {
      }
   }

   /*
    * This method clears the text field after the action Performed method for
    * the add and delete Buttons
    */
   public void setClearTextFld() {
      loanIdFld.setText("");
      lenderFld.setText("");
      loanamountFld.setText("");
   }

   public void valueChanged(ListSelectionEvent e) {
      listSelectionModel = (ListSelectionModel) e.getSource();
      int maxselectedListIndex = listSelectionModel.getMaxSelectionIndex();
      int minselectedListIndex = listSelectionModel.getMinSelectionIndex();
      System.out.println(selectedListIndex);
      if (!listSelectionModel.isSelectionEmpty()) {
         for (int i = minselectedListIndex; i <= maxselectedListIndex; i++) {
            if (listSelectionModel.isSelectedIndex(i)) {
               selectedListIndex = i;
               System.out.println("inside valueChanged. selectedListIndex");
               System.out.println(selectedListIndex);
               loanIdFld.setText("1234");
               lenderFld.setText("Test LoaN NAME");
               loanamountFld.setText("Test loan amount");
            }
         }
      }
   }

   public static void main(String[] args) {
      loansController controller = new loansController();
      controller.buildGUI();
   }
}

Note that this is what you should be doing: simplifying your code until you isolate the problem as it allows you to solve it much more easily, and failing that, then if you post this compilable runnable code, it lets us help you solve it more easily.请注意,这是您应该做的:简化您的代码,直到您隔离问题,因为它可以让您更轻松地解决它,如果失败了,那么如果您发布这个可编译的可运行代码,它可以让我们帮助您解决更多问题容易地。 This process is called creating an SSCCE or Short, Self Contained, Correct (Compilable), Example此过程称为创建 SSCCE 或简短、自包含、正确(可编译)、示例

Edit 3编辑 3
A better SSCCE:更好的SSCCE:

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

@SuppressWarnings("serial")
public class loansController extends JFrame implements ListSelectionListener {
   private JPanel mainPnl = new JPanel();
   private JPanel dataPnl = new JPanel();
   private JPanel listPnl = new JPanel();
   private JTextField loanIdFld = new JTextField(15);
   private JTextField lenderFld = new JTextField(15);
   private JTextField loanamountFld = new JTextField(15);
   private DefaultListModel dlm = new DefaultListModel();
   private JList jlst = new JList(dlm);
   private ListSelectionModel listSelectionModel;

   public void buildGUI() {
      String[] data = {"one", "two", "three", "four"};
      for (String datum : data) {
         dlm.addElement(datum);
      }
      dataPnl.setLayout(new GridLayout(4, 2));
      dataPnl.add(loanIdFld);
      dataPnl.add(lenderFld);
      dataPnl.add(loanamountFld);
      mainPnl.add(dataPnl);
      Dimension listDim = new Dimension(50, 90);
      jlst.setPreferredSize(listDim);
      listPnl.add(new JScrollPane(jlst));
      listSelectionModel = jlst.getSelectionModel();

      // ****** here, comment one line and uncomment the other
      // !! listSelectionModel.addListSelectionListener(new loansController());
      listSelectionModel.addListSelectionListener(this);

      mainPnl.add(listPnl);
      getContentPane().add(mainPnl);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      pack();
      setLocationRelativeTo(null);
      setVisible(true);
   }

   public void valueChanged(ListSelectionEvent e) {
      System.out.println("inside valueChanged. ");
      loanIdFld.setText("1234");
      lenderFld.setText("Test LoaN NAME");
      loanamountFld.setText("Test loan amount");
   }

   public static void main(String[] args) {
      new loansController().buildGUI();
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM