Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Displaying JList

Tags:

java

swing

again I am having problems with JList in displaying data from mysql database, I used the code given below but it is not displaying anything on screen..

JFrame f8 = new JFrame("Schedule");
f8.setVisible(true);
f8.setSize(1000, 1000);
JPanel jpa1 = new JPanel(new GridBagLayout());

String query = "SELECT * FROM Location";
DefaultListModel model = new DefaultListModel();
DefaultListModel model1 = new DefaultListModel();
try {
    Class.forName("oracle.jdbc.driver.OracleDriver");
    Statement stmt = null;
    ResultSet rs;
    Connection conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1/SPL", "root", "PWD");
    stmt = (Statement) conn.createStatement();
    rs = stmt.executeQuery(query);
    while (rs.next()) {
        String stadium = rs.getString("Stadium");
        String city = rs.getString("City");
        model.addElement(stadium);
        model1.addElement(city);
    }
    JList list = new JList(model);
    JList list1 = new JList(model1);
    f8.add(jpa1);
    jpa1.add(list);
    list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
    list.setLayoutOrientation(JList.HORIZONTAL_WRAP);
    list.setVisibleRowCount(1);
    JScrollPane listScroller = new JScrollPane(list);
} catch (SQLException e) {
    System.out.println("Message   : " + e.getMessage());
}

can you tell me please where am I WRONG?

like image 878
Rohan Singh Dhaka Avatar asked Jun 02 '26 12:06

Rohan Singh Dhaka


1 Answers

It's difficult to say what the problem is based on the snippet of code, not to mention a bit of unformatted code that is difficult to read, but...

  • You add one list to a JPanel but then add the same list to a JScrollPane and ignore the JScrollPane.
  • You're using GridBagLayout without any GridBagConstraints
  • You're doing a lot of JDBC code on the Swing event thread which threatens to lock this thread up.
  • You create one JList, list1, but don't add it to anything.

You should consider:

  • Testing your database code outside of a GUI. Divide the problem to conquer it else you will have too many variables that can effect your results making it difficult to know what's causing what.
  • placing debug statements in your code or use a debugger to first find out where the errors are.
  • Posting only well formatted code when asking for volunteers to help. It's hard enough to understand someone else's code that you should strive not to make it any more difficult. We greatly appreciate the effort!
like image 126
Hovercraft Full Of Eels Avatar answered Jun 04 '26 02:06

Hovercraft Full Of Eels