简体   繁体   English

如何更改表格的列宽

[英]How to change column width of a table

For the following code, I am not able to set the column size to a custom size. 对于以下代码,我无法将列大小设置为自定义大小。 Why is it so?Also the first column is not being displayed. 为什么会这样呢?第一列也没有显示。

    import java.awt.BorderLayout;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.table.TableColumn;

public class Trial extends JFrame{
   public void create(){
     JPanel jp = new JPanel();
     String[] string = {" ", "A"};
     Object[][] data = {{"A", "0"},{"B", "3"},{"C","5"},{"D","-"}};
     JTable table = new JTable(data, string);     
     jp.setLayout(new GridLayout(2,0));   
     jp.add(table);

     table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
     TableColumn column = null;
     for (int i = 0; i < 2; i++) {
        column = table.getColumnModel().getColumn(i);
        column.setPreferredWidth(20);      //custom size
       }
     setLayout(new BorderLayout());
     add(jp);
   }

   public static void main(String [] a){
      Trial trial = new Trial();
      trial.setSize(300,300);
      trial.setVisible(true);
      trial.setDefaultCloseOperation(Trial.EXIT_ON_CLOSE);
      trial.create();
   }
}

You've got a couple of issues here. 您在这里遇到了几个问题。 First and foremost, Always initialize your JFrame from the Swing EDT as such: 首先, 始终从Swing EDT初始化JFrame,如下所示:

   public static void main(String[] a) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            Trial trial = new Trial();
            trial.setSize(300, 300);
            trial.setDefaultCloseOperation(Trial.EXIT_ON_CLOSE);
            trial.create();
         }
      });
   }

Failure to do so will lead to subtle errors. 否则会导致细微的错误。 Second: JTables like to exist within JScrollPanes. 第二:JTables喜欢存在于JScrollPanes中。 That's why you don't see the column headers: 这就是为什么看不到列标题的原因:

  JScrollPane pane = new JScrollPane();
  pane.setViewportView(table);
  jp.add(pane);

With the above done, I see your tiny little columns, each 20 pixels wide. 完成上述操作后,我将看到您的细小的小列,每列20像素宽。

When autoresize mode is set to off the column widths will not be adjusted at all when the table is layed out. 如果将自动调整大小模式设置为关闭,则在布置表格时将完全不调整列宽。 From JTable's doLayout() documentation: 从JTable的doLayout()文档中:

AUTO_RESIZE_OFF: Don't automatically adjust the column's widths at all. AUTO_RESIZE_OFF:完全不会自动调整列的宽度。 Use a horizontal scrollbar to accomodate the columns when their sum exceeds the width of the Viewport. 当列的总和超过视口的宽度时,请使用水平滚动条来容纳它们。 If the JTable is not enclosed in a JScrollPane this may leave parts of the table invisible. 如果JTable未包含在JScrollPane中,则可能会使表的某些部分不可见。

Try adding the JTable to a JScrollPane and then adding that to the panel. 尝试将JTable添加到JScrollPane ,然后将其添加到面板。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM