【问题标题】:I am not getting names of column我没有得到列的名称
【发布时间】:2012-12-05 10:55:07
【问题描述】:

我在JPanel 中放置了一个JTable,但是当我显示时,我看到的是表格内容,而不是列名。

public class Neww extends JPanel
{
    Connection conn = null;
    Statement st;
    DefaultTableModel model = new DefaultTableModel(new Object[][] {
        { " ", " " },
        { " ", " " },
        { " ", " " },
        { " ", " " },
        { " ", " " },
        { " ", " " }
    }, new Object[] {
        "ItemName",
        "No of items"
    });

    JTable table = new JTable(model);
    TableColumn ItemName = table.getColumnModel().getColumn(0);
    JComboBox comboBox = new JComboBox();
    Neww()
    {
        this.setLayout(new FlowLayout(FlowLayout.CENTER));
        this.add(table);

        comboBox.addItem("Spoon");
        comboBox.addItem("Plate");
        comboBox.addItem("Mixer");
        comboBox.addItem("Glass");
        ItemName.setCellEditor(new DefaultCellEditor(comboBox));
    }
}

【问题讨论】:

    标签: java swing jtable jpanel jtableheader


    【解决方案1】:

    有两种方法

    • (正确的方式)必须将JTable 放入JScrollPane,然后JTableHeader 可见

    • JTable 获取JTableHeader(将JPanels LayoutManager 更改为BorderLayout)并放入NORTH area in JPanel

    【讨论】:

      【解决方案2】:

      1) 将您的 JTable 包裹在 JScrollPane 中。像这样:

      JTable table=...;
      
      JPanel container = new JPanel();
      
      JScrollPane jsp=new JScrollPane(table);
      
      container.add(jsp);
      

      2) 使用getTableHeader() 并将其添加到需要的位置(但通常位于北方):

      ...
      
      JTableHeader header = table.getTableHeader();
      
      JPanel container = new JPanel(new BorderLayout());
      
      // Add header at NORTH position
      container.add(header, BorderLayout.NORTH);
      
      //Add table below header
      container.add(table, BorderLayout.CENTER);
      

      【讨论】:

        【解决方案3】:

        以下语句在您的代码中造成问题。

         this.add(table);
        

        添加表格时使用滚动窗格。

         add(new JScrollPane(table));
        

        我们为什么要使用JScrollPane

        正如@OscarRyz 在此comment. 中所述

        它放入 JScrollPane 顶部组件(或顶部 视图或类似的东西被命名)当没有顶部组件时 JTable 显得无头。这是设计使然。

        编辑:也可以查看answer了解更多详情。

        【讨论】:

          猜你喜欢
          • 2013-09-23
          • 2014-05-06
          • 2012-07-27
          • 2013-01-21
          • 1970-01-01
          • 2023-04-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多