简体   繁体   English

按钮ActionPerfomed将字符串从JList移到JList

[英]Button ActionPerfomed move string from JList to JList

I am working on an assessment for a program I would like to participate in. I am still a bit turned around on how to interpret, understand or properly use the "tutorials" located at Tutorials Point which were provided by the program. 我正在为我想参加的程序进行评估。关于如何解释,理解或正确使用该程序提供的Tutorials Point上的“ tutorials”,我还有点回头。

Jlist created using Netbeans 8.1 --> JFrame Form GUI Builder 使用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                   
}

I am getting errors cannot find symbol - symbol: method addElement(Object) location: variable partsList type of Jlist 我遇到错误, 找不到符号 -符号:方法addElement(Object)位置:可变部件Jlist的列表类型

the error reads very straight-forward to me. 该错误对我来说很简单。 My problem is most of the examples I've seen are using DefaultListModel. 我的问题是我看到的大多数示例都使用DefaultListModel。 NetBeans is using the AbstractListModel method. NetBeans使用的是AbstractListModel方法。

I have reviewed the following references: 我查看了以下参考资料:

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

But I honestly feel like I am not properly understanding how these sources are to be used to debug. 但老实说,我觉得我没有正确理解如何使用这些源进行调试。 I feel like I am not properly using the Object --> String based on this bit of code: 我觉得我基于这段代码无法正确使用Object-> String:

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

} }

I will be including this request for assistance in the code via comment. 我将通过注释在代码中包含此帮助请求。 I'm not a cheater. 我不是骗子。 I have looked, worked, searched and thought about this for a few days. 我已经寻找,工作,搜索并考虑了几天。 At this point I feel like asking for help would be prudent. 在这一点上,我觉得寻求帮助将是审慎的。

The API will help you some here, since if you check out the JList API, you'll see that your compiler was right, that JList does not have an addElement(...) method, but don't lose heart -- the DefaultListModel class does have this method, and you can extract this from your JList by calling getModel() , and then call addElement(...) on the extracted model. 该API将在这里为您提供帮助,因为如果您检出JList API,您会看到编译器是正确的,JList没有addElement(...)方法,但请不要灰心- DefaultListModel类确实具有此方法,您可以通过调用getModel()从JList中提取此方法,然后在提取的模型上调用addElement(...)

Edit: no good, you're using your own model derived from AbstractListModel -- you will need to make your model non-abstract -- give it a class name, and then give your Model class an addElement method. 编辑:不好,您正在使用从AbstractListModel派生的自己的模型-您将需要使模型非抽象-给它一个类名,然后给您的Model类一个addElement方法。 Either that or more simply, use a DefaultListModel object that you fill with your data. 更简单地说,使用您用数据填充的DefaultListModel对象。

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

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