-4

I want to create button in my JFrame (view cars) that will show new JFrame with table. And I want to fill table with data from my MySQL database. When I start program, it works alright, but when I try to click on button that should show my JFrame with table, it show me error that "conn" is null. I'm relatively new in Java, so sorry if I have some stupid things in my code. Could you please simply explain what I have wrong and what I should change? MyJFrame

MyJFrame code:

public class MyJFrame {

    private JFrame frame;

    public static void main(String[] args) {
        String dbHost="localhost";
        String dbDatabase="cars";
        String dbUser = "root";
        String dbPassword = "";
        CarDAO carDAO = new CarDAO();
        ResultSet result = null;

        try {
            // register driver
            Class.forName("com.mysql.jdbc.Driver");
            // Make Connection Url
            String connectionUrl = "jdbc:mysql://" + dbHost
                        + "/" + dbDatabase
                        + "?user=" + dbUser
                        + "&password=" + dbPassword;
            //open Connection
            Connection conn = DriverManager.getConnection(connectionUrl);
            carDAO.setConn(conn);

            conn.close();
        }catch (ClassNotFoundException cnfe){
            throw new RuntimeException(cnfe);
        }catch (SQLException sqle) {
        throw new RuntimeException(sqle);
        }


        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    MyJFrame window = new MyJFrame();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }


    public MyJFrame() {
        initialize();
    }


    private void initialize() {
        frame = new JFrame();
        frame.setBounds(100, 100, 472, 346);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(null);

        JButton btnNewButton = new JButton("Create Car");
        btnNewButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                frame.dispose();
                CreateCar createCar = new CreateCar();
                createCar.setVisible(true);
            }
        });
        btnNewButton.setBounds(10, 125, 135, 46);
        frame.getContentPane().add(btnNewButton);

        JButton btnNewButton_1 = new JButton("Search Car For Sale");
        btnNewButton_1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
            }
        });
        btnNewButton_1.setBounds(10, 68, 135, 46);
        frame.getContentPane().add(btnNewButton_1);

        JButton btnNewButton_2 = new JButton("Update Entry");
        btnNewButton_2.setBounds(10, 182, 135, 46);
        frame.getContentPane().add(btnNewButton_2);

        JButton btnNewButton_4 = new JButton("Sold Car");
        btnNewButton_4.setBounds(10, 239, 135, 46);
        frame.getContentPane().add(btnNewButton_4);

        JButton btnNewButton_3 = new JButton("View Cars");
        btnNewButton_3.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                frame.dispose();
                ShowCars showCars = new ShowCars();
                showCars.setVisible(true);
            }
        });
        btnNewButton_3.setBounds(10, 11, 135, 46);
        frame.getContentPane().add(btnNewButton_3);

        JLabel lblNewLabel = new JLabel("Choose your option");
        lblNewLabel.setFont(new Font("Tahoma", Font.BOLD, 17));
        lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);
        lblNewLabel.setBounds(160, 11, 190, 46);
        frame.getContentPane().add(lblNewLabel);
    }
}

ShowCars class:

public class ShowCars extends JFrame {

    private JPanel contentPane;
    private JTable table;

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    ShowCars frame = new ShowCars();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public ShowCars() {
        CarDAO carDAO = new CarDAO();
        table = new JTable();
        carDAO.showCars(table);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 489, 400);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        JScrollPane scrollPane = new JScrollPane();
        scrollPane.setBounds(10, 11, 453, 339);
        contentPane.add(scrollPane);

        scrollPane.setViewportView(table);
    }
}

CarDAO class:

public class CarDAO {

    String type;
    int price;
    String date;
    int ID;
    static String sql;
    String year;
    String month;
    String day;
    String word;
    Connection conn;
    boolean show = false;
    static int option;
    Scanner input = new Scanner(System.in);
    Cars cars = new Cars();
    MyJFrame myJFrame = new MyJFrame();
    public void setConn (Connection Conn){
        this.conn = Conn;
    }
    public void showCars (JTable table){
        try{
            String sql = "select * from cars;";
            // prepare Statement
            PreparedStatement ps = conn.prepareStatement(sql);
            ResultSet rs = ps.executeQuery();
            table.setModel(DbUtils.resultSetToTableModel(rs));
        }catch (Exception e) {
            e.printStackTrace();
        }
        option = 2;
    }
}

error message:

java.lang.NullPointerException
    at databaseProject.CarDAO.showCars(CarDAO.java:64)
    at databaseProject.ShowCars.<init>(ShowCars.java:41)
    at databaseProject.MyJFrame$4.actionPerformed(MyJFrame.java:120)
    at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
    at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
    at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
    at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
    at java.awt.Component.processMouseEvent(Unknown Source)
    at javax.swing.JComponent.processMouseEvent(Unknown Source)
    at java.awt.Component.processEvent(Unknown Source)
    at java.awt.Container.processEvent(Unknown Source)
    at java.awt.Component.dispatchEventImpl(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Window.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    at java.awt.EventQueue.access$500(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue$4.run(Unknown Source)
    at java.awt.EventQueue$4.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)
Lenob
  • 9
  • 6

1 Answers1

-1
    CarDAO carDAO = new CarDAO();
    table = new JTable();
    carDAO.showCars(table);

You forget to set the connection.

Edit: Basically your program is very "mixed up". To summarise:

  1. You should never pass gui elements like JTable into the DAO.
  2. The gui code should not know anything about database connections.
  3. Your DAO is really a mixup of DAO and DTO. The values you expect to return from a DAO method should be "packed" into a "dumb" DTO object (google it).
  4. Even better would be to hide the DAO from GUI, by using a Facade/Service layer (google that, too), where you also could deal with getting connection, and transactions.

A good place to start reading could be https://en.wikipedia.org/wiki/Multitier_architecture

When you have understood the basics you can have a framework (like Spring Boot) handle all the "boilerplate" code for you, providing you with a connection pool, transaction handling and so on.

jon martin solaas
  • 459
  • 1
  • 4
  • 14
  • Is it necessary to have connection in every frame? Why I need to have connection in "ShowCars" class when I only refer to method in another class where connection is already set? – Lenob Apr 03 '16 at 06:31
  • @Lenob: Because `conn`is null when the statement `PreparedStatement ps = conn.prepareStatement(sql);` is executed. Other connections in other parts of the program are not known to your dao. See the edited answer above for details. – jon martin solaas Apr 03 '16 at 11:03