Set width in JTable with 1 column

In the code below, how do I get table1 to be only as wide as the text in it?

import javax.swing.*;
import javax.swing.table.DefaultTableModel;

import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

/**
 * ThreeTablePanel
 */
public class ThreeTablePanel extends JPanel {
    
	private final static String TABLE1 =  "Table1";
    private final static String TABLE2 =  "Table2";
    private final static String TABLE3 =  "Table3";

    private JPanel centerPanel;
    
    private JTable table1;
    private JTable table2;
    private JTable  table3;

    
	private String[] table1ColumnArray = {"Fruit"};

	private Object[][]  table1DataArray = { 
			{"Apple"}, 
			{"Orange"}, 
			{"Lemon"}, 
			{"Lime"}, 
	};

	private String[] table2ColumnArray = {"Longer"};

	private Object[][]  table2DataArray = { 
			{"AppleAppleAppleAppleAppleAppleAppleApple"}, 
			{"OrangeOrangeOrangeOrangeOrangeOrangeOrangeOrange"}, 
			{"LemonLemonLemonLemonLemonLemonLemonLemonLemon"}, 
			{"LimeLimeLimeLimeLimeLimeLimeLimeLimeLime"}, 
	};
			
    /**
     * constructor
     */
    public ThreeTablePanel() {
        
    	super();
        
        setLayout();
    }

    public void setLayout() {

		DefaultTableModel defaultTableModel1 = new DefaultTableModel(table1DataArray, table1ColumnArray);
		DefaultTableModel defaultTableModel2 = new DefaultTableModel(table2DataArray, table2ColumnArray);
		
		// layout
		SpringLayout springLayout = new SpringLayout();
        centerPanel = new JPanel (springLayout);
        // table 1
        table1 = new JTable(defaultTableModel1);
        JScrollPane table1ScrollPane = new JScrollPane(table1);
        table1.setFillsViewportHeight(true);
        JPanel table1Panel = new JPanel(new BorderLayout());
        
        table1Panel.add(new JLabel(TABLE1), BorderLayout.PAGE_START);
        table1Panel.add(table1ScrollPane, BorderLayout.CENTER);

        centerPanel.add(table1Panel);

		// adjust constraints (ie position component)
		springLayout.putConstraint(SpringLayout.WEST, table1Panel, 5, SpringLayout.WEST, centerPanel);
		springLayout.putConstraint(SpringLayout.NORTH, table1Panel, 10, SpringLayout.NORTH, centerPanel);

        // table 2
        table2 = new JTable(defaultTableModel2);
        JScrollPane tables2ScrollPane = new JScrollPane(table2);
        table2.setFillsViewportHeight(true);
        JPanel table2Panel = new JPanel(new BorderLayout());
        table2Panel.add(new JLabel(TABLE2), BorderLayout.PAGE_START);
        table2Panel.add(tables2ScrollPane, BorderLayout.CENTER);

        centerPanel.add(table2Panel);
        
		// adjust constraints (ie position component)
        springLayout.putConstraint(SpringLayout.WEST, table2Panel, 5, SpringLayout.EAST, table1Panel);
		springLayout.putConstraint(SpringLayout.NORTH, table2Panel, 0, SpringLayout.NORTH, table1Panel);
		
        // table 3
        table3 = new JTable();
        JScrollPane table3ScrollPane = new JScrollPane(table3);
        table3.setFillsViewportHeight(true);
        JPanel table3Panel = new JPanel(new BorderLayout());
        table3Panel.add(new JLabel(TABLE3), BorderLayout.PAGE_START);
        table3Panel.add(table3ScrollPane, BorderLayout.CENTER);

        centerPanel.add(table3Panel);
        
		// adjust constraints (ie position component)
        springLayout.putConstraint(SpringLayout.WEST, table3Panel, 5, SpringLayout.EAST, table2Panel);
		springLayout.putConstraint(SpringLayout.NORTH, table3Panel, 0, SpringLayout.NORTH, table2Panel);

		// set constraints for center panel
		springLayout.putConstraint(SpringLayout.EAST, centerPanel, 5, SpringLayout.EAST, table3Panel);
		springLayout.putConstraint(SpringLayout.SOUTH, centerPanel, 10, SpringLayout.SOUTH, table3Panel);
		
        add(centerPanel, BorderLayout.CENTER);

    }

    /**
	 *
	 * @param args
	 */
	public static void main(String[] args) {

		try{
			UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
		}
		catch (Exception e){
			e.printStackTrace();
		}

		final JFrame frame = new JFrame();
		final ThreeTablePanel threeTablePanel = new ThreeTablePanel();
		frame.add(threeTablePanel, BorderLayout.CENTER);
		frame.setTitle("ThreeTablePanel");
//		frame.setPreferredSize(new Dimension(500, 500));
		frame.addWindowListener(new WindowAdapter(){
			@Override
			public void windowClosing(WindowEvent e) {
			}
		});

		frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		frame.setLocation(300, 200);
		frame.pack();
		frame.setVisible(true);

	}

}

Open in new window

LVL 1
allelopathAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

CEHJCommented:
Try the following:
    public void setLayout() {
	DefaultTableModel defaultTableModel1 = new DefaultTableModel(table1DataArray,
		table1ColumnArray);
	DefaultTableModel defaultTableModel2 = new DefaultTableModel(table2DataArray,
		table2ColumnArray);

	// layout
	SpringLayout springLayout = new SpringLayout();
	centerPanel = new JPanel(springLayout);
	// table 1
	table1 = new JTable(defaultTableModel1);

	JScrollPane table1ScrollPane = new JScrollPane(table1);
	table1.setFillsViewportHeight(true);

	JPanel table1Panel = new JPanel(new BorderLayout());

	table1Panel.add(new JLabel(TABLE1), BorderLayout.PAGE_START);
	table1Panel.add(table1ScrollPane, BorderLayout.CENTER);

	centerPanel.add(table1Panel);

	// adjust constraints (ie position component)
	springLayout.putConstraint(SpringLayout.WEST, table1Panel, 5,
		SpringLayout.WEST, centerPanel);
	springLayout.putConstraint(SpringLayout.NORTH, table1Panel, 10,
		SpringLayout.NORTH, centerPanel);

	// table 2
	table2 = new JTable(defaultTableModel2);

	JScrollPane tables2ScrollPane = new JScrollPane(table2);
	table2.setFillsViewportHeight(true);

	JPanel table2Panel = new JPanel(new BorderLayout());
	table2Panel.add(new JLabel(TABLE2), BorderLayout.PAGE_START);
	table2Panel.add(tables2ScrollPane, BorderLayout.CENTER);

	centerPanel.add(table2Panel);

	// adjust constraints (ie position component)
	springLayout.putConstraint(SpringLayout.WEST, table2Panel, 5,
		SpringLayout.EAST, table1Panel);
	springLayout.putConstraint(SpringLayout.NORTH, table2Panel, 0,
		SpringLayout.NORTH, table1Panel);

	// table 3
	table3 = new JTable();

	JScrollPane table3ScrollPane = new JScrollPane(table3);
	table3.setFillsViewportHeight(true);

	JPanel table3Panel = new JPanel(new BorderLayout());
	table3Panel.add(new JLabel(TABLE3), BorderLayout.PAGE_START);
	table3Panel.add(table3ScrollPane, BorderLayout.CENTER);

	centerPanel.add(table3Panel);

	// adjust constraints (ie position component)
	springLayout.putConstraint(SpringLayout.WEST, table3Panel, 5,
		SpringLayout.EAST, table2Panel);
	springLayout.putConstraint(SpringLayout.NORTH, table3Panel, 0,
		SpringLayout.NORTH, table2Panel);

	// set constraints for center panel
	springLayout.putConstraint(SpringLayout.EAST, centerPanel, 5,
		SpringLayout.EAST, table3Panel);
	springLayout.putConstraint(SpringLayout.SOUTH, centerPanel, 10,
		SpringLayout.SOUTH, table3Panel);

	add(centerPanel, BorderLayout.CENTER);

	// Pack the first table's sole column
	table1.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); 
	int prefWidth = packColumn(table1, 0, 5);

	Dimension d = table1Panel.getPreferredSize();
	table1Panel.setPreferredSize(new Dimension(prefWidth, d.height));
    }


    // Sets the preferred width of the visible column specified by vColIndex. The column 
    // will be just wide enough to show the column head and the widest cell in the column. 
    // margin pixels are added to the left and right 
    // (resulting in an additional width of 2*margin pixels). 
    public int packColumn(JTable table, int vColIndex, int margin) {
	TableModel model = table.getModel();
	DefaultTableColumnModel colModel = (DefaultTableColumnModel) table.getColumnModel();
	TableColumn col = colModel.getColumn(vColIndex);
	int width = 0;

	// Get width of column header 
	TableCellRenderer renderer = col.getHeaderRenderer();

	if (renderer == null) {
	    renderer = table.getTableHeader().getDefaultRenderer();
	}

	Component comp = renderer.getTableCellRendererComponent(table,
		col.getHeaderValue(), false, false, 0, 0);
	width = comp.getPreferredSize().width;
	System.out.printf("Pref width is %d\n", width);

	// Get maximum width of column data 
	for (int r = 0; r < table.getRowCount(); r++) {
	    renderer = table.getCellRenderer(r, vColIndex);
	    comp = renderer.getTableCellRendererComponent(table,
		    table.getValueAt(r, vColIndex), false, false, r, vColIndex);
	    width = Math.max(width, comp.getPreferredSize().width);
	}

	// Add margin 
	width += (2 * margin);
	// Set the width 
		System.out.printf("Setting pref width to %d\n", width);

	col.setPreferredWidth(width);
	return width;
    }

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
allelopathAuthor Commented:
Thanks!
CEHJCommented:
:-)
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Editors IDEs

From novice to tech pro — start learning today.