将表添加到java swing

时间:2013-02-18 14:17:05

标签: java swing layout jtable jpanel

我已经有一个面板,我已经添加了按钮和文本区域。现在我需要在它下面显示一个表格。面板的布局是AbsoluteLayout,如果我使用以下方法给表膨胀它显示为空

        String data[][] = { { "vinod", "BCA", "A" }, { "Raju", "MCA", "b" },
                { "Ranjan", "MBA", "c" }, { "Rinku", "BCA", "d" } };

        String col[] = { "Name", "Course", "Grade" };
        JTable table = new JTable(data, col);
        table.setLocation(25,343);
        panel.add(table, BorderLayout.CENTER);

然而,当我使用setbounds时,表显示没问题,但它占用的空间超出了它的要求,并且这些行不显示在空白区域,看起来很糟糕。有没有人知道如何只设置一个表的x,y位置并留下其余的定位(宽度和高度以适应所需的)

String data[][] = { { "vinod", "BCA", "A" }, { "Raju", "MCA", "b" },
        { "Ranjan", "MBA", "c" }, { "Rinku", "BCA", "d" } };

String col[] = { "Name", "Course", "Grade" };
JTable table = new JTable(data, col);
table.setBounds(25,343,122,122);
panel.add(table, BorderLayout.CENTER);

2 个答案:

答案 0 :(得分:5)

答案 1 :(得分:0)

JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new BorderLayout());
frame.add (Box.createVerticalStrut(343), BorderLayout.NORTH);
frame.add (Box.createHorizontalStrut(25), BorderLayout.WEST);
frame.add (new JTable (5, 5), BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);