表格标题未显示在表格中

时间:2019-12-27 10:04:46

标签: java swing jtable layout-manager jscrollpane

我想做一个计分板。我正在使用表来显示数据。数据将显示,但表头将不显示。我已经检查了其他文章,并且也输入了JScrollPane

import javax.swing.*;

public class Table {

    JFrame car;

    Table() {
        car = new JFrame();

        car.setTitle("Career");
        car.setSize(500, 500);
        car.setVisible(true);
        car.setLayout(null);

        String[] column = {"No.", "User Name", "Total Score"};
        String row[][] = {{"101", "Amit", "670000"},
        {"102", "Jai", "780000"},
        {"101", "Sachin", "700000"}};

        JTable jt = new JTable(row, column);
        jt.setBounds(20, 100, 225, 200);
        jt.setRowHeight(25);
        JScrollPane sp = new JScrollPane(jt);
        sp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        car.add(sp);
        car.add(jt);
    }

    public static void main(String[] args) {
        new Table();
    }
}

在其他网站上,我没有看到任何缺少的代码。 有什么问题吗?

2 个答案:

答案 0 :(得分:3)

  1. 删除此语句:car.add(jt);。该表位于滚动窗格中,并且该滚动窗格已添加到GUI
  2. 还删除car.setLayout(null);jt.setBounds(20,100,225,200);。空布局会弄乱很多事情,包括滚动窗格的工作方式。
  3. 在添加所有组件后调用setVisible,并调用pack()
  4. 需要进一步更改,BNI。

结果

enter image description here

import javax.swing.*;

public class Table {

    JFrame car;

    Table() {
        car = new JFrame();

        car.setTitle("Career");
        // this is just a guess. Add components then pack()
        //car.setSize(500, 500);
        //car.setLayout(null);

        String[] column = {"No.", "User Name", "Total Score"};
        String row[][] = {{"101", "Amit", "670000"},
        {"102", "Jai", "780000"},
        {"101", "Sachin", "700000"}};

        JTable jt = new JTable(row, column);
        //jt.setBounds(20, 100, 225, 200);
        jt.setRowHeight(25);
        JScrollPane sp = new JScrollPane(jt);
        sp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        car.add(sp);
        //car.add(jt);
        car.pack();
        // this statement should be last, immediately after pack()
        car.setVisible(true);
    }

    public static void main(String[] args) {
        new Table();
    }
}

答案 1 :(得分:-2)

我找到了我想要的另一种方式。

import javax.swing.*;

public class Table {

    JFrame car;

    Table() {
        car = new JFrame();
        car.setTitle("Career");
        car.setSize(500, 500);
        car.setVisible(true);
        car.setLayout(null);

        String[] column = {"No.", "User Name", "Total Score"};
        String row[][] = {{"101", "Amit", "670000"},
        {"102", "Jai", "780000"},
        {"101", "Sachin", "700000"}};

        JTable jt = new JTable(row, column);
        jt.setRowHeight(25);
        JScrollPane sp = new JScrollPane(jt);
        sp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        sp.setBounds(20,100,225,200);
        car.add(sp);
    }

    public static void main(String[] args) {
        new Table();
    }
}