简体   繁体   English

在Java中将Integer添加到JList

[英]Add Integer to JList in java

Im making a jframe with two components. 我正在制作一个包含两个组件的jframe。 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. 该列表从0开始,每按一次该按钮便增加1。因此,如果按此按钮,则jlist中的值将从0变为1。

My question is, how can I add an integer to a jlist? 我的问题是,如何将整数添加到jlist? (i tried the setText method just in case - only works for Strings) (我尝试了setText方法,以防万一-仅适用于字符串)

Thanks EDIT: PART OF MY CODE (ActionListener) 谢谢编辑:我的代码的一部分(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. 我假设您要向JList添加一个int项,这意味着每次按下按钮时,列表的显示中都会弹出一个新的int。 You can create a JList<Integer> and add Integers (or boxed ints) to the JList's model, usually using listModel.addElement(myInteger) . 您通常可以使用listModel.addElement(myInteger) )来创建JList<Integer>并将Integer(或装箱的int)添加到JList的模型中。

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

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

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