Java: 将数据从对话框文本字段复制到 JTable

Java: Copying data from dialog box text field to JTable

此项目要求用户将数据输入到可从菜单栏访问的对话框的文本字段中,并将文本字段中的数据放入 JTable。问题是,一旦用户在将信息放入文本字​​段后单击对话框上的确定,对话框就不再可见,但 JTable 中什么也没有出现。 JTable headers 在那里,但是刚刚提交的信息没有。

这是一个露营注册程序,所有classes编译都可以。我只是先从房车预订处获取信息,但最终会为帐篷预订做同样的事情。这是对应于 RV 签到的 classes。有一个 RV 构造函数,它具有参数 (String (name), String (check in day), int (days staying), String (leave day), int(站点编号),int(所需电源))。 首先是对话框 class:

package campingPrj;

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;

public class DialogCheckInRv extends javax.swing.JDialog implements ActionListener {

private static final long serialVersionUID = 1L;
private javax.swing.JTextField nameTxt;
private javax.swing.JTextField dateIn;
private javax.swing.JTextField stayingTxt;
private javax.swing.JTextField siteNumberTxt;
private javax.swing.JTextField checkOutDate;
private javax.swing.JTextField powerTxt;
private javax.swing.JButton okButton;
private javax.swing.JButton cancelButton;
private boolean cancel;
private boolean okay;


public DialogCheckInRv(java.awt.Frame parent) {
    super(parent, true);
    setupDialog();
    setTitle("RV Check In");
}


private void setupDialog() {
    setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);

    nameTxt = new javax.swing.JTextField(27);
    dateIn = new javax.swing.JTextField(25);
    stayingTxt = new javax.swing.JTextField(25);
    siteNumberTxt = new javax.swing.JTextField(27);
    powerTxt = new javax.swing.JTextField(27);

    okButton = new javax.swing.JButton("Ok");
    okButton.addActionListener(this);
    cancelButton = new javax.swing.JButton("Cancel");
    cancelButton.addActionListener(this);

    setLayout(new GridLayout(6, 1));

    JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT));
    panel.add(new JLabel("Name Reserving:"));
    panel.add(nameTxt);
    add(panel);

    panel = new JPanel(new FlowLayout(FlowLayout.LEFT));
    panel.add(new JLabel("Start Date (mm/dd/yy) :"));
    panel.add(dateIn);
    add(panel);

    panel = new JPanel(new FlowLayout(FlowLayout.LEFT));
    panel.add(new JLabel("Days Planning on Staying:"));
    panel.add(stayingTxt);
    add(panel);

    panel = new JPanel(new FlowLayout(FlowLayout.LEFT));
    panel.add(new JLabel("Requested Site Number:"));
    panel.add(siteNumberTxt);
    add(panel);

    panel = new JPanel(new FlowLayout(FlowLayout.LEFT));
    panel.add(new JLabel("Power Needed (in AMPs):"));
    panel.add(powerTxt);
    add(panel);


    panel = new JPanel();
    panel.add(okButton);
    panel.add(cancelButton);
    add(panel);

    pack();
    setLocationRelativeTo(null);
}

public void actionPerformed(java.awt.event.ActionEvent event) {
    if (event.getSource() == okButton) {
        okay = true;
        cancel = false;
        setVisible(false);
    }
    if (event.getSource() == cancelButton) {
        okay = false;
        cancel = true;
        setVisible(false);
    }
}

public boolean isOk() {
    return okay;
}

public boolean isCancel() {
    return cancel;
}

public String getName() {
    return nameTxt.getText();
}

public String getDateIn() {
    return dateIn.getText();
}

public String getDaysStaying() {
    return stayingTxt.getText();
}

public String getCheckOutDate() {
    return checkOutDate.getText();
}

public String getPower() {
    return powerTxt.getText();
}

public String getSiteNumber() {
    return siteNumberTxt.getText();
}

public void clear() {
    nameTxt.setText(null);
    dateIn.setText(null);
    stayingTxt.setText(null);
    dateIn.setText(null);
    powerTxt.setText(null);
    siteNumberTxt.setText(null);
}

}

