1

Is it possible to move a table downward in Java. I tried setBorder, setLocation, ... but it didn't work. What should I do?

JLabel label = new JLabel("Enter proper data: ");
label.setBounds(0, 0, 120, 50);
frame.add(label);
JButton btn = new JButton("Click");
btn.setBounds(100, 300, 80, 50);
frame.add(btn);
String data [][] = new String [6][4];
String column[]={"No.","Player 1","Player 2","Strategy"};         
JTable table = new JTable(data, column);
JScrollPane sp=new JScrollPane(table);
frame.add(sp);          
frame.setSize(300,400);
frame.setVisible(true); 

Please look at this image:

enter image description here

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433

2 Answers2

2

enter image description here

Looks good for a BorderLayout for the outer panel (outlined in blue). The big red label goes in the PAGE_START and the (scroll pane of the) table goes in the CENTER.

Put the button in a panel with a FlowLayout (centered), the panel with the red outline, in the PAGE_END of the border layout. Done.

All extra height (if the user makes the GUI bigger) will be given to the table.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
1

I changed the code based on @AndrewThompson suggestion and result was good.

    JFrame frame = new JFrame("Play");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JPanel outerPanel = new JPanel(new BorderLayout());
    JPanel topPanel = new JPanel(new BorderLayout());
    JLabel label = new JLabel("Enter proper data: ");
    JButton btn = new JButton("Click");
    String data [][] = new String [100][4];
    String column[]={"No.","Player 1","Player 2","Strategy"};
    JTable table = new JTable(data, column);
    JScrollPane sp=new JScrollPane(table);
    topPanel.add(label, BorderLayout.PAGE_START);
    topPanel.add(sp, BorderLayout.CENTER);
    topPanel.add(btn, BorderLayout.PAGE_END);
    outerPanel.add(topPanel);
    frame.add(outerPanel);
    frame.pack();
    frame.setLocationRelativeTo(null);  
    frame.setVisible(true);

enter image description here

  • 1
    1) `frame.pack();` Nice! 2) `frame.setLocationRelativeTo(null);` I prefer `setLocationByPlatform(true);`. See [this answer](https://stackoverflow.com/a/7143398/418556) for demo code and screenshots of the effect. – Andrew Thompson Dec 17 '19 at 11:19