简体   繁体   中英

Add Integer to JList in java

Im making a jframe with two components. A list and a button. The list starts at 0 and everytime i press the button it increases by 1. So if i press the button, the value in the jlist changes from 0 to 1.

My question is, how can I add an integer to a jlist? (i tried the setText method just in case - only works for Strings)

Thanks EDIT: PART OF MY CODE (ActionListener)

            increase.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
                counter++;
                System.out.println(counter);
                listModel.addElement(counter);
//              listModel.clear();
            }
        });

I'm assuming that you want to add an int item to the JList, meaning a new int pops up in the list's display each time the button is pushed. You can create a JList<Integer> and add Integers (or boxed ints) to the JList's model, usually using listModel.addElement(myInteger) .

If you need to clear previous elements, do so before adding the element, not after . For example,

import java.awt.event.ActionEvent;

import javax.swing.*;

public class Foo2 extends JPanel {
   private DefaultListModel<Integer> dataModel = new DefaultListModel<>();
   private JList<Integer> intJList = new JList<>(dataModel);

   public Foo2() {
      add(new JScrollPane(intJList));
      intJList.setFocusable(false);
      add(new JButton(new AbstractAction("Add Int") {
         private int count = 0;

         @Override
         public void actionPerformed(ActionEvent e) {
            dataModel.clear();  // if you need to clear previous entries
            dataModel.addElement(count);
            count++;
         }
      }));
   }

   private static void createAndShowGui() {
      JFrame frame = new JFrame("Foo2");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(new Foo2());
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }

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

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