Amarnath Amarnath - 14 days ago 5
Java Question

Not able to display 2 JTable's horizontally in swing

I need to display 2

JTable
's along x-axis. I am able to display them vertically (Y-axis.) This is what so far I have done:

Displaying Two tables.

But I want to display tables like the following,

enter image description here

Here is my code:

tableA = new JTable(data, colNames);
tableB = new JTable(data, colNames);

JLabel labelA = new JLabel("Table-A");
JLabel labelB = new JLabel("Table-B");

JButton bt_copy = new JButton("Copy");

Container c = frame.getContentPane();

c.setLayout(new BoxLayout(c, BoxLayout.Y_AXIS));

c.add(labelA);
c.add(tableA.getTableHeader());
c.add(tableA);

c.add(labelB);
c.add(tableB.getTableHeader());
c.add(tableB);

c.add(bt_copy);


When I changed Y-axis in
c.setLayout(new BoxLayout(c, BoxLayout.Y_AXIS));
to X-axis. I really got a bad GUI view.

Answer

Something like this ??

Layout

JTable leftTable = new JTable();
JTable rightTable = new JTable();

addButton = new JButton("Add >>");
removeButton = new JButton("<< Remove");

setLayout(new GridBagLayout());

// Prepare the buttons panel...
JPanel pnlActions = new JPanel(new GridBagLayout());
pnlActions.setBorder(new LineBorder(Color.RED));
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 1;
gbc.anchor = GridBagConstraints.SOUTH;
gbc.weighty = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
pnlActions.add(addButton, gbc);
gbc.weighty = 0;
gbc.gridy++;
pnlActions.add(removeButton, gbc);

// Prepare the main layout
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 0.33;
gbc.fill = GridBagConstraints.BOTH;
gbc.weighty = 1;

add(new JScrollPane(leftTable), gbc);
gbc.gridx = 2;
add(new JScrollPane(rightTable), gbc);

gbc.gridx = 1;
gbc.gridy++;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weighty = 0;
add(pnlActions, gbc);
Comments