簡體   English   中英

在Java中將Integer添加到JList

[英]Add Integer to JList in java

我正在制作一個包含兩個組件的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。 您通常可以使用listModel.addElement(myInteger) )來創建JList<Integer>並將Integer(或裝箱的int)添加到JList的模型中。

如果您需要清除之前的元素,請添加元素之前而不是之后清除。 例如,

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