簡體   English   中英

從JComboBox中選擇一個名稱后,如何獲得積分顯示在程序上?

[英]How do I get points to show up on my program after selecting a name from my JComboBox?

我正在構建一個程序,該程序將在從JComboBox中選擇“獲得的總積分”旁邊的名稱后顯示積分,我不知道如何使用System.out.println(""); 但是我希望它顯示在程序內部的“獲得的總積分:”一詞旁邊的pointsEarned JTextField中,而不是在我的編譯器框中。

這是我的代碼:

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

public class UserHistory extends JPanel {
    private JLabel jcomp1;
    private JComboBox userList;
    private JLabel jcomp5;
    private JTextField pointsEarned;
    private JLabel jcomp7;
    private JList choresCompleted;

    public UserHistory() {        
        //construct preComponents
        ManageUsersGUI list = new ManageUsersGUI();
        String[] userListItems = new String[list.users.size()];
        String[] choresCompletedItems = {"Item 1", "Item 2", "Item 3"};

        //construct components
        jcomp1 = new JLabel ("User History");
        userList = new JComboBox(userListItems);

        userList.addPopupMenuListener(new PopupMenuListener() {
            @Override
            public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
                userList.removeAllItems();
                for (User user: list.users) {
                    userList.addItem(user.getUserName());
                }   
            }

            @Override
            public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
            }

            @Override
            public void popupMenuCanceled(PopupMenuEvent e) {
            }
        });

        jcomp5 = new JLabel ("Total points earned: ");
        pointsEarned = new JTextField ();
        userList.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
               myBox(e);
            }
        });     


        jcomp7 = new JLabel ("List of chores completed: ");
        choresCompleted = new JList (choresCompletedItems);

        //set components properties
        userList.setToolTipText ("Select a user");

        //adjust size and set layout
        setPreferredSize (new Dimension (465, 343));
        setLayout (null);

        //add components
        add (jcomp1);
        add (userList);
        add (jcomp5);
        add (pointsEarned);
        add (jcomp7);
        add (choresCompleted);

        //set component bounds (only needed by Absolute Positioning)
        jcomp1.setBounds (120, 20, 70, 25);
        userList.setBounds (210, 20, 100, 25);
        jcomp5.setBounds (125, 105, 140, 25);
        pointsEarned.setBounds (245, 105, 100, 25);
        jcomp7.setBounds (95, 140, 160, 25);
        choresCompleted.setBounds (245, 145, 100, 75);
    }

    protected void myBox(ActionEvent e) {
        if(userList.getSelectedItem() != null) {
            //System.out.println(User.getPoints());
        }
    }        

    public static void main (String[] args) {
        JFrame frame = new JFrame ("UserHistory");
        frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add (new UserHistory());
        frame.pack();
        frame.setVisible (true);

        ManageUsersGUI.manageUsers();
    }
}

這是我的User類:

public class User {
   private String userName;
   private int points = 0;

   public User(String userName) {
      this.userName = userName;
   }

   public User() {
      userName = "";
   }   

   public void setUserName(String userName) {
      this.userName = userName;   
   }

   public String getUserName() {
      return userName;
   }

   public void addPoints(int chorePoints) {
      points += chorePoints;
   }

   public int getPoints() {
      return points;
   }

   public String toString() {
      return userName + "\n";
   }

} 

這是我的ManageUsersGUI類:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import javax.swing.JCheckBox;

public class ManageUsersGUI extends JPanel {
   public static ArrayList<User> users = new ArrayList<>();

   private final JLabel addNewUserLabel;
   private final JTextField addNewUserTextField;
   private final JLabel deleteUsersLabel;
   private final JButton addButton;
   private final JButton deleteButton;
   private final JPanel namePanel;

