问题
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:
回答1:
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.
回答2:
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);
来源:https://stackoverflow.com/questions/59369704/how-can-i-move-a-table-downward-in-java