How do I fix my Problem with ComboBoxes in Java Swing?

29 views Asked by At

As the title says I can't fill my Comboboxes.

Ok, so I'm making a program for a football club for managing events and players. The idea is that I have a SQLite Database and a Java Swing Program with 2 ComboBoxes, one for the Type (Players or Events) and the other for the (The Player or Event Names). When the Type Combobox Selected Item changes it should reload all the items from the second ComboBox i.e. make a Database connection and get either all Player or all Event names.

Here is my code

javax.swing.*;
import java.awt.*;
import java.sql.*;
import java.text.MessageFormat;

public class MainWindow extends JFrame {
    private JPanel window;
    private JComboBox<String> comboBox2;
    private JButton deleteButton;
    private JComboBox<String> type = new JComboBox<>(new String[] {"Spieler", "Events"});

    private JButton addButton;
    private JButton changeButton;

    String selected = (String) type.getSelectedItem();

    Util util = new Util();

    MainWindow() throws SQLException{
        setConfigurations();
        reloadSelection(selected);
        type.addActionListener(e -> {
            try {reloadSelection((selected));}
            catch (SQLException ex) {throw new RuntimeException(ex);}

        });
        addButton.addActionListener(e -> System.out.println("not yet implemented"));
        deleteButton.addActionListener(e -> System.out.println("not yet implemented"));
        changeButton.addActionListener(e -> System.out.println("not yet implemented"));
    }

    private void  reloadSelection(String selected) throws SQLException {
        Connection c = util.getConnection();
        Statement stmt = c.createStatement();
        String[] arr = new String[0];
        String query;
        System.out.println(selected);
        if(selected.equals("Spieler")) {
            query = "SELECT firstName, lastName FROM Players;";
            ResultSet rs = stmt.executeQuery(query);
            while(rs.next()) {
                String name = rs.getString("firstName") + rs.getString("lastName");
                arr = name.split("\n");
            }
        }
        /*else if(selected.equals("Events")) {
            query = "SELECT eventName FROM Events;";
        } */
        comboBox2.setModel(new DefaultComboBoxModel<>(arr));
        util.closeConnection(c);
    }
    private void setConfigurations() {
        setContentPane(window);
        setName("LineUp");
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setSize(350, 175);
        setMaximumSize(new Dimension(350, 175));
        setMinimumSize(new Dimension(350, 175));
    }

}

This theoretically works but returns me this: enter image description here

It also says that I overewrite code with

private JComboBox<String> type = new JComboBox<>(new String[] {"Spieler", "Events"});

But when I put the decleration in the Configuration Function it outputs:

Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.equals(Object)" because "selected" is null

Which is understandable because in the beginning it's null and so i can't make comparisons.

Can you help me fix this?

I wanted it to reload the second Combobox when I changed the selected Item of the first combobox

1

There are 1 answers

0
MadProgrammer On

I'm pretty sure that...

String name = rs.getString("firstName") + rs.getString("lastName");
arr = name.split("\n");

is never going to do what you want it to do. Apart from the fact that it's very unlikely that name will contain \n, you're assigning a new value to arr on each iteration, so at best, you'd get the last row.

Instead, I'd recommend using a List of some kind instead. List has a toArray method which you can use to feed the results to the DefaultComboBoxModel.

I would also recommend taking a look at try-with-resources and Using Prepared Statements (as a consideration of best practices).

Something like...

private void reloadSelection(String selected) throws SQLException {
    if ("Spieler".equals(selected)) {
        List<String> rows = new ArrayList<>(32);
        try (Connection c = util.getConnection(); 
                PreparedStatement stmt = c.prepareStatement("SELECT firstName, lastName FROM Players"); 
                ResultSet rs = stmt.executeQuery()) {
            while (rs.next()) {
                String name = rs.getString("firstName") + " " + rs.getString("lastName");
                rows.add(name.trim());
            }
        }
        comboBox2.setModel(new DefaultComboBoxModel<>(rows.toArray(new String[rows.size()])));
    }
}

would likely produce more desirable results.

Also beware, creating a Connection is typically an expensive operation, instead, if you can, create it once at the start of the app and close it when the app closes.