Set the size of JTextField fixed in a JPanel

懵懂的女人 提交于 2019-12-24 06:42:37

问题


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:


  1. It happens because you use BoxLayout,try to use FlowLayout which is default for JPanel or another.
  2. In next statement pnData.add(txtEventList, BorderLayout.CENTER); , BorderLayout.CENTER doesn't work, because you doesn't use BorderLayout for your panel.
  3. For fixing size of JTextField, use constructor JTextField(int cols).
  4. For your purposes use JTable as recommended by @AndrewThompson. Tutorial for table.
  5. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!