如何使用 Java 禁止通过在 JTable 组件中拖动标题栏来调整列大小


让我们首先创建一个带行和列的表格 −

String data[][] = { {"Australia","5","1"},
   {"US","10","2"},
   {"Canada","9","3"},
   {"India","7","4"},
   {"Poland","2","5"},
   {"SriLanka","5","6"}
};
String col [] = {"Team","Selected Players","Rank"};
DefaultTableModel tableModel = new DefaultTableModel(data,col);
JTable table = new JTable(tableModel);

现在,我们将通过拖动标题栏使列不可调整大小 −

table.getTableHeader().setResizingAllowed(false);

以下是一个在 JTable 中通过拖动标题栏禁止调整列大小的示例:−

示例

package my;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRootPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class SwingDemo {
   public static void main(String[] argv) throws Exception {
      JFrame frame = new JFrame("Demo");
      JPanel panel = new JPanel();
      String data[][] = { {"Australia","5","1"},
         {"US","10","2"},
         {"Canada","9","3"},
         {"India","7","4"},
         {"Poland","2","5"},
         {"SriLanka","5","6"}
      };
      String col [] = {"Team","Selected Players","Rank"};
      DefaultTableModel tableModel = new DefaultTableModel(data,col);
      JTable table = new JTable(tableModel);
      table.getTableHeader().setResizingAllowed(false);
      Dimension dim = new Dimension(50,2);
      table.setIntercellSpacing(new Dimension(dim));
      JScrollPane scrollPane = new JScrollPane(table);
      panel.add(scrollPane);
      frame.add(panel);
      frame.setSize(600,400);
      frame.setUndecorated(true);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getRootPane().setWindowDecorationStyle(JRootPane.COLOR_CHOOSER_DIALOG);
      frame.setVisible(true);
   }
}

输出如下。你无法通过拖动表格标题栏来调整列的大小 −

输出

更新日期: 30-Jul-2019

97 次浏览

开启您的职业生涯生涯

完成课程后获得认证

开始
广告