如何在GUI上显示jdbc表的结果?

时间:2014-05-08 20:31:38

标签: java sql user-interface jdbc

嘿伙计们我试图从我创建的jdbc表中获取数据并在我创建的GUI上显示它们。这是一个显示电影名称的程序。我的表由7列组成,它们是: MovieID, title, genre, year, mpaaRating, directors, company。我的工作只是展示movieID标题年份和导演。我创建的第一个GUI界面包含三个按钮,每个按钮都会将您带到不同的界面,并且它们可以正常工作。我的主界面代码是:

public class MovieGUI extends JFrame implements ActionListener {
 private static final int FRAME_WIDTH = 600;
 private static final int FRAME_HEIGHT= 600;
 private static final int FRAME_X_ORIGIN = 200;
 private static final int FRAME_Y_ORIGIN = 50;
 private static final String dbPrefix = "xxxxx";
 private static final String netID = "xxxxx";
 private static final String hostName = "xxxxx";
 private static final String databaseURL = "jdbc:mysql://"+hostName+"/"+dbPrefix+netID;
 private static final String password = "xxxxx";
 private Connection connection = null;
 private Statement statement = null;
 private ResultSet resultSet = null;
 private JLabel movies[] = new JLabel[20];
 private JLabel promptName;
 private JTextField fieldName;
 private JButton browseMoviesButton, findNameButton, findRatingButton;

 public MovieGUI(){
     setTitle("Menu");
     setResizable(false);
     setSize(FRAME_WIDTH, FRAME_HEIGHT);
     setLocation(FRAME_X_ORIGIN, FRAME_Y_ORIGIN);

     Container contentPane = getContentPane();
     contentPane.setLayout(null);
     contentPane.setBackground(Color.red);

     promptName = new JLabel();
     promptName.setText("Movie Rating Services");
     promptName.setBounds(250, 35, 150, 100);
     contentPane.add(promptName);

     browseMoviesButton = new JButton("Browse Movies");
     browseMoviesButton.setBounds(240,120,150,50);
     contentPane.add(browseMoviesButton);
     browseMoviesButton.addActionListener(this);

     findNameButton = new JButton("Find movies given name");
     findNameButton.setBounds(230,220,180, 80);
     contentPane.add(findNameButton);
     findNameButton.addActionListener(this);

     findRatingButton = new JButton("Find movie by rating");
     findRatingButton.setBounds(230,350,180, 80);
     contentPane.add(findRatingButton);
     findRatingButton.addActionListener(this);

     setDefaultCloseOperation(EXIT_ON_CLOSE);
 }

 public static void main(String args[]){
        MovieGUI obj = new MovieGUI();
        try{
            //connects to database
            Class.forName("com.mysql.jdbc.Driver");
            System.out.println("databaseURL =" + databaseURL);
            obj.connection = (Connection) DriverManager.getConnection(databaseURL, netID, password);
            System.out.println("Connection Established");
            obj.statement = (Statement) obj.connection.createStatement();
            String sql;
        }
        catch(SQLException e){
            System.out.println("command did not go through");
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
     MovieGUI frameObj = new MovieGUI();
     frameObj.setVisible(true);



     }

 public void actionPerformed (ActionEvent event){
     if (event.getSource() instanceof JButton){

            FindName nameObj = new FindName();
            BrowseMovies browseObj = new BrowseMovies();
            FindRating ratingObj = new FindRating();
            JButton clickedButton = (JButton) event.getSource();
            JRootPane rootPane = clickedButton.getRootPane();
            JFrame frame = (JFrame) rootPane.getParent();
            String buttonText = clickedButton.getText();
            if (buttonText.equals("Browse Movies")){
                 browseObj.setVisible(true);
                 frame.setVisible(false);
                 try {
                    statement = (Statement) connection.createStatement();
                    String sql;
                    sql = "SELECT movieID, title, year, directors FROM MOVIE";
                    resultSet = statement.executeQuery(sql);
                    int columns = resultSet.getMetaData().getColumnCount();
                    StringBuilder message = new StringBuilder();
                    while (resultSet.next()) {                          
                        for (int i = 0; i < movies.length; i++){
                            for (int j = 1; j <= columns; j++) {                        
                                message.append(resultSet.getString(j) + "\t\t");    
                        }//end nested for loop
                        message.append("\n");
                        movies[i].setText(message.toString());
                    }//end for loop

                    }//end while loop
                    } catch (SQLException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }//end catch

                     for (int i = 0; i < movies.length; i++){
                         movies[i].setBounds(150,60,300,50);
                         browseObj.add(movies[i]);

                     }

             }
            else if(buttonText.equals("Find movies given name")){
                nameObj.setVisible(true);
                frame.setVisible(false);

            }
            else if (buttonText.equals("Find movie by rating")){
                ratingObj.setVisible(true);
                frame.setVisible(false);
            }
     }

 }




}

当我点击浏览电影按钮时,它应该转到下一个界面并在我的表格中显示电影的上述属性,其中有20个。

我的BrowseMovies界面代码是:

public class BrowseMovies extends JFrame {
 private static final int FRAME_WIDTH = 600;
 private static final int FRAME_HEIGHT= 600;
 private static final int FRAME_X_ORIGIN = 200;
 private static final int FRAME_Y_ORIGIN = 50;

 private JLabel promptName;
 public BrowseMovies(){
     setTitle("Movie List");
     setResizable(false);
     setSize(FRAME_WIDTH, FRAME_HEIGHT);
     setLocation(FRAME_X_ORIGIN, FRAME_Y_ORIGIN);

     Container contentPane = getContentPane();
     contentPane.setLayout(null);
     contentPane.setBackground(Color.blue);

     promptName = new JLabel();
     promptName.setText("Movie Rating Services -- Browse Movies");
     promptName.setBounds(200, 35, 250, 100);
     contentPane.add(promptName);




 }//GUI constructor
}

我遇到的问题是browseMovies界面只显示promptName而没有其他内容,我在控制台中收到一个很长的错误。错误是:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at project5.MovieGUI.actionPerformed(MovieGUI.java:111)
    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$200(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$1.doIntersectionPrivilege(Unknown Source)
    at java.security.ProtectionDomain$1.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$1.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)

我不知道出了什么问题。我猜这个问题是在actionPerformed方法的try块中的某个地方,但我似乎无法找到它。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

您必须使用实际的JLabel对象初始化数组。 下面给出了第一次迭代中的空指针

public class TestSwing {
    public static void main(String[] args) {
        JLabel movies[] = new JLabel[20];
        for (int j = 0; j < movies.length; j++) {
            System.out.println("Loop Counter : " + j);
            movies[j].setText("Counter : " + j);
        }
    }
}

你必须做类似的事情

public class TestSwing {
        public static void main(String[] args) {
            JLabel movies[] = new JLabel[20];
            for (int j = 0; j < movies.length; j++) {
                System.out.println("Loop Counter : " + j);
                movies[j] = new JLabel(); // initialize your JLable
                movies[j].setText("Counter : " + j);
            }
        }
    }

注意:这只是代码的摘录,我删除了一些代码只是为了更好地澄清它