    /**
     *
     */
    public ManageUsersGUI() {
       //construct components
       addNewUserLabel = new JLabel ("Add new User here:");
       addNewUserTextField = new JTextField (0);
       deleteUsersLabel = new JLabel ("Select which User(s) you would like to delete:");
       addButton = new JButton ("Add");
       deleteButton = new JButton ("Delete");
       namePanel = new JPanel();
       namePanel.setLayout(new BoxLayout(namePanel, BoxLayout.Y_AXIS));

       //set components properties
       addNewUserTextField.setToolTipText ("Enter name and click on Add button.");
       addButton.setToolTipText ("Click here to Add new user.");
       deleteButton.setToolTipText ("Click here to delete User(s) selected.");

       //adjust size and set layout
       setPreferredSize (new Dimension (580, 485));
       setLayout (null);

       //add components
       add (addNewUserLabel);
       add (addNewUserTextField);
       add (deleteUsersLabel);
       add (namePanel);
       add (addButton);
       add (deleteButton);

       //set component bounds (only needed by Absolute Positioning)
       addNewUserLabel.setBounds (85, 130, 120, 25);
       addNewUserTextField.setBounds (235, 130, 125, 25);
       deleteUsersLabel.setBounds (135, 225, 281, 25);
       addButton.setBounds (385, 130, 100, 25);
       namePanel.setBounds(225, 270, 140, 0);
       deleteButton.setBounds (230, 335, 100, 25);

       addButton.addActionListener(new AddButtonListener());

       deleteButton.addActionListener(new DeleteButtonListener());
   }

    /**
     *
     * @return
     */
    public ArrayList<User> getUser() {
              return users;
           }        

   private class AddButtonListener implements ActionListener {
       @Override
       public void actionPerformed(ActionEvent e) {
           String text = addNewUserTextField.getText();
           users.add(new User(text));

           // Display the changes.
           JOptionPane.showMessageDialog(null, text + " has been added.");

           JCheckBox nameCheckBox = new JCheckBox();
           nameCheckBox.setText(addNewUserTextField.getText());
           namePanel.add(nameCheckBox);
           namePanel.setBounds(225, 270, 140, namePanel.getHeight() + 25);
           deleteButton.setBounds(230, deleteButton.getY() + 25, 100, 25);
           JFrame frame = (JFrame) getRootPane().getParent();
           frame.setSize(frame.getWidth(), frame.getHeight() + 25);
           frame.pack(); 

       }
   }

   private class DeleteButtonListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
           for(Component component : namePanel.getComponents()) {
              if(component instanceof JCheckBox) {
                 if(((JCheckBox)component).isSelected())
                    namePanel.remove(component);
              }
           }
           namePanel.revalidate();
           namePanel.repaint();
        }   
   }


   public static void main (String[] args) {
       JFrame frame = new JFrame ("AddUsersPanel");
       frame.setTitle("Manage Users");
       frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
       frame.getContentPane().add (new ManageUsersGUI());
       frame.pack();
       frame.setVisible (true);
   }

   // in ManageUsersGUI
   public static void manageUsers() {
       JFrame frame = new JFrame ("AddUsersPanel1");
       frame.setTitle("Manage Users");
       frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
       frame.getContentPane().add (new ManageUsersGUI());
       frame.pack();
       frame.setVisible (true);
   }
}   

您似乎有一個JTextFieldpointsEarned ,這似乎是您要用來打印值的東西。

如果你看看在JavaDoc中JTextField ,你會發現一個setText方法,它需要一個String

因此,問題實際上變成了“如何將int轉換為String ?”。 好吧,有很多方法...

  • Integer.toString
  • String.valueOf
  • NumberFormat.getNumberInstance
  • "" + intValue

您將使用哪種取決於您要實現的目標。

protected void myBox(ActionEvent e) {
    Object obj = userList.getSelectedItem();
    if(obj != null) {
        if (obj instanceof User) {
            User user = (User)obj;
            pointsEarned.setText(NumberFormat.getNumberInstance().format(user.getPoints())
        }
    }
}      

更新

因此,在花了一些時間使用代碼之后,似乎已經出現了許多問題。

一,對static的依賴

public class ManageUsersGUI extends JPanel {
    public static ArrayList<User> users = new ArrayList<>();

static不是跨對象通信機制,該信息應在需要時傳遞給ManageUsersGUI的實例,或者應生成並返回列表,具體取決於您要實現的目標。

其次,僅用用戶名填充JComboBox即可,並且可以通過多種方法對其進行管理,只是直接將User對象添加到其中,這很簡單,然后解決了發生的問題當兩個具有相同名稱的用戶添加到列表中時

for (User user: list.users) {
    userList.addItem(user);
}   

您還應該使泛型用戶定義您的異常...

private JComboBox<User> userList;

這意味着addItem將僅接受User實例,而getSelectedItem將返回User而不是Object

只要JComboBox發生更改,它就應該從List填充,而不是在彈出窗口可見時填充,您會發現用戶體驗會好得多。

您還應該利用模式對話框,從用戶那里收集少量信息,從長遠來看,這將使您的代碼更易於管理。

看一下:

更多細節

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM