Home > database >  I want to transfer JComboBox info into this JTable
I want to transfer JComboBox info into this JTable

Time:12-27

Am pressing the Button but it's not working for some reason. I want to transfer JComboBox info into this JTable.

Here's what the GUI looks like

enter image description here

Please help me fix this issue. I am suspect it's a logic error. I just want the contents in the dropbox to be transferred to the 2nd table (Which is basically empty)

Here's the code:

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                   
}

CodePudding user response:

Answering The Question

You're not learning Swing by using a GUI builder. Oracle has a helpful tutorial, enter image description here

Modify these methods.

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;
        }
    }
}  

A Better Way

I created what I've seen as a bi-directional selection list.

I didn't use a GUI builder. I coded the Swing GUI by hand.

Not only does the selection list work in both directions, but the sort order of the pavilions is also maintained.

Here's the GUI when starting the application.

enter image description here

Here's the GUI after selecting three pavilions. You select multiple pavilions by holding down the Ctrl key while left-clicking the mouse on the pavilions you've visited.

enter image description here

Here's the GUI after left-clicking the > button.

enter image description here

Here's the GUI after I changed my mind snd removed one pavilion.

enter image description here

Here's the final state of the GUI.

enter image description here

Explanation

I created one model for the not visited pavilions. I don't have to worry about two data models holding inconsistent information.

I extended the DefaultListModel class to add a sort method. This method ensures that the pavilion list in both the not visited and visited JLists will be in alphabetical order.

I coded a JFrame, a main JPanel, and two inner JPanels. The JFrame uses a default BorderLayout. The main JPanel uses a FlowLayout and holds the two inner JPanels and the two JButtons.

Each inner JPanel uses a BoxLayout and holds a JLabel and a JList inside of a JScrollPane. I made both inner JPanels the same preferred size.

Here's the complete runnable code. i made all the additional classes inner classes so I could post the code as one block.

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);
            }
        }

    }

}
  • Related