如何从另一个JFrame接收值并插入JTable中

时间:2016-03-27 03:31:55

标签: java swing netbeans

我很难接受来自一个JFrame的值并插入JTable中。

我想知道如何接收一个准备插入我的JTable的对象。来自我的班级FrameTemp。

班级模型Acadêmico。

package model;

public class Academico {
private String matricula;
private String nome;
private String curso;
private int periodo;

public Academico() {
}

public Academico(String matricula, String nome, String curso, int periodo) {
    this.matricula = matricula;
    this.nome = nome;
    this.curso = curso;
    this.periodo = periodo;
}

public String getMatricula() {
    return matricula;
}

public void setMatricula(String matricula) {
    this.matricula = matricula;
}

public String getNome() {
    return nome;
}

public void setNome(String nome) {
    this.nome = nome;
}

public String getCurso() {
    return curso;
}

public void setCurso(String curso) {
    this.curso = curso;
}

public int getPeriodo() {
    return periodo;
}

public void setPeriodo(int periodo) {
    this.periodo = periodo;
}
}

应该接收值的类框架。

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;

public class Frame extends JFrame implements ActionListener {

private static Academico novoAcademico;
private static FrameTemp frameTemporario;
private JTable tabela;
private DefaultTableModel modelo;
private ArrayList<Academico> academicos;
private JButton btAdd, btAtualizar, btDelete;
private JPanel painel, painelGrid;
private BorderLayout borderLayout;
private GridLayout gridLayout;

public Frame(Academico academico) {
    this.setTitle("Acadêmicos Cadastrados");

    this.painel = new JPanel();
    this.painelGrid = new JPanel();

    borderLayout = new BorderLayout();
    gridLayout = new GridLayout(1, 3);
    setContentPane(painel);
    this.setLayout(borderLayout);

    painel.add(painelGrid);
    painelGrid.setLayout(gridLayout);

    this.modelo = new DefaultTableModel();
    this.tabela = new JTable(modelo);
    this.btAdd = new JButton("Insert");
    this.btAdd.setFont(new Font("Verdana", Font.PLAIN, 20));
    this.btAdd.setBackground(Color.BLACK);
    this.btAdd.setForeground(Color.WHITE);
    this.btAtualizar = new JButton("Update");
    this.btAtualizar.setFont(new Font("Verdana", Font.PLAIN, 20));
    this.btAtualizar.setBackground(Color.BLACK);
    this.btAtualizar.setForeground(Color.WHITE);
    this.btDelete = new JButton("Delete");
    this.btDelete.setFont(new Font("Verdana", Font.PLAIN, 20));
    this.btDelete.setBackground(Color.BLACK);
    this.btDelete.setForeground(Color.WHITE);

    this.modelo.addColumn("Matrícula");
    this.modelo.addColumn("Nome");
    this.modelo.addColumn("Curso");
    this.modelo.addColumn("Período");

    this.tabela.getColumnModel().getColumn(0).setPreferredWidth(20);
    this.tabela.getColumnModel().getColumn(1).setPreferredWidth(30);
    this.tabela.getColumnModel().getColumn(2).setPreferredWidth(50);
    this.tabela.getColumnModel().getColumn(3).setPreferredWidth(20);

    this.academicos = new ArrayList<>();

    this.academicos.add(new Academico("123", "Student1", "Information System", 3));
    this.academicos.add(new Academico("234", "Student2", "Science", 5));
    this.academicos.add(new Academico("345", "Student3", "Engineer", 7));

    for (Academico a : this.academicos) {
        this.modelo.addRow(new Object[]{a.getMatricula(), a.getNome(), a.getCurso(), a.getPeriodo()});
    }

    this.painel.add(BorderLayout.NORTH, new JScrollPane(this.tabela));
    this.painel.add(BorderLayout.SOUTH, painelGrid);
    this.painelGrid.add(btAdd);
    this.painelGrid.add(btAtualizar);
    this.painelGrid.add(btDelete);

    this.btDelete.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            int dialog = JOptionPane.YES_NO_OPTION;

            int selRow = tabela.getSelectedRow();
            if (selRow != -1) {
                int resultado = JOptionPane.showConfirmDialog(null, "Deseja realmente excluir essa linha?", "Confirmação", dialog);

                if (resultado == 0) {
                    modelo.removeRow(selRow);
                }

            }
        }
    }
    );

    this.btAdd.addActionListener(this);

    this.pack();

    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    this.setVisible(true);
}

public static void main(String[] args) {
    new Frame(novoAcademico);
}

@Override
public void actionPerformed(ActionEvent e) {
    if (e.getSource() == btAdd) {

        Academico academico = new Academico();
        frameTemporario = new FrameTemp();
        frameTemporario.setVisible(true);


        ArrayList<Academico> lista = new ArrayList<>();

        lista.add(new Academico(academico.getMatricula(), academico.getNome(), academico.getCurso(), academico.getPeriodo()));

        for (Academico a : lista) {

            this.modelo.addRow(new Object[]{a.getMatricula(), a.getNome(), a.getCurso(), a.getPeriodo()});
        }


    }
}
}

应该发送值的类

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import org.jdesktop.swingx.prompt.PromptSupport;

public class FrameTemp extends JFrame implements ActionListener {

private String title = "Adicionar novo";
private Frame frame;
private ArrayList<Academico> academicos;
private Academico academico;
private JTextField tfMatricula, tfNome, tfCurso, tfPeriodo;
private JButton btConfirmar;
private JPanel painel, painelGrid;

private BorderLayout borderLayout;
private GridLayout gridLayout;

public FrameTemp() {
    this.setTitle(title);
    Container c = getContentPane();

    c.setLayout(new BorderLayout());

    Container c2 = new JPanel();
    c2.setLayout(new GridLayout(1, 4));
    academico = new Academico();
    academicos = new ArrayList<Academico>();

    this.btConfirmar = new JButton("Confirmar");
    this.tfMatricula = new JTextField();
    this.tfMatricula.setToolTipText("Insira sua matrícula aqui");
    PromptSupport.setPrompt("Matrícula", tfMatricula);
    PromptSupport.setFocusBehavior(PromptSupport.FocusBehavior.SHOW_PROMPT, tfMatricula);
    PromptSupport.setFontStyle(Font.BOLD, tfMatricula);

    this.tfNome = new JTextField();
    this.tfNome.setToolTipText("Insira seu nome aqui");
    PromptSupport.setPrompt("Nome", tfNome);
    PromptSupport.setFocusBehavior(PromptSupport.FocusBehavior.SHOW_PROMPT, tfNome);
    PromptSupport.setFontStyle(Font.BOLD, tfNome);

    this.tfCurso = new JTextField();
    this.tfCurso.setToolTipText("Insira seu curso aqui");
    PromptSupport.setPrompt("Curso", tfCurso);
    PromptSupport.setFocusBehavior(PromptSupport.FocusBehavior.SHOW_PROMPT, tfCurso);
    PromptSupport.setFontStyle(Font.BOLD, tfCurso);

    this.tfPeriodo = new JTextField();
    this.tfPeriodo.setToolTipText("Insira seu período aqui");
    PromptSupport.setPrompt("Período", tfPeriodo);
    PromptSupport.setFocusBehavior(PromptSupport.FocusBehavior.SHOW_PROMPT, tfPeriodo);
    PromptSupport.setFontStyle(Font.BOLD, tfPeriodo);

    btConfirmar.addActionListener(this);
    c2.add(tfMatricula);
    c2.add(tfNome);
    c2.add(tfCurso);
    c2.add(tfPeriodo);

    c.add(btConfirmar);

    c.add(BorderLayout.NORTH, c2);
    c.add(BorderLayout.SOUTH, btConfirmar);

    this.setVisible(true);
    this.setSize(500, 300);
    this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}

@Override
public void actionPerformed(ActionEvent e) {

    this.academico.setMatricula(tfMatricula.getText().toString());
    this.academico.setNome(tfNome.getText());
    this.academico.setCurso(tfCurso.getText());
    this.academico.setPeriodo(Integer.parseInt(tfPeriodo.getText()));

   Frame frame = new Frame(academico);
    this.dispose();
}

}

