簡體   English   中英

如何在JScrollPane中放置JTable?

[英]How can I place a JTable inside a JScrollPane?

這是我的代碼:

    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標頭?

我該如何解決?

默認情況下, JFrame使用BorderLayout在每個段(北,南,中,西,東)中僅添加單個組件。 請看一下如何使用BorderLayout

記得:

  • 不要僅使用setBounds()方法將其移交給Layout Manager來設置其用途的組件的大小和位置。
  • JButton使用ActionListener而不是MouseListener
  • 絕對避免使用絕對布局的null布局,並且必須指定該容器中每個組件的大小和位置。 絕對定位的一個缺點是,在調整頂層容器的大小時,它無法很好地進行調整。 它還不能很好地適應用戶和系統之間的差異,例如不同的字體大小和區域設置。

進行一些更改后再試一次:

  • 無需在contentPane中添加JTable ,因為它已經在JScrollPane添加了
  • 只需在JFrame的中心添加JScrollPane
  • 根據需要在北部或南部添加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);

快照:

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM