我想将 JComboBox 信息传输到这个 JTable

I want to transfer JComboBox info into this JTable

我正在按下按钮,但由于某种原因无法正常工作。 我想将 JComboBox 信息传输到此 JTable

这是 GUI 的样子

请帮我解决这个问题。我怀疑这是一个逻辑错误。 我只想把dropbox里的内容转移到第二个table(基本上是空的)

代码如下:

package com.mycompany.expoapp.newpackage;

import java.util.Vector;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import javax.swing.JFrame;

public class ExpoAPP extends javax.swing.JFrame {
    DefaultTableModel model;

    /**
     * Creates new form ExpoAPP
     */
    public ExpoAPP() {
        initComponents();
    }

    @SuppressWarnings("unchecked")                         
    private void initComponents() {
        Dropbox = new javax.swing.JComboBox<>();
        jScrollPane1 = new javax.swing.JScrollPane();
        visit = new javax.swing.JTable();
        jScrollPane2 = new javax.swing.JScrollPane();
        notvisit = new javax.swing.JTable();
        VISITED = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        Dropbox.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Select the Pavillion you Visited", "Algeria Pavillion", "Brazil Pavillion", "Chile Pavillion", "Denmark Pavillion", "Ethiopia Pavillion", "Fiji Pavillion", "Germany Pavillion", "Hungary Pavillion", "Indonesia Pavillion", "Japan Pavillion", "Korea Pavillion", "Luxembourg Pavillion", "Malaysia Pavillion", "Niger Pavillion", "Palestine Pavillion", "Qatar Pavillion", "Rawanda Pavillion", "Singapore Pavillion", "UK pavillion", "Venezuela Pavillion", "Yemen Pavillion", "Zambia Pavillion" }));
        Dropbox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                DropboxActionPerformed(evt);
            }
        });

        visit.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
            },
            new String [] {
                "Visited"
            }
        ));
        visit.setAlignmentX(1.0F);
        visit.setAlignmentY(1.0F);
        visit.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                visitMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(visit);

        notvisit.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {"Algeria Pavillion"},
                {"Brazil Pavillion"},
                {"Chile Pavillion"},
                {"Denmark Pavillion"},
                {"Ethiopia Pavillion"},
                {"Fiji Pavillion "},
                {"Germany Pavillion"},
                {"Hungary Pavillion"},
                {"Indonesia Pavillion"},
                {"Japan Pavillion"},
                {"Korea Pavillion"},
                {"Luxembourg Pavillion"},
                {"Malaysia Pavillion"},
                {"Niger Pavillion"},
                {"Palestine Pavillion"},
                {"Qatar Pavillion"},
                {"Rawanda Pavillion"},
                {"Singapore Pavillion"},
                {"UK pavillion"},
                {"Venezuela Pavillion"},
                {"Yemen Pavillion"},
                {"Zambia Pavillion"}
            },
            new String [] {
                "Not Visited"
            }
        ));
        notvisit.setAlignmentX(1.0F);
        notvisit.setAlignmentY(1.0F);
        jScrollPane2.setViewportView(notvisit);

        VISITED.setText("Visited!");
        VISITED.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                VISITEDActionPerformed(evt);
            }
        });

        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(Dropbox, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 34, Short.MAX_VALUE)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addGap(132, 132, 132)
                .addComponent(VISITED, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(61, 61, 61)
                .addComponent(Dropbox, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(28, 28, 28)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 385, Short.MAX_VALUE)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(VISITED, javax.swing.GroupLayout.DEFAULT_SIZE, 38, Short.MAX_VALUE)
                .addGap(25, 25, 25))
        );

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

    private void DropboxActionPerformed(java.awt.event.ActionEvent evt) {                                        
        // TODO add your handling code here:
    }                                       

    private void visitMouseClicked(java.awt.event.MouseEvent evt) {                                   
        // TODO add your handling code here:
int selectedRow = visit.getSelectedRow();
    String comboSub = model.getValueAt(selectedRow, 0).toString();
        for (int i = 0; i < Dropbox.getItemCount(); i++) 
{
           if (Dropbox.getItemAt(i).toString().equalsIgnoreCase(comboSub)) 
               {
                Dropbox.setSelectedIndex(i);
               }
}
    }                                  

    private void VISITEDActionPerformed(java.awt.event.ActionEvent evt) {                                        
        // TODO add your handling code here:
    }                                       

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

    // Variables declaration - do not modify                     
    private javax.swing.JComboBox<String> Dropbox;
    private javax.swing.JButton VISITED;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable notvisit;
    private javax.swing.JTable visit;
    // End of variables declaration                   
}

回答问题

您不是通过使用 GUI 生成器来学习 Swing。 Oracle 有一个有用的教程,Creating a GUI With Swing。跳过 Netbeans 部分。

您有一个保管箱和一个包含展馆列表的 table。为什么你需要两者?您要么有一个保管箱,要么有一个带有展馆列表的 table。带有展馆列表的 table 通常在两个 table 之间有按钮,用于在两个方向上移动项目。看来你想要的是所谓的双向select离子列表。

此外,您有两个不同的展馆列表。斐济在 table 名单中多了一个 space,英国馆有未大写的展馆。

这是select三个亭子后的界面。

修改这些方法。

private void DropboxActionPerformed(java.awt.event.ActionEvent evt) {                                        
    // TODO add your handling code here:
}                                       

private void visitMouseClicked(java.awt.event.MouseEvent evt) {                                   
    // TODO add your handling code here:
}                                  

private void VISITEDActionPerformed(java.awt.event.ActionEvent evt) {
    // Keep user from selecting "Select..."
    int index = Dropbox.getSelectedIndex();
    if (index <= 0) {
        return;
    }

    // Add visited pavilion
    String pavilion = ((String) Dropbox.getSelectedItem()).trim();
    Object[] modelRow = new Object[] { pavilion };
    DefaultTableModel visitModel = (DefaultTableModel) visit.getModel();
    visitModel.addRow(modelRow);

    // Remove visited pavilion
    Dropbox.removeItem(pavilion);
    Dropbox.setSelectedIndex(0);
    DefaultTableModel notvisitModel = (DefaultTableModel) notvisit.getModel();

    @SuppressWarnings("rawtypes")
    Vector<Vector> vector = notvisitModel.getDataVector();
    int size = vector.size();
    for (index = 0; index < size; index++) {
        Vector<?> innerVector = vector.get(index);
        String visitedPavilion = ((String) innerVector.get(0)).trim();
        if (pavilion.equals(visitedPavilion)) {
            vector.remove(index);
            notvisit.repaint();
            break;
        }
    }
}  

更好的方法

我创建了我所看到的双向 select离子列表。

我没有使用 GUI 生成器。我手动编写了 Swing GUI。

不仅 selection 列表双向工作,而且展馆的排序顺序也保持不变。

这是启动应用程序时的 GUI。

这是 select 三个亭子后的 GUI。您 select 多个展馆,方法是按住 Ctrl 键,同时在您访问过的展馆上左键单击鼠标。

这是左键单击 > 按钮后的 GUI。

这是我改变主意并删除了一个亭子后的 GUI。

这是 GUI 的最终状态。

说明

我为未参观的展馆创建了一个模型。我不必担心两个数据模型持有不一致的信息。

我扩展了 DefaultListModel class 以添加排序方法。此方法可确保未访问和已访问的展馆列表 JLists 将按字母顺序排列。

我编码了一个JFrame,一个主JPanel,两个内部JPanelsJFrame 使用默认值 BorderLayout。主 JPanel 使用一个 FlowLayout 并包含两个内部 JPanels 和两个 JButtons.

每个内部 JPanel 使用一个 BoxLayout 并在 JScrollPane 中包含一个 JLabel 和一个 JList。我将两个内部 JPanels 设为相同的首选尺寸。

这是完整的可运行代码。我将所有额外的 classes 都放在 classes 中,这样我就可以 post 将代码作为一个块。

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.util.Arrays;

import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;