2 个答案:

答案 0 :(得分:4)

根据您似乎尝试做的事情,应该使用modal对话框,这会导致代码执行停止,对话框变为可见,直到它被隐藏为止用户。

有关详细信息,请参阅How to Make Dialogs

例如......

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import org.jdesktop.swingx.prompt.PromptSupport;

public class Main {

    public static void main(String[] args) {
        new Main();
    }

    public Main() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                StuffINeedToAskYou askYou = new StuffINeedToAskYou();
                int response = JOptionPane.showConfirmDialog(null, askYou, "Adicionar novo", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
                if (response == JOptionPane.OK_OPTION) {
                    Academico academico = askYou.getAcademico();
                }
            }
        });
    }

    public class StuffINeedToAskYou extends JPanel implements ActionListener {

        private String title = "Adicionar novo";
        private ArrayList<Academico> academicos;
        private Academico academico;
        private JTextField tfMatricula, tfNome, tfCurso, tfPeriodo;
        private JButton btConfirmar;
        private JPanel painel, painelGrid;

        private BorderLayout borderLayout;
        private GridLayout gridLayout;

        public StuffINeedToAskYou() {

            setLayout(new BorderLayout());

            Container c2 = new JPanel();
            c2.setLayout(new GridLayout(1, 4));
            academico = new Academico();
            academicos = new ArrayList<Academico>();

            this.btConfirmar = new JButton("Confirmar");
            this.tfMatricula = new JTextField();
            this.tfMatricula.setToolTipText("Insira sua matrícula aqui");
            PromptSupport.setPrompt("Matrícula", tfMatricula);
            PromptSupport.setFocusBehavior(PromptSupport.FocusBehavior.SHOW_PROMPT, tfMatricula);
            PromptSupport.setFontStyle(Font.BOLD, tfMatricula);

            this.tfNome = new JTextField();
            this.tfNome.setToolTipText("Insira seu nome aqui");
            PromptSupport.setPrompt("Nome", tfNome);
            PromptSupport.setFocusBehavior(PromptSupport.FocusBehavior.SHOW_PROMPT, tfNome);
            PromptSupport.setFontStyle(Font.BOLD, tfNome);

            this.tfCurso = new JTextField();
            this.tfCurso.setToolTipText("Insira seu curso aqui");
            PromptSupport.setPrompt("Curso", tfCurso);
            PromptSupport.setFocusBehavior(PromptSupport.FocusBehavior.SHOW_PROMPT, tfCurso);
            PromptSupport.setFontStyle(Font.BOLD, tfCurso);

            this.tfPeriodo = new JTextField();
            this.tfPeriodo.setToolTipText("Insira seu período aqui");
            PromptSupport.setPrompt("Período", tfPeriodo);
            PromptSupport.setFocusBehavior(PromptSupport.FocusBehavior.SHOW_PROMPT, tfPeriodo);
            PromptSupport.setFontStyle(Font.BOLD, tfPeriodo);

            btConfirmar.addActionListener(this);
            c2.add(tfMatricula);
            c2.add(tfNome);
            c2.add(tfCurso);
            c2.add(tfPeriodo);

            add(btConfirmar);

            add(BorderLayout.NORTH, c2);
            add(BorderLayout.SOUTH, btConfirmar);

        }

        public Academico getAcademico() {
            return academico;
        }

        @Override
        public void actionPerformed(ActionEvent e) {

            this.academico.setMatricula(tfMatricula.getText().toString());
            this.academico.setNome(tfNome.getText());
            this.academico.setCurso(tfCurso.getText());
            this.academico.setPeriodo(Integer.parseInt(tfPeriodo.getText()));
        }

    }

    public class Academico {

        private String matricula;
        private String nome;
        private String curso;
        private int periodo;

        public Academico() {
        }

        public Academico(String matricula, String nome, String curso, int periodo) {
            this.matricula = matricula;
            this.nome = nome;
            this.curso = curso;
            this.periodo = periodo;
        }

        public String getMatricula() {
            return matricula;
        }

        public void setMatricula(String matricula) {
            this.matricula = matricula;
        }

        public String getNome() {
            return nome;
        }

        public void setNome(String nome) {
            this.nome = nome;
        }

        public String getCurso() {
            return curso;
        }

        public void setCurso(String curso) {
            this.curso = curso;
        }

        public int getPeriodo() {
            return periodo;
        }

        public void setPeriodo(int periodo) {
            this.periodo = periodo;
        }
    }
}

