我正在按下按鈕,但由于某種原因它不起作用。我想將JComboBox資訊傳輸到此JTable.
這是 GUI 的樣子

請幫我解決這個問題。我懷疑這是一個邏輯錯誤。我只想將保管箱中的內容轉移到第二張桌子(基本上是空的)
這是代碼:
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
}
uj5u.com熱心網友回復:
回答問題
您不是通過使用 GUI 構建器來學習 Swing。Oracle 有一個有用的教程,
修改這些方法。
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;
}
}
}
更好的方式
我創建了我所看到的雙向選擇串列。
我沒有使用 GUI 構建器。我手工撰寫了 Swing GUI。
不僅選擇串列在兩個方向都起作用,而且展館的排序順序也保持不變。
這是啟動應用程式時的 GUI。

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.

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

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

Here's the final state of the GUI.

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.
我編碼了一個JFrame,一個主要的JPanel和兩個內部的JPanels。在JFrame使用默認BorderLayout。主要JPanel使用一個FlowLayout和持有兩個內部JPanels和兩個JButtons。
每個內部都JPanel使用 aBoxLayout并持有 aJLabel和 a 的JList內部JScrollPane。我把兩個內部都做成JPanels了相同的首選尺寸。
這是完整的可運行代碼。我制作了所有附加類的內部類,以便我可以將代碼作為一個塊發布。
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);
}
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/396213.html