带有 table 的 GUI(我猜问题出在 actionPerformed 方法中):

 package campingPrj;

 import java.awt.BorderLayout;
 import java.awt.event.ActionEvent;
 import java.awt.event.ActionListener;

 import javax.swing.*;

 @SuppressWarnings("serial")
 public class GUICampingReg extends javax.swing.JFrame implements ActionListener {

private JMenuItem openSerialFileItem = new JMenuItem("Open Serialized File");
private JMenuItem openTextFileItem = new JMenuItem("Open Text File");
private JMenuItem saveSerialFileItem = new JMenuItem("Save Serialized File");
private JMenuItem saveTextFileItem = new JMenuItem("Save Text File");
private JMenuItem exitItem = new JMenuItem("Exit");
private JMenuItem checkInTentItem = new JMenuItem("Check in tent");
private JMenuItem checkInRVItem = new JMenuItem("Check in RV");
private JMenuItem checkOutItem = new JMenuItem("Date Leaving");

private JTextField nameReservingTxt;
private JTextField dateInTxt;
private JTextField daysStayingTxt;
private JTextField checkOutOnTxt;
private JTextField siteNumberTxt;
private JTextField powerTxt;

private JFrame frame;
private JTable table;
private SiteModel model;
private JScrollPane scrollPane;
private DialogCheckInRv newRv;

public GUICampingReg() {
    setupFrame();
    newRv = new DialogCheckInRv(this);
    model = new SiteModel();
    table.setModel(model);
}

private void setupFrame() {
    frame = new JFrame();
    frame.setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    frame.setTitle("Camping Registration Program");

    scrollPane = new JScrollPane();
    table = new JTable();

    JMenuBar menubar = new JMenuBar();

    JMenu fileMenu = new JMenu("File");
    fileMenu.add(openSerialFileItem);
    fileMenu.add(openTextFileItem);
    fileMenu.add(saveSerialFileItem);
    fileMenu.add(saveTextFileItem);
    fileMenu.add(exitItem);

    JMenu checkInMenu = new JMenu("Check In");
    checkInMenu.add(checkInRVItem);
    checkInMenu.add(checkInTentItem);

    JMenu checkOutMenu = new JMenu("Check Out");
    checkOutMenu.add(checkOutItem);

    menubar.add(fileMenu);
    menubar.add(checkInMenu);
    menubar.add(checkOutMenu);

    openSerialFileItem.addActionListener(this);
    openTextFileItem.addActionListener(this);
    saveSerialFileItem.addActionListener(this);
    saveTextFileItem.addActionListener(this);
    exitItem.addActionListener(this);
    checkInTentItem.addActionListener(this);
    checkInRVItem.addActionListener(this);
    checkOutItem.addActionListener(this);

    frame.setJMenuBar(menubar);

    scrollPane
            .setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
    table.setToolTipText("");
    table.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
    table.getTableHeader().setReorderingAllowed(false);
    table.addMouseListener(new java.awt.event.MouseAdapter() {
        public void mouseClicked(java.awt.event.MouseEvent evt) {
            tableMouseClicked();
        }

    });

    scrollPane.setViewportView(table);
    frame.add(scrollPane, BorderLayout.CENTER);

    frame.pack();
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
}

private void tableMouseClicked() {
    // TODO Auto-generated method stub

}

public void actionPerformed(ActionEvent evt) {
    Object pressed = evt.getSource();

    if (pressed == exitItem) {
        System.exit(0);
    }
    if (pressed == openSerialFileItem) {

    }
    if (pressed == openTextFileItem) {

    }
    if (pressed == saveSerialFileItem) {

    }
    if (pressed == saveTextFileItem) {

    }
    if (pressed == checkInTentItem) {

    }
    if (pressed == checkInRVItem) {
        newRv.clear();
        newRv.setVisible(true);
        if (newRv.isOk()) {
            String nameReserving = nameReservingTxt.getText();
            String checkIn = dateInTxt.getText();
            int daysStaying = Integer.parseInt(daysStayingTxt.getText());
            String checkOutOn = checkOutOnTxt.getText();
            int siteNumber = Integer.parseInt(siteNumberTxt.getText());
            int power = Integer.parseInt(powerTxt.getText());
            RV rv = new RV (nameReserving, checkIn, daysStaying, checkOutOn, siteNumber, power);
            model.add(rv);
        }

    }
    if (pressed == checkOutItem) {

    }

}

public static void main(String args[]) {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            new GUICampingReg();
        }
    });
}

}