public class ExpoGUI implements Runnable {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new ExpoGUI());
    }
    
    private final ExpoModel model;
    
    private JList<String> notVisitedList, visitedList;
    
    public ExpoGUI() {
        this.model = new ExpoModel();
    }

    @Override
    public void run() {
        JFrame frame = new JFrame("Expo GUI");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        frame.add(createMainPanel(), BorderLayout.CENTER);
        
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }
    
    private JPanel createMainPanel() {
        JPanel panel = new JPanel(new FlowLayout());
        panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        
        JPanel notVisitedPanel = createNotVisitedPanel();
        JPanel visitedPanel = createVisitedPanel();
        visitedPanel.setPreferredSize(notVisitedPanel.getPreferredSize());
        panel.add(notVisitedPanel);
        
        JButton removeButton = new JButton("<");
        panel.add(removeButton);
        
        removeButton.addActionListener(event -> {
            int[] indices = visitedList.getSelectedIndices();
            String[] pavilions = new String[indices.length];
            for (int index = 0; index < indices.length; index++) {
                pavilions[index] = model.getVisitedListModel().get(indices[index]);
                model.addNotVisited(pavilions[index]);
            }
            for (int index = 0; index < indices.length; index++) {
                model.removeVisited(pavilions[index]);
            }
            model.getNotVisitedListModel().sort();
            model.getVisitedListModel().sort();
        });
        
        JButton addButton = new JButton(">");
        panel.add(addButton);
        
        addButton.addActionListener(event -> {
            int[] indices = notVisitedList.getSelectedIndices();
            String[] pavilions = new String[indices.length];
            for (int index = 0; index < indices.length; index++) {
                pavilions[index] = model.getNotVisitedListModel().get(indices[index]);
                model.addVisited(pavilions[index]);
            }
            for (int index = 0; index < indices.length; index++) {
                model.removeNotVisited(pavilions[index]);
            }
            model.getNotVisitedListModel().sort();
            model.getVisitedListModel().sort();
        });
        
        panel.add(visitedPanel);
        
        return panel;
    }
    
    private JPanel createNotVisitedPanel() {
        JPanel panel = new JPanel();
        panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
        panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        
        JLabel label = new JLabel("Not Visited");
        label.setHorizontalAlignment(JLabel.CENTER);
        panel.add(label);
        
        notVisitedList = new JList<>(model.getNotVisitedListModel());
        JScrollPane scrollPane = new JScrollPane(notVisitedList);
        scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        panel.add(scrollPane);
        
        return panel;
    }
    
    private JPanel createVisitedPanel() {
        JPanel panel = new JPanel();
        panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
        panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        
        JLabel label = new JLabel("Visited");
        label.setHorizontalAlignment(JLabel.CENTER);
        panel.add(label);
        
        visitedList = new JList<>(model.getVisitedListModel());
        JScrollPane scrollPane = new JScrollPane(visitedList);
        scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        panel.add(scrollPane);
        
        return panel;
    }
    
    public class ExpoModel {
        
        private final String [] pavilions = {            
            "Algeria Pavilion",
            "Brazil Pavillon",
            "Chile Pavilion",
            "Denmark Pavilion",
            "Ethiopia Pavllion",
            "Fiji Pavilion",
            "Germany Pavilion",
            "Hungary Pavilion",
            "Indonesia Pavilion",
            "Japan Pavilion",
            "Korea Pavilion",
            "Luxembourg Pavilion",
            "Malaysia Pavilion",
            "Niger Pavilion",
            "Palestine Pavilion",
            "Qatar Pavilion",
            "Rawanda Pavilion",
            "Singapore Pavilion",
            "UK Pavilion",
            "Venezuela Pavilion",
            "Yemen Pavilion",
            "Zambia Pavilion"
        };
        
        private final SortedListModel notVisitedListModel, visitedListModel;
        
        public ExpoModel() {
            this.notVisitedListModel = new SortedListModel();
            this.visitedListModel = new SortedListModel();
            
            for (int index = 0; index < pavilions.length; index++) {
                this.notVisitedListModel.addElement(pavilions[index]);
            }
        }
        
        public void addNotVisited(String pavilion) {
            notVisitedListModel.addElement(pavilion);
        }
        
        public void addVisited(String pavilion) {
            visitedListModel.addElement(pavilion);
        }
        
        public void removeNotVisited(String pavilion) {
            notVisitedListModel.removeElement(pavilion);
        }
        
        public void removeVisited(String pavilion) {
            visitedListModel.removeElement(pavilion);
        }

        public SortedListModel getNotVisitedListModel() {
            return notVisitedListModel;
        }

        public SortedListModel getVisitedListModel() {
            return visitedListModel;
        }
    
    }
    
    public class SortedListModel extends DefaultListModel<String> {

        private static final long serialVersionUID = 1L;

        private String[] array;

        public void sort() {
            if (getSize() <= 0) {
                return;
            }
            
            array = new String[getSize()];
            copyInto(array);
            Arrays.sort(array);
            clear();

            for (String s : array) {
                addElement(s);
            }
        }

    }

}