How to apply adjustments to the last column of a JTable only, when the width of any column is changed in Java Swing?


To apply adjustments to the last column only, use the setAutoResizeMode and set the mode. The mode here would be AUTO_RESIZE_LAST_COLUMN. This will allow you to adjust only the last columns even if any of the column header is dragged to resize.

Let us first see an example to create a table in Java −

Example

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);
   }
}

Output

Now, if you will resize any of the columns (we are resizing Technology column here), then all the adjustments would affect the column itself as well as only the last column. The other 2 columns (BCA and MCA) will remain intact −

Updated on: 30-Jul-2019

201 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements