如何在 Java Swing 中仅当更改任何一列的宽度时,将调整应用到 JTable 的最后一列?
若仅对最后一列应用调整,请使用 setAutoResizeMode 并设置模式。此处的模式应为 AUTO_RESIZE_LAST_COLUMN。这将允许你仅调整最后一列,即使任何一个列标题被拖动来调整大小。
我们首先来看一个在 Java 中创建表的示例 −
示例
package my; import java.awt.Color; 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 last column only table.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_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)将保持不变 −
广告