答案 1 :(得分:-1)

我解决了一个新方法,并且Click事件的一部分也是错误的。

我没有改变任何学术课程。

<强>解决方案

班级框架

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

public class Frame extends JFrame implements ActionListener {

private static Academico novoAcademico;
private static FrameTemp frameTemporario;
private JTable tabela;
private static DefaultTableModel modelo;
private ArrayList<Academico> academicos;
private JButton btAdd, btAtualizar, btDelete;
private JPanel painel, painelGrid;
private BorderLayout borderLayout;
private GridLayout gridLayout;

public Frame(Academico academico) {
    this.setTitle("Acadêmicos Cadastrados");
    this.painel = new JPanel();
    this.painelGrid = new JPanel();

    borderLayout = new BorderLayout();
    gridLayout = new GridLayout(1, 3);
    setContentPane(painel);
    this.setLayout(borderLayout);

    painel.add(painelGrid);
    painelGrid.setLayout(gridLayout);

    this.modelo = new DefaultTableModel();
    this.tabela = new JTable(modelo);
    this.btAdd = new JButton("Insert");
    this.btAdd.setFont(new Font("Verdana", Font.PLAIN, 20));
    this.btAdd.setBackground(Color.BLACK);
    this.btAdd.setForeground(Color.WHITE);
    this.btAtualizar = new JButton("Update");
    this.btAtualizar.setFont(new Font("Verdana", Font.PLAIN, 20));
    this.btAtualizar.setBackground(Color.BLACK);
    this.btAtualizar.setForeground(Color.WHITE);
    this.btDelete = new JButton("Delete");
    this.btDelete.setFont(new Font("Verdana", Font.PLAIN, 20));
    this.btDelete.setBackground(Color.BLACK);
    this.btDelete.setForeground(Color.WHITE);

    this.modelo.addColumn("Matrícula");
    this.modelo.addColumn("Nome");
    this.modelo.addColumn("Curso");
    this.modelo.addColumn("Período");

    this.tabela.getColumnModel().getColumn(0).setPreferredWidth(20);
    this.tabela.getColumnModel().getColumn(1).setPreferredWidth(30);
    this.tabela.getColumnModel().getColumn(2).setPreferredWidth(50);
    this.tabela.getColumnModel().getColumn(3).setPreferredWidth(20);

    this.academicos = new ArrayList<>();

    this.academicos.add(new Academico("123", "Fredson", "Sistemas de Informação", 3));
    this.academicos.add(new Academico("234", "Vieira", "Ciência da Computação", 5));
    this.academicos.add(new Academico("345", "Costa", "Engenharia da Computação", 7));

    for (Academico a : this.academicos) {
        this.modelo.addRow(new Object[]{a.getMatricula(), a.getNome(), a.getCurso(), a.getPeriodo()});
    }

    this.painel.add(BorderLayout.NORTH, new JScrollPane(this.tabela));
    this.painel.add(BorderLayout.SOUTH, painelGrid);
    this.painelGrid.add(btAdd);
    this.painelGrid.add(btAtualizar);
    this.painelGrid.add(btDelete);

    this.btDelete.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            int dialog = JOptionPane.YES_NO_OPTION;

            int selRow = tabela.getSelectedRow();
            if (selRow != -1) {
                int resultado = JOptionPane.showConfirmDialog(null, "Deseja realmente excluir essa linha?", "Confirmação", dialog);

                if (resultado == 0) {
                    modelo.removeRow(selRow);
                    JOptionPane.showMessageDialog(null, "Registro excluído com sucesso!" + "\nTotal de registros existentes: " + modelo.getRowCount());
                }

            }
        }
    }
    );

    this.btAdd.addActionListener(this);

    this.pack();

    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    this.setVisible(true);
}

