当在 Java Swing 中更改列宽时,如何仅对 JTable 的下一列应用调整?
要仅对下一列应用调整,请使用 setAutoResizeMode 并设置模式。此处的模式将是 AUTO_RESIZE_NEXT_COLUMN。即使拖动任何列头进行调整大小,这也会允许你仅调整下一列。
我们先来看一个创建表的示例 -
示例
package my; import java.awt.Font; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.table.DefaultTableModel; public class SwingDemo { public static void main(String[] argv) throws Exception { DefaultTableModel tableModel = new DefaultTableModel(); JTable table = new JTable(tableModel); tableModel.addColumn("Technology"); tableModel.addColumn("BCA"); tableModel.addColumn("MCA"); tableModel.addColumn("Lectures"); // applying adjustments to the next column only table.setAutoResizeMode(JTable.AUTO_RESIZE_NEXT_COLUMN); tableModel.addRow(new Object[] { "F#", "Yes", "No", "20"}); tableModel.addRow(new Object[] { "Blockchain", "Yes", "No", "30"}); tableModel.addRow(new Object[] { "SharePoint", "Yes", "Yes", "25"}); tableModel.addRow(new Object[] { "AWS", "No", "Yes", "25"}); tableModel.addRow(new Object[] { "Python", "Yes", "No", "20"}); tableModel.addRow(new Object[] { "Scala", "Yes", "No", "30"}); tableModel.addRow(new Object[] { "Swift", "No", "Yes", "35"}); tableModel.addRow(new Object[] { "C#", "Yes", "Yes", "50"}); tableModel.addRow(new Object[] { "NodeJS", "No", "Yes", "40"}); tableModel.addRow(new Object[] { "MVC", "Yes", "No", "30"}); tableModel.addRow(new Object[] { "ASP.NET", "Yes", "Yes", "35"}); tableModel.addRow(new Object[] { "Java", "Yes", "No", "55"}); tableModel.addRow(new Object[] { "jQuery", "Yes", "Yes", "30"}); Font font = new Font("Verdana", Font.PLAIN, 12); table.setFont(font); JFrame frame = new JFrame(); frame.setSize(600, 400); frame.add(new JScrollPane(table)); frame.setVisible(true); } }
输出
现在,如果你要调整任何一列的大小(在这种情况下为 BCA),那么所有调整都将影响该列本身以及下一列(在这种情况下为 MCA) -
广告