![](/img/trans.png)
[英]How to add new element under existing element in jlist using java swing?
[英]Add Item to an existing Java Swing jList (added to a JFrame using Netbeans UI)
我第一次在我的 UI 中使用 jList 元素。 所有 UI 都是使用 Netbeans UI 構建器設計的。
如果相關,我在 Java 8 下。
我正在嘗試將元素添加到列表中。
這是 JFrame 運行的屏幕截圖:
這是所需的操作:
按jButton1
后, jTextfield1
的內容將作為附加項添加到jList1
。
這是按鈕操作的摘錄,包括我嘗試失敗的兩件事:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String textToAddToList = this.jTextField1.getText();
//this.jList1.add(textToAddToList); <<-- this does not work as add method requires a second paramenter Component which I do not understand.
//this.jList1.setListData(String []) <<-- I have used this with a different list because I have the whole list at once, but I do not know how to add a single item with this method either.
}
這是我的完整可復制代碼:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author me
*/
public class JFrame1 extends javax.swing.JFrame {
/**
* Creates new form JFrame1
*/
public JFrame1() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
jList1 = new javax.swing.JList<>();
jButton1 = new javax.swing.JButton();
jTextField1 = new javax.swing.JTextField();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jList1.setModel(new javax.swing.AbstractListModel<String>() {
String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
public int getSize() { return strings.length; }
public String getElementAt(int i) { return strings[i]; }
});
jScrollPane1.setViewportView(jList1);
jButton1.setText("jButton1");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jTextField1.setText("jTextField1");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1)
.addGroup(layout.createSequentialGroup()
.addComponent(jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 313, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton1)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton1)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String textToAddToList = this.jTextField1.getText();
//this.jList1.add(textToAddToList);
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(JFrame1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(JFrame1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(JFrame1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(JFrame1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new JFrame1().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JList<String> jList1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextField jTextField1;
// End of variables declaration
}
這有效:
在你的類中定義一個模型:
private DefaultListModel jList1Model;
將模型分配給構造函數中的 jList 項:
jList1Model = new DefaultListModel();
jList1.setModel(jList1Model);
將項目添加到模型中,而不是添加到操作方法中的 jList(或您想要添加項目的任何位置):
jList1.addElement(textToAddToList);
您必須始終使用 DefaultListModel。
DefaultListModel listmodel = new DefaultListModel(); JList list = new JList(listmodel);
你不能用這樣的字符串數組初始化模型:
String items[] = String[]{"item 1", "item 2", "item 3"}; listmode.addAll(items);//錯誤
但是你必須用這樣的集合初始化
ArrayList items = new ArrayList(Arrays.asList("item 1", "item 2", "item 3"));
然后在 actionPerformed(....) 你可以添加這個
DefaultListModel defModel = (DefaultListModel)jList1.getModel(); defModel.addElement("新元素");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.