How to disable auto resizing for a JTable in Java?

Java 8Object Oriented ProgrammingProgramming

To disable auto resizing for a table in Java, set the setAutoResizeMode() to AUTO_RESIZE_OFF −

JTable table = new JTable(tableModel);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

The following is an example to disable auto resizing for a JTable in Java −

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.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
      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.INFORMATION_DIALOG);
      frame.setVisible(true);
   }
}

The output is as follows. Now, the table won’t get auto-resized on its own and would appear like this −

Now, to display the table columns completely, you can drag the column header manually. After that, the entire table would be visible as shown below −


raja
Published on 31-May-2019 14:39:38
Advertisements