简体   繁体   中英

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. 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. I know where the problem is occurring and you'll immediately see it in the actionevent lines. 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

    {

       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 . Instead re-use the original JList newbie and add the new Human to its model. Use a DefaultListModel which is mutable.

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 . 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.

To simplify you generate a new Model which contains the last added Human and use it as new model for your list.

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.

You will find more details in the Java Tutorials : http://docs.oracle.com/javase/tutorial/uiswing/components/list.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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