站点模型class:

package campingPrj;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;

import javax.swing.table.AbstractTableModel;

public class SiteModel extends AbstractTableModel {

private static final long serialVersionUID = 1L;
private ArrayList<Site> listSites;
private String[] columnNames = { "Name Reserving", "Checked in Date",
        "Days Staying", "Site #", "Tenters/RV Power Needed" };

public SiteModel() {
    listSites = new ArrayList<Site>();
}

public String getColumnName(int col) {
    return columnNames[col];
}

public int getColumnCount() {
    return columnNames.length;
}

public int getRowCount() {
    return listSites.size();
}

public Object getValueAt(int row, int col) {
    Object val = null;
    switch (col) {
    case 0:
        val = listSites.get(row).getNameReserving();
        break;
    case 1:
        val = listSites.get(row).getCheckIn();
        break;
    case 2:
        val = listSites.get(row).getDaysStaying();
        break;
    case 3:
        val = listSites.get(row).getSiteNumber();
        break;
    case 4:
        val = listSites.get(row).getCheckOutOn();
        break;

    }
    return val;
}

public Site get(int index) {
    return listSites.get(index);
}

public int indexOf(Site s) {
    return listSites.indexOf(s);
}

public void add(Site s) {
    if (s != null) {
        listSites.add(s);
        fireTableRowsInserted(listSites.size() - 1, listSites.size() - 1);
    }
}

public void add(int index, Site s) {
    if (s != null) {
        listSites.add(index, s);
        fireTableRowsInserted(index, index);
    }
}

public void remove(int index) {
    listSites.remove(index);
    fireTableRowsDeleted(index, index);
    return;
}

public void remove(Site s) {
    remove(indexOf(s));
}

public void saveAsSerialized(String filename) throws IOException {
    FileOutputStream fos = new FileOutputStream(filename);
    ObjectOutputStream os = new ObjectOutputStream(fos);
    os.writeObject(listSites);
    os.close();
}

@SuppressWarnings("unchecked")
public void loadFromSerialized(String filename) throws IOException,
        ClassNotFoundException {
    FileInputStream fis = new FileInputStream(filename);
    ObjectInputStream is = new ObjectInputStream(fis);
    listSites = (ArrayList<Site>) is.readObject();
    is.close();
}

}

那么,如何让信息显示在 JTable 中?

也许我误解了你的代码,但我没有看到你在哪里提取用户输入对话框的信息。例如这里:

    if (newRv.isOk()) {
        String nameReserving = nameReservingTxt.getText();
        String checkIn = dateInTxt.getText();
        int daysStaying = Integer.parseInt(daysStayingTxt.getText());
        String checkOutOn = checkOutOnTxt.getText();
        int siteNumber = Integer.parseInt(siteNumberTxt.getText());
        int power = Integer.parseInt(powerTxt.getText());
        RV rv = new RV (nameReserving, checkIn, daysStaying, checkOutOn, siteNumber, power);
        model.add(rv);
    }

您似乎是从 GUICampingReg 而不是 newRv 对象持有的字段中提取信息。您不应该调用 newRv 的方法来提取创建 RV 对象所需的数据吗?

例如,

    if (newRv.isOk()) {
        String nameReserving = newRv.getName();
        String checkIn = newRv.getDateIn();

        // .... etc

        RV rv = new RV (nameReserving, checkIn, daysStaying, checkOutOn, siteNumber, power);
        model.add(rv);
    }