eclipse中的JTable没有显示列名

时间:2016-04-06 07:58:26

标签: java eclipse jtable jscrollpane

当我手动添加数据时,JTable都没有将列名显示为标题,也没有滚动条。

JTable和JScrollPane的代码:

 private JPanel contentPane = new JPanel();
    Object[] title = {"ISBN", "Name", "Author", "Shelf No", "Row No", "Col No"};
    DefaultTableModel dtm = new DefaultTableModel();
    dtm.setColumnIdentifiers(title);
    table = new JTable(dtm);
    table.setBounds(23, 55, 435, 217);
    table.setModel(dtm);
    JScrollPane scroll = new JScrollPane(table, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    table.setForeground(Color.gray);
    table.setRowHeight(30);
    contentPane.add(scroll);
    contentPane.add(table);
    Object[] row = {"hi", "2", "3", "5", "r", "we" };

ActionListener在表中添加数据:

    btnSearch.addActionListener(
            new ActionListener() {
                public void actionPerformed(ActionEvent e) {

                    dtm.addRow(row);

                }
            });

如下图所示,我没有这些列(标题)和滚动条。

picture

3 个答案:

答案 0 :(得分:1)

您不是将JTable添加到滚动窗格,而是添加到contentpane。试试这个:

contentPane.add(scroll);
scroll.add(table); //instead of contentPane.add(table)

答案 1 :(得分:1)

JTableJScrollPane列标题为displayed,所以这是正确的:

contentPane.add(scroll);

不要立即用表格替换滚动窗格:

//contentPane.add(table);

而不是setBounds(),按照建议here覆盖getPreferredScrollableViewportSize()。由于JPanel的默认布局为FlowLayout,因此表格将保持固定大小。考虑GridLayout,这将允许显示在反映大小的封闭框架时反映更改。

JPanel contentPane = new JPanel(new GridLayout());

答案 2 :(得分:1)

对您的代码进行以下更改

#include <stdio.h>
#include <libpq-fe.h>
#include <string>

int     main() {
PGconn          *conn;
PGresult        *res;
int             rec_count;
int             row;
int             col;



    conn = PQconnectdb("dbname=ljdata host=localhost ser=dataman                        password=postgre");

    if (PQstatus(conn) == CONNECTION_BAD) {
            puts("We were unable to connect to the database");
            exit(0);
    }

   res = PQexec(conn,
            "update people set phonenumber=\'5055559999\' where id=3");

     res = PQexec(conn,
             "select lastname,firstname,phonenumber from people order by id");

     if (PQresultStatus(res) != PGRES_TUPLES_OK) {
             puts("We did not get any data!");
             exit(0);
     }

     rec_count = PQntuples(res);

    printf("We received %d records.\n", rec_count);
     puts("==========================");

     for (row=0; row<rec_count; row++) {
             for (col=0; col<3; col++) {
                     printf("%s\t", PQgetvalue(res, row, col));
             }
             puts("");
     }

     puts("==========================");

     PQclear(res);

     PQfinish(conn);

     return 0;
     }

Otu-Put:

enter image description here