在java中向JList添加Integer



我正在制作一个包含两个组件的jframe。一个列表和一个按钮。列表从0开始,每次我按下按钮,它都会增加1。因此,如果我按下按钮,jlist中的值将从0变为1。

我的问题是,如何将整数添加到jlist?(我尝试了setText方法以防万一——只适用于字符串)

谢谢编辑:我的代码的一部分(ActionListener)

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

我假设您想向JList添加一个int项,这意味着每次按下按钮时,列表的显示中都会弹出一个新的int。您可以创建一个JList<Integer>,并将整数(或带框的整数)添加到JList的模型中,通常使用listModel.addElement(myInteger)

如果需要清除以前的元素,请在添加元素之前执行,而不是在之后执行。例如,

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();
         }
      });
   }  
}

最新更新