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


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

Let us first see an example to create a table −

Example

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

Output

Now, if you will resize any of the columns (in this case, BCA), then all the adjustments would affect the column itself as well as the next column (in this case, MCA) −

Updated on: 30-Jul-2019

105 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements