刷新JTable,以便显示插入的数据

时间:2019-05-19 02:58:28

标签: java swing jframe jtable

我正在做一个项目,并且有两个JFrame窗口。第一帧显示一个空表。其下方的按钮将打开第二个应输入数据的框架。我的问题是,当我在第二帧中单击“确定”时,第一帧中的表将不会显示插入的数据。

我尝试了jframe.revalidate();jframe.repaint()以及table.revalidate();table.repaint();,但是它不起作用。

此外,我正在使用DefaultTableModel,所以我也尝试过model.fireTableDataChanged();,但还是没有。

//first jframe
public NewJFrame() {
    initComponents();
    setLocationRelativeTo(null);
    viewTable();
}

Object[] newRow;

public NewJFrame(Object[] newRow){
    initComponents();
    setLocationRelativeTo(null);
    this.newRow = newRow;
    addNewRow();
}

public void viewTable(){
    table.setFont(new Font("Segoe UI", Font.PLAIN, 16));
    JTableHeader tablehead1 = table.getTableHeader();
    tablehead1.setFont(new Font("Segoe UI", Font.PLAIN, 16));
    table.setRowHeight(30);

    TableColumnModel columnModel = table.getColumnModel();        
    columnModel.getColumn(0).setPreferredWidth(400);     //Name
    columnModel.getColumn(1).setPreferredWidth(100);    //Age
}

public void addNewRow(){
    DefaultTableModel model = (DefaultTableModel) table.getModel();
    model.addRow(newRow);
    System.out.println(newRow[0].toString() + newRow[1].toString()); //so i would know data is present
}

private void addActionPerformed(java.awt.event.ActionEvent evt) {                                    
    form f = new form();
    f.setVisible(true);
} 

//here's the second jframe
public form() {
    initComponents();
    setLocationRelativeTo(null);
}

private void OKActionPerformed(java.awt.event.ActionEvent evt) {                                   
    Object[] input = { name.getText(), age.getText() };

    if(input.equals("")){
        System.out.println("empty");
    } else {
        NewJFrame n = new NewJFrame(input);
        n.revalidate();
        n.repaint();
        this.setVisible(false);
    }

1 个答案:

答案 0 :(得分:0)

Your problem is that you're passing the input data to a new NewJFrame and not to the existing one. The solution is to not do this, to pass it to the existing and currently displayed NewJFrame instance. How? Depends on your code. Note that the second "JFrame" should instead be a JDialog, likely a modal JDialog.