我想将JTable添加到布局为空的JPanel中。JPanel包含其他组件。我必须在适当的位置添加JTable。


当前回答

不要使用空布局。学习使用LayoutManagers:

http://download.oracle.com/javase/tutorial/uiswing/layout/using.html

LayoutManagers允许您正确地处理窗口大小调整或动态组件计数。它们一开始可能看起来很吓人,但它们值得你努力去学习。

其他回答

不要使用空布局。学习使用LayoutManagers:

http://download.oracle.com/javase/tutorial/uiswing/layout/using.html

LayoutManagers允许您正确地处理窗口大小调整或动态组件计数。它们一开始可能看起来很吓人,但它们值得你努力去学习。

如果你使用空布局管理器,你总是需要设置一个组件的边界。 这就是你的问题所在。

你应该按照每个人的建议去做,使用一些布局管理器,它们可以节省时间。 去@jzd的帖子里看看教程吧。

享受吧,博罗。

this.setTitle("Sample");
        JPanel p = new JPanel(new BorderLayout());
        WindowEvent we = new WindowEvent(this, WindowEvent.WINDOW_CLOSED);
        this.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent we) {
                System.exit(0);
            }
        }); 
        // Create columns names
        String columnNames[] = { "FirstCol", "SecondCol",
                "ThirdCol", "FourthCol" };
        dataModel = new DefaultTableModel();
        for (int col = 0; col < columnNames.length; col++) {
            dataModel.addColumn(columnNames[col]);
        }
        // Create a new table instance
        table = new JTable(dataModel);
        table.setPreferredScrollableViewportSize(new Dimension(200, 120));
        table.setFillsViewportHeight(true);
        table.setShowGrid(true);
        table.setAutoscrolls(true);

        // Add the table to a scrolling pane
        scrollPane = new JScrollPane(table,
                JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        scrollPane.setPreferredSize(new Dimension(700, 700));
        JPanel jpResultPanel = new JPanel();
        jpResultPanel.setBorder(BorderFactory.createTitledBorder(
                BorderFactory.createEtchedBorder(), "Result",
                TitledBorder.CENTER, TitledBorder.TOP));
        jpResultPanel.add(scrollPane);
        add(jpResultPanel);
        pack();
        setSize(720, 720);
        setVisible(true);

试试这个。

您可以使用以下代码。将JTable添加到JPanel。

JPanel panel = new JPanel();
this.setContentPane(panel);
panel.setLayout(null);
String data[][] = {{"1.", "ABC"}, {"2.", "DEF"}, {"3.", "GHI" }};
String col[] = {"Sr. No", "Name"};
JTable table = new JTable(data,col);
table.setBounds(100, 100, 100, 80);
panel.add(table);
setVisible(true);
setSize(300,300);

JTable应该添加到JScrollPane中,而JScrollPane实际上应该添加到JPanel中。

JPanel应该有一些布局管理器。

如果你不关心组件大小的精度,你可以使用纯BorderLayout,并将其与FlowLayout和GridLayout结合起来。如果你需要精度-使用jgoodies FormLayout。

FormLayout是非常棘手的一个,但是您可以使用WindowBuilder(嵌入到Eclipse中)并查看它生成的代码。这可能看起来很复杂,但这只是一种无知。

祝你好运。