问题
for school I am working on a Java GUI program to store some administrative data.
Now I want to display eventdata from my DB (mysql) into a JPanel with use of a JTextField, my problem is I can't get the size of the JTextField fixed as it always takes up a lot of place (see picture)
Picture: http://postimg.org/image/5pcklo5n1/
Here's my code, anyone some tips? (I am new to java):
public void editEvent() {
JFrame frEventEdit = new JFrame ("Event Edit Menu");
frEventEdit.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frEventEdit.setVisible(true);
frEventEdit.setSize(700, 500);
//JPanel for displaying data
JPanel pnData = new JPanel();
pnData.setLayout(new BoxLayout(pnData, BoxLayout.PAGE_AXIS));
pnData.add(Box.createRigidArea(new Dimension(0,5)));
pnData.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
pnData.setAutoscrolls(true);
Statement stmt;
try {
stmt = mySql.createStatement();
ResultSet rs = stmt.executeQuery("SELECT name, date, time, type, address, representative FROM events " ) ;
while (rs.next() == true){
System.out.println(rs.getString("name")+" "+rs.getString("date")+" "+rs.getString("time")+" "+rs.getString("type")+" "+rs.getString("address")+" "+rs.getString("representative"));
final JTextField txtEventList = new JTextField(rs.getString("name")+" "+rs.getString("date")+" "+rs.getString("time")+" "+rs.getString("type")+" "+rs.getString("address")+" "+rs.getString("representative"));
pnData.add(txtEventList, BorderLayout.CENTER);
}
} catch (SQLException e) {
e.printStackTrace();
}
JScrollPane scroller = new JScrollPane(pnData);
frEventEdit.add(scroller);
frEventEdit.setLocationRelativeTo(null);
}
Thanks in advance
回答1:
- It happens because you use
BoxLayout
,try to useFlowLayout
which is default forJPanel
or another. - In next statement
pnData.add(txtEventList, BorderLayout.CENTER);
,BorderLayout.CENTER
doesn't work, because you doesn't useBorderLayout
for your panel. - For fixing size of
JTextField
, use constructorJTextField(int cols)
. - For your purposes use
JTable
as recommended by @AndrewThompson. Tutorial for table. call
frEventEdit.setVisible(true);
at the end of construction or like next:SwingUtilities.invokeLater(new Runnable() { @Override public void run() { frEventEdit.setVisible(true); } });
来源:https://stackoverflow.com/questions/20243956/set-the-size-of-jtextfield-fixed-in-a-jpanel