如何将JTable放在JScrollPane中?

时间:2014-05-30 22:14:34

标签: java swing user-interface jtable

这是我的代码:

    String col[] = {"No","Name","Capacity"};
    final DefaultTableModel tablemodel = new DefaultTableModel(col,0);      

    Container contentPane = this.getContentPane();
    JTable table = new JTable(tablemodel);
    table.setBounds(414, 39, 294, 281);
    contentPane.add(table);
    contentPane.add(new JScrollPane(table));

    JButton btnCreateTheMovie = new JButton("Create the movie theater");        
    btnCreateTheMovie.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
            movietheater.addMovieTheater(addtheaterID.getText(), Integer.parseInt(addtheater_capacity.getText()));
            try {
                write_movie_theater = new PrintWriter(new FileOutputStream(new File("d:/movietheater.txt"),true));
            } catch (FileNotFoundException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            };  

                int x = movietheater.movietheater_array.size()-1;
                i++;
                String ID = movietheater.movietheater_array.get(x).getID();
                int capacity = movietheater.movietheater_array.get(x).getCapacity();

                Object[] data = {i,ID,capacity};
                tablemodel.addRow(data);                    
        }
    });
    btnCreateTheMovie.setBounds(75, 192, 166, 23);
    contentPane.add(btnCreateTheMovie,BorderLayout.NORTH);

我运行了这段代码,但JTtable不可见。如何将JScrollpane添加到JList? 我怎样才能看到jtable标题?

我该如何解决?

1 个答案:

答案 0 :(得分:2)

默认情况下,

JFrame使用BorderLayout,在每个细分(北,南,中,西,东)中仅添加单个组件。请查看How to Use BorderLayout

记住:

  • 请勿使用setBounds()方法将其交给布局管理器,以设置组件的大小和位置。
  • JButton
  • 使用ActionListener代替MouseListener
  • 完全避免使用绝对定位null布局,您必须指定该容器中每个组件的大小和位置。绝对定位的一个缺点是在调整顶层容器大小时它不能很好地调整。它也不能很好地适应用户和系统之间的差异,例如不同的字体大小和区域设置。

进行一些更改后再试一次:

  • 无需在contentPane中添加JTable,因为它已添加到JScrollPane
  • 只需在JScrollPane
  • 的中心添加JFrame即可
  • 根据需要在北方或南方添加JButton

示例代码:

String col[] = { "No", "Name", "Capacity" };
DefaultTableModel tablemodel = new DefaultTableModel(col, 0);

Container contentPane = this.getContentPane();
JTable table = new JTable(tablemodel);
contentPane.add(new JScrollPane(table));

JButton btnCreateTheMovie = new JButton("Create the movie theater");
contentPane.add(btnCreateTheMovie, BorderLayout.NORTH);

快照:

enter image description here