public static void main(String[] args) {
    new Frame(novoAcademico);
}

@Override
public void actionPerformed(ActionEvent e) {
    if (e.getSource() == btAdd) {

        frameTemporario = new FrameTemp();
        frameTemporario.setVisible(true);

    }
}

public static void addAcademico(Academico academico) {
    academico = frameTemporario.getAcademico();

    ArrayList<Academico> lista = new ArrayList<>();

    lista.add(new Academico(academico.getMatricula(), academico.getNome(), academico.getCurso(), academico.getPeriodo()));

    for (Academico a : lista) {
        System.out.println("Lista: " + lista.size());
        modelo.addRow(new Object[]{a.getMatricula(), a.getNome(), a.getCurso(), a.getPeriodo()});
        System.out.println(a.getMatricula() + "\n" + a.getNome() + "\n" + a.getCurso() + "\n" + a.getPeriodo());
    }

}

}

类FrameTemp

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import org.jdesktop.swingx.prompt.PromptSupport;

/**
 *
 * @author rafaelcarlos
 */
public class FrameTemp extends JFrame implements ActionListener {

private String title = "Adicionar novo";
private ArrayList<Academico> academicos;
private static Academico academico;
private JTextField tfMatricula, tfNome, tfCurso, tfPeriodo;
private JButton btConfirmar;

public FrameTemp() {
    this.setTitle(title);
    Container c = getContentPane();

    c.setLayout(new BorderLayout());

    Container c2 = new JPanel();
    c2.setLayout(new GridLayout(1, 4));
    academico = new Academico();
    academicos = new ArrayList<Academico>();

    this.btConfirmar = new JButton("Confirmar");
    this.tfMatricula = new JTextField();
    this.tfMatricula.setToolTipText("Insira sua matrícula aqui");
    PromptSupport.setPrompt("Matrícula", tfMatricula);
    PromptSupport.setFocusBehavior(PromptSupport.FocusBehavior.SHOW_PROMPT, tfMatricula);
    PromptSupport.setFontStyle(Font.BOLD, tfMatricula);

    this.tfNome = new JTextField();
    this.tfNome.setToolTipText("Insira seu nome aqui");
    PromptSupport.setPrompt("Nome", tfNome);
    PromptSupport.setFocusBehavior(PromptSupport.FocusBehavior.SHOW_PROMPT, tfNome);
    PromptSupport.setFontStyle(Font.BOLD, tfNome);

    this.tfCurso = new JTextField();
    this.tfCurso.setToolTipText("Insira seu curso aqui");
    PromptSupport.setPrompt("Curso", tfCurso);
    PromptSupport.setFocusBehavior(PromptSupport.FocusBehavior.SHOW_PROMPT, tfCurso);
    PromptSupport.setFontStyle(Font.BOLD, tfCurso);

    this.tfPeriodo = new JTextField();
    this.tfPeriodo.setToolTipText("Insira seu período aqui");
    PromptSupport.setPrompt("Período", tfPeriodo);
    PromptSupport.setFocusBehavior(PromptSupport.FocusBehavior.SHOW_PROMPT, tfPeriodo);
    PromptSupport.setFontStyle(Font.BOLD, tfPeriodo);

    btConfirmar.addActionListener(this);
    c2.add(tfMatricula);
    c2.add(tfNome);
    c2.add(tfCurso);
    c2.add(tfPeriodo);

    c.add(btConfirmar);

    c.add(BorderLayout.NORTH, c2);
    c.add(BorderLayout.SOUTH, btConfirmar);

    this.setVisible(true);
    this.setSize(500, 300);
    this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}

//Metodo que você vai usar para recuperar os dados na outra classe
public static Academico getAcademico() {
    return FrameTemp.academico;
}

@Override
public void actionPerformed(ActionEvent e) {

    this.academico.setMatricula(tfMatricula.getText());
    this.academico.setNome(tfNome.getText());
    this.academico.setCurso(tfCurso.getText());
    this.academico.setPeriodo(Integer.parseInt(tfPeriodo.getText()));
    ;
    Frame.addAcademico(academico);
    this.dispose();
}

}