java - 按钮 ActionPerfomed 将字符串从 JList 移动到 JList

标签 java swing compiler-errors jlist cannot-find-symbol

我正在对一个我想参加的项目进行评估。对于如何解释、理解或正确使用该项目提供的位于教程点的“教程”,我仍然有些困惑。

使用 Netbeans 8.1 创建的 Jlist --> JFrame Form GUI Builder

public class Window extends javax.swing.JFrame {

/**
 * Creates new form for BootcampAssessmentGui
 */
public Window() {
    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() {

    controlsbuttonGroup = new javax.swing.ButtonGroup();
    partsScrollPane = new javax.swing.JScrollPane();
    partsList = new javax.swing.JList<>();
    buildScrollPane = new javax.swing.JScrollPane();
    buildList = new javax.swing.JList<>();
    addButton = new javax.swing.JButton();
    removeButton = new javax.swing.JButton();
    jMenuBar1 = new javax.swing.JMenuBar();
    fileMenu = new javax.swing.JMenu();
    loadMenuItem = new javax.swing.JMenuItem();
    saveMenuItem = new javax.swing.JMenuItem();
    exitMenuItem = new javax.swing.JMenuItem();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    setTitle("Devereaux Assessment");

    partsList.setModel(new javax.swing.AbstractListModel<String>() {
        String[] strings = { "Case", "Motherboard", "CPU", "RAM", "GPU", "HDD", "PSU" };
        public int getSize() { return strings.length; }
        public String getElementAt(int i) { return strings[i]; }
    });
    partsScrollPane.setViewportView(partsList);

    buildScrollPane.setViewportView(buildList);

    addButton.setText(">>");
    addButton.setToolTipText("Add Parts to Build list");
    controlsbuttonGroup.add(addButton);
    addButton.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            addButtonActionPerformed(evt);
        }
    });

    removeButton.setText("<<");
    removeButton.setToolTipText("Remove Parts from Build list");
    controlsbuttonGroup.add(removeButton);
    removeButton.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            removeButtonActionPerformed(evt);
        }
    });

    fileMenu.setText("File");

    loadMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_L, java.awt.event.InputEvent.CTRL_MASK));
    loadMenuItem.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/cooksys/assessment/arrow95.png"))); // NOI18N
    loadMenuItem.setText("Load");
    fileMenu.add(loadMenuItem);

    saveMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.CTRL_MASK));
    saveMenuItem.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/cooksys/assessment/floppy13.png"))); // NOI18N
    saveMenuItem.setText("Save");
    fileMenu.add(saveMenuItem);

    exitMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_X, java.awt.event.InputEvent.CTRL_MASK));
    exitMenuItem.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/cooksys/assessment/exit18.png"))); // NOI18N
    exitMenuItem.setText("Exit");
    exitMenuItem.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            exitMenuItemActionPerformed(evt);
        }
    });
    fileMenu.add(exitMenuItem);

    jMenuBar1.add(fileMenu);

    setJMenuBar(jMenuBar1);

    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()
            .addComponent(partsScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 209, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 31, Short.MAX_VALUE)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(addButton)
                .addComponent(removeButton))
            .addGap(28, 28, 28)
            .addComponent(buildScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 209, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap())
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addComponent(buildScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 279, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(partsScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 279, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGroup(layout.createSequentialGroup()
                    .addGap(125, 125, 125)
                    .addComponent(addButton)
                    .addGap(18, 18, 18)
                    .addComponent(removeButton)))
            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    );

    pack();
}// </editor-fold>                        

private void exitMenuItemActionPerformed(java.awt.event.ActionEvent evt) {                                             
    System.exit(0);
}                                            

private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {                                          
    // add Parts to buildList
  for (Object selectedValue : partsList.getSelectedValuesList()) {
      buildList.addElement(selectedValue);
      partsList.removeElement(selectedValue);
      int  iSelected = partsList.getSelectedIndex();
      if (iSelected == -1) {
          return;
      }
    }
}                                         

private void removeButtonActionPerformed(java.awt.event.ActionEvent evt) {                                             
    // remove Parts from buildList
    for (Object selectedValue : buildList.getSelectedValuesList()) {
      partsList.addElement(selectedValue);
      buildList.removeElement(selectedValue);
      int  iSelected = buildList.getSelectedIndex();
      if (iSelected == -1) {
          return;
      }
    }
}                                            

/**
 * @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(Window.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(Window.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(Window.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(Window.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>
    //</editor-fold>

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new Window().setVisible(true);
        }
    });
}

// Variables declaration - do not modify                     
private javax.swing.JButton addButton;
private javax.swing.JList<String> buildList;
private javax.swing.JScrollPane buildScrollPane;
private javax.swing.ButtonGroup controlsbuttonGroup;
private javax.swing.JMenuItem exitMenuItem;
private javax.swing.JMenu fileMenu;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JMenuItem loadMenuItem;
private javax.swing.JList<String> partsList;
private javax.swing.JScrollPane partsScrollPane;
private javax.swing.JButton removeButton;
private javax.swing.JMenuItem saveMenuItem;
// End of variables declaration                   
}

我收到错误找不到符号 - 符号:方法addElement(Object) 位置:Jlist的变量partsList类型

这个错误对我来说非常简单。我的问题是我见过的大多数示例都使用 DefaultListModel。 NetBeans 正在使用 AbstractListModel 方法。

我已查看以下引用资料:

http://www.java2s.com/Code/Java/Swing-JFC/DualJListwithbuttonsinbetween.htm http://docs.oracle.com/javase/tutorial/uiswing/components/list.html#scrollingapi

但老实说,我觉得我没有正确理解如何使用这些源进行调试。我觉得我没有正确使用基于这段代码的对象 --> 字符串:

 private void clearDestinationSelected() {
Object selected[] = destList.getSelectedValues();
for (int i = selected.length - 1; i >= 0; --i) {
  destListModel.removeElement(selected[i]);
}
destList.getSelectionModel().clearSelection();

}

我将通过注释将此帮助请求包含在代码中。我不是骗子。这几天我一直在观察、工作、搜索和思考这个问题。在这一点上,我觉得寻求帮助是明智的。

最佳答案

API 会在这里为您提供一些帮助,因为如果您查看 JList API,您会发现您的编译器是正确的,JList 没有 addElement(...) 方法,但不要灰心 - DefaultListModel 类确实有这个方法,您可以通过调用 getModel() 从 JList 中提取该方法,然后调用 addElement(...) 在提取的模型上。

编辑:不好,您正在使用从 AbstractListModel 派生的自己的模型 - 您需要使您的模型成为非抽象的 - 给它一个类名,然后给您的 Model 类一个 addElement 方法。或者更简单地说,使用您用数据填充的 DefaultListModel 对象。

关于java - 按钮 ActionPerfomed 将字符串从 JList 移动到 JList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34698370/

相关文章:

java - Spring Boot 文件上传 - 连接由对等错误重置

java - 从另一个数组定义数组

java - 如何使用 Java 在 JPanel 中显示 JTable?

Java try/catch - 找到 "return isn' t“或初始化 "variable isn' t”?

c++ - 编译错误 : No match for overloaded operator

java - 按下按钮时应用程序崩溃

java - 将 Long/ULong 转换为带填充零的无符号十六进制字符串

java - 正在 64 位 VM 上编写引用原子

java - 从 JList Java Swing 中删除元素

java - 使用鼠标适配器调整 jpopupmenu 的大小