在JTable顶部添加按钮

时间:2016-05-10 13:12:00

标签: java swing jtable jpanel jbutton

如何在button之上添加返回JTable?我试过但没有运气。

public class viewMovie extends JPanel{

    static JFrame frame = new JFrame("View Movie");
    JTable table;

     public static void main(String[] args) {
            SwingUtilities.invokeLater(() -> {
                try {
                    createAndShowGui();
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            });
        }

     static void createAndShowGui() throws Exception  {
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.getContentPane().add(new viewMovie());
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        }

     public viewMovie() throws Exception
     {
         String sql="Select * from movie";
            DatabaseConnection db = new DatabaseConnection();
            Connection  conn =db.getConnection();
            PreparedStatement  ps = conn.prepareStatement(sql);
             ResultSet rs = ps.executeQuery();
             ResultSetMetaData rsmt= rs.getMetaData();
             int c= rsmt.getColumnCount();
             Vector column= new Vector(c);
             for(int i=1;i<=c;i++)
             {
                 column.add(rsmt.getColumnName(i));
             }
             Vector data = new Vector();
             Vector row=new Vector();
             while(rs.next())
             {
                 row=new Vector(c);
                 for(int i=1;i<=c;i++)
                 {
                     row.add(rs.getString(i));
                 }
                 data.add(row);
             }

             JButton back= new JButton("Back");
             JPanel topPanel = new JPanel(new GridLayout(1, 0, 3, 3));
                     topPanel.add(back);

                 JPanel panel= new JPanel();
                 table=new JTable(data,column);
             JScrollPane jsp = new JScrollPane(table);
                 panel.setLayout(new BorderLayout());
                 panel.add(jsp,BorderLayout.CENTER);
                 frame.setContentPane(panel);
                 frame.setVisible(true);

     } 

}

这是我得到的输出。

enter image description here

1 个答案:

答案 0 :(得分:2)

您忘记了一行代码,即将topPanel添加到面板JPanel的行:

panel.add(topPanel, BorderLayout.PAGE_START);

旁注:对于将来的问题,您需要让我们的代码可编辑和运行,这意味着摆脱不必要的依赖,例如数据库。对于上面的代码,数据库内容可以替换为:

JPanel panel = new JPanel();
Integer[][] data = { { 1, 2, 3 }, { 4, 5, 6 } };
String[] column = { "A", "B", "C" };

table = new JTable(data, column);

但实际上因为它只是一个简单的布局问题,所以即使是JTable也不是必需的。