Java在表格中显示数据

时间:2018-11-30 12:09:10

标签: java intellij-idea

我是Java的新手,正在使用IntelliJ。本来我是C#开发人员。我有一些疑问,也许是简单的将数据显示到Forms应用程序中的表中。我有App类别,据我了解是我的表单类别,如下所示。单击btnLoadData时,数据显示在表格中,但是我没有看到要在btnLoadData.addActionListener中添加为Col1Col2的任何列名。表中也完全没有滚动。谁能告诉我我做错了什么或我想念什么。这似乎比在Visual Studio中更难:)

public class App {
    private JButton button_msg;
    private JPanel panelName;
    private JButton btnLoadData;
    private JTable JTable_Articles;

    public App() {
        button_msg.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JOptionPane.showConfirmDialog(null, "Hello");
            }
        });
        btnLoadData.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {

                try {
                    DefaultTableModel model = (DefaultTableModel)JTable_Articles.getModel();
                    String[] columnNames = { "Nummer", "Vater"};
                    ArrayList<Artikel> list= GetArtikelList();
                    Object[] data = new Object[2];
                    model.addColumn("Col1");
                    model.addColumn("Col2");

                    for (Artikel st : list) {
                        data[0] = st.nummer;
                        data[1] = st.vater;
                        model.addRow(data);
                    }

                } catch (Exception f) {
                    JOptionPane.showMessageDialog(null,f);
                }
            }
        });
    }

    public static void main(String[] args) {
        JFrame jf = new JFrame("App");
        jf.setContentPane(new App().panelName);
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jf.pack();
        jf.setVisible(true);
    }

    public ArrayList<Artikel> GetArtikelList() {

        ArrayList<Artikel> ArtikelList = new ArrayList<>();
        try {

            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
            String url="jdbc:sqlserver://localhost:1433;databaseName=MyDb;user=sa;password=XXX";
            Connection con = DriverManager.getConnection(url);
            String query = "SELECT * FROM MyTable";
            Statement st = con.createStatement();
            ResultSet rs = st.executeQuery(query);
            Artikel art;
            while(rs.next()){
                art = new Artikel(rs.getString("Nummer"), rs.getString("Vater"));
                ArtikelList.add(art);
            }

        } catch (Exception e) {
            JOptionPane.showMessageDialog(null,e);
        }

        return ArtikelList;
    }
}

0 个答案:

没有答案