将JScrollPane添加到JTable

时间:2013-12-01 13:56:47

标签: java swing jtable jscrollpane

我一直在研究这个问题,但似乎无法添加滚动窗格。我正在创建一个JFrame,在该帧中添加一个JTable,然后在for循环中更新单元格。但是我无法在没有崩溃的情况下添加JScrollPane。我也无法在没有崩溃的情况下声明列标题。任何想法都会受到赞赏。

 frame6.setIconImage(Toolkit.getDefaultToolkit().getImage("images\\iconimage.jpg"));
 frame6.pack();
 frame6.setResizable(false);
 frame6.setVisible(true);
 frame6.setSize(400,200);
 frame6.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

 Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
 int w = frame6.getSize().width;
 int h =  frame6.getSize().height;
 int x = (dim.width-w)/2;
 int y = (dim.height-h)/2;
 frame6.setLocation(x, y);

 JPanel btnPnl = new JPanel(new BorderLayout());
 JPanel topBtnPnl = new JPanel(new FlowLayout(FlowLayout.TRAILING));
 JPanel bottombtnPnl = new JPanel(new FlowLayout(FlowLayout.CENTER));

 JButton close = new JButton("Close");
 bottombtnPnl.add(close);

 btnPnl.add(topBtnPnl, BorderLayout.NORTH);
 btnPnl.add(bottombtnPnl, BorderLayout.CENTER);


defaultTableModel model = new DefaultTableModel(list.size(), 6);
JTable table = new JTable(model);
frame6.add(table, BorderLayout.NORTH);



JScrollPane jps = new JScrollPane();
table.add(jps);


table.setValueAt("FIRST NAME", 0,0);
table.setValueAt("LAST NAME", 0, 1);
table.setValueAt("CLUB", 0, 2);
table.setValueAt("POSITION", 0, 3);
table.setValueAt("AGE", 0, 4);
table.setValueAt("COUNTRY", 0, 5);

int j = 0;

for(i = 0; i < PlayerManager.list.size(); i++){

     if(list.get(i).getPosition().toUpperCase().equals(pPosition.toUpperCase()))
    {
    table.setValueAt(PlayerManager.list.get(i).getfName(), j+1, 0);
        table.setValueAt(PlayerManager.list.get(i).getlName(), j+1, 1);
    table.setValueAt(PlayerManager.list.get(i).getClub(), j+1, 2);
    table.setValueAt(PlayerManager.list.get(i).getPosition(), j+1, 3);
    table.setValueAt(PlayerManager.list.get(i).getAge(), j+1, 4);
    table.setValueAt(PlayerManager.list.get(i).getNationality(), j+1, 5);
    j++;
        }
    }

frame6.add(table, BorderLayout.CENTER);
frame6.add(btnPnl, BorderLayout.SOUTH);

frame6.setTitle("Player Table");


close.addActionListener(new ActionListener(){

    public void actionPerformed(ActionEvent e){
    frame6.setVisible(false);
    frame6.dispose();
}
 });

1 个答案:

答案 0 :(得分:0)

您必须将表格添加到scroolpane而不是反之亦然

    JScrollPane jps = new JScrollPane();
    jps.add(table);

而不是

    JScrollPane jps = new JScrollPane();
    table.add(jps);

并查看this。希望它有所帮助。