简体   繁体   English

Java:无法将项目从本地JList添加到JList

[英]Java: Having trouble adding items to a JList from local JList

I'm having a problem here where I've created an actionListener which is intended to create a random human and add it to JList to be displayed on JScrollPane. 我在这里遇到一个问题,我在其中创建了一个actionListener,该监听器旨在创建一个随机的人类并将其添加到要显示在JScrollPane上的JList中。 Everything has worked out good so far except that whenever I click the JButton to add a new human, the JList does not add to the current list, instead it replaces it each time again and so only one item is ever displayed on the Jlist. 到目前为止,一切工作都很好,除了每当我单击JButton添加新人员时,JList都不会添加到当前列表,而是每次都替换它,因此Jlist上只显示一项。 I know where the problem is occurring and you'll immediately see it in the actionevent lines. 我知道问题出在哪里,您将在actionevent行中立即看到它。 Anyways, thanks for any help my friends! 无论如何,感谢我的朋友们的帮助!

private static final JTextArea PlayerList = new JTextArea(30, 100);
private JList newbie;
private List<Human> members = new ArrayList<Human>();
private JTextArea Area;
private String[] listString;
private String[] newString;
private ArrayList<String> list = new ArrayList<String>();
private ArrayList<String> zz = new ArrayList<String>();


public JTabbedPaneFrame() throws FileNotFoundException 
{
    super("JTabbedPane Demo");


    JTabbedPane tabbedPane = new JTabbedPane(); 

    JPanel Gladiator = new JPanel();
    getContentPane().add(Gladiator); 

    /////////////Tabbed Pane Gladiator///////////////////

    tabbedPane.addTab("Gladiator", null, Gladiator, "");




    Box ListOfPlayers = Box.createVerticalBox();
    ListOfPlayers.add(Box.createRigidArea(new Dimension(100,100)));
    ListOfPlayers.setBorder(new TitledBorder("List of Players"));

    Area = new JTextArea(20, 15);
    Area.setLineWrap(true);
    Area.setWrapStyleWord(false);

    final JList newbie = new JList();

    JScrollPane PlayerViewer = new JScrollPane(newbie);
    PlayerViewer.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    ListOfPlayers.add(PlayerViewer);


    Gladiator.add(ListOfPlayers);
    /////////////Vertical Box between Text and Tabbed Profile//////

    Box Randomer = Box.createVerticalBox();
    Randomer.setBorder(new TitledBorder("Randomize or Add Gladiator"));
    JButton AddIndividual = new JButton("Add a Player");
    Randomer.add(AddIndividual); 

    Gladiator.add(Randomer);



    AddIndividual.addActionListener(new ActionListener()
    {

        public void actionPerformed(ActionEvent event)
        {


                String x = "";
                String y = "";
                String z = "";
                String ee = "";
                ArrayList<String> listx = new ArrayList<String>();
                ArrayList<String> zzx = new ArrayList<String>();
                JList newbiex;
                Human temp;
                try {


                    temp = new Human();
                    x = temp.toString();
                    y = temp.getSurname();
                    z = temp.getFirstName();
                    listx.add(x);
                    ee = String.format(y + ", " + z );
                    zzx.add(ee);
                    listString = new String[zzx.size()];
                    listString = zzx.toArray(listString);

                    newbiex = new JList(zzx.toArray());
                    newbie.setModel(newbiex.getModel());

                    members.add(temp);


                    for(String W: listString) /////testing diff method here////
                    {
                          Area.append(W);
                    }

                    } 
                catch (FileNotFoundException e) 
                    {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    }




        }


    });





    add(tabbedPane); 



    /////////////Action Buttons////////////////////



}

}       

class HumanRenderer extends DefaultListCellRenderer HumanRenderer类扩展DefaultListCellRenderer

    {

       public Component getListCellRendererComponent(JList list, Object value,
          int index, boolean isSelected, boolean cellHasFocus) {

          JLabel label = new JLabel(); 
          if (value != null) {
             Human human = (Human) value;
             label.setText(human.getSurname() + ", " + human.getFirstName());
          }

          return label;
       }
    }

You are creating a new JList newbiex in your ActionListener which you never add to the JFrame . 您将在ActionListener中创建一个新的JList newbiex ,而从未添加到JFrame Instead re-use the original JList newbie and add the new Human to its model. 而是重新使用原始的JList newbie ,并将新的Human添加到其模型中。 Use a DefaultListModel which is mutable. 使用一个可变的DefaultListModel

DefaultListModel<Human> model = new DefaultListModel<>();
JList<Human> newbie = new JList<>(model);

You will need a custom cell renderer to display the Human objects in the JList . 您将需要一个自定义单元格渲染器,以在JList显示Human对象。 See Writing a Custom Cell Renderer 请参阅编写自定义单元格渲染器


class HumanRenderer extends DefaultListRenderer {
   @Override
   public Component getListCellRendererComponent(JList list, Object value,
      int index, boolean isSelected, boolean cellHasFocus) {

      JLabel label = new JLabel(); 
      if (value != null) {
         Human human = (Human) value;
         label.setText(human.getSurName() + ", " + human.getFirstName());
      }

      return label;
   }
}

You do a lot of strange things here. 您在这里做了很多奇怪的事情。

It seems that you create a JList each time you click, add a Human in it and set your initial model's list to the newly created list's model. 似乎您每次单击都创建一个JList,在其中添加一个Human,并将初始模型的列表设置为新创建的列表的模型。

To simplify you generate a new Model which contains the last added Human and use it as new model for your list. 为简化起见,您将生成一个包含最后添加的Human的新模型,并将其用作列表的新模型。

The only thing to do is to add your new Human to the EXISTING model, so you have to keep a reference to this model. 唯一要做的就是将新的Human添加到EXISTING模型中,因此您必须保留对该模型的引用。

You will find more details in the Java Tutorials : http://docs.oracle.com/javase/tutorial/uiswing/components/list.html 您可以在Java教程中找到更多详细信息: http : //docs.oracle.com/javase/tutorial/uiswing/components/list.html

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

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