views:

66

answers:

2

I'm currently working on a sample application in java. I haven't really used java for much more than hello world before so please bear with me. I've set my application up so It's polling a mysql database for information. The issue I have now has to do with updating the content in the frame. Currently I have it opening a new window with the content upon every request. This is due to my limited knowledge of java. I'd like to update the content within the frame without creating a new window. here's the code:

// Import the swing and AWT classes needed
import java.awt.EventQueue;
import java.awt.FlowLayout;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.BoxLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.*;
import java.awt.Component;
import java.awt.Container;
import java.util.*;
import java.awt.event.*;
import java.util.Timer;
import java.util.TimerTask;
/**
 * Basic Swing example.
 */
public class client extends JPanel {

    public static void main(String[] args) {

        // Make sure all Swing/AWT instantiations and accesses are done on the
                // Create a JFrame, which is a Window with "decorations", i.e. 
                // title, border and close-button
                JFrame f = new JFrame("Densebrain Test Client");

                // Set a simple Layout Manager that arranges the contained 
                // Components
                f.setLayout(new FlowLayout());

                // Add some Components
                f.add(new JLabel("Hello, world!"));
                f.add(new JButton("Press me!"));
                // "Pack" the window, making it "just big enough".
                f.pack();

                // Set the default close operation for the window, or else the 
                // program won't exit when clicking close button
                //  (The default is HIDE_ON_CLOSE, which just makes the window
                //  invisible, and thus doesn't exit the app)
                f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

                // Set the visibility as true, thereby displaying it
                f.setVisible(true);

int delay = 0;   // delay for 5 sec.
int period = 5000;  // repeat every sec.
Timer timer = new Timer();

    timer.scheduleAtFixedRate(new TimerTask() {
        public void run() {
            runn();
        }
    }, delay, period);
        //runn();
    }
    public static void runn() {
         Connection con = null;
         Statement stmt = null;
         ResultSet rs = null;
        try {
          Class.forName("com.mysql.jdbc.Driver").newInstance();
          con = DriverManager.getConnection("jdbc:mysql://localhost:3306/densebrain",
            "root", "");

          if(!con.isClosed())
        {
            System.out.println("Successfully connected to " +
              "MySQL server using TCP/IP...");
            stmt = con.createStatement();
            try {
                rs = stmt.executeQuery( "SELECT * FROM posts" );
                try {
                    JFrame f = new JFrame("POSTS");

                    f.setLayout(new GridLayout(40,1));
                    //pane = f.getContentPane();
                    //getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
                    while ( rs.next() ) {
                        int numColumns = rs.getMetaData().getColumnCount();
                        for ( int i = 1 ; i <= numColumns ; i++ ) {
                           // Column numbers start at 1.
                           // Also there are many methods on the result set to return
                           //  the column as a particular type. Refer to the Sun documentation
                           //  for the list of valid conversions.
                           System.out.println( "COLUMN " + i + " = " + rs.getObject(i) );
                            switch(i)
                            {
                                case 1: 
                                break;
                                case 2: f.add(new JLabel("NAME = " + rs.getObject(i)));
                                break;
                                case 3: f.add(new JLabel("CONTENT = " + rs.getObject(i)));
                                break;
                                case 4: f.add(new JLabel("CREATED = " + rs.getObject(i)));
                                break;
                            }

                        }
                        f.add(new JLabel("*********"));
                    }
                f.pack();

                // Set the default close operation for the window, or else the 
                // program won't exit when clicking close button
                //  (The default is HIDE_ON_CLOSE, which just makes the window
                //  invisible, and thus doesn't exit the app)
                f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

                // Set the visibility as true, thereby displaying it
                f.setVisible(true);
                } finally {
                    try { rs.close(); } catch (SQLException ignore) { /* Propagate the original exception instead of this one that you may want just logged */ }
                }
            } finally {
                try { stmt.close(); } catch (SQLException ignore) { /* Propagate the original exception instead of this one that you may want just logged */ }
            }
        }

        } catch(Exception e) {
          System.err.println("Exception: " + e.getMessage());
        } finally {
          try {
            if(con != null)
              con.close();
          } catch(SQLException e) {}
        }
    }
}
A: 

You could put the frame with it's components in a class and give that class methods to change the components. So a class that has a reference to the frame and it's components.

JFrame thisframe
JLabel thislabel = new JLabel("somedeafaulttext");
// etc.

Then you could write a method like this:

void updateText(String text){
thisLabel.setText(text);
}  

in stead of creating new Labels on each update. As far as I know when you invoke these set methods on JComponents they will automatically update.

Erik1984
A: 

A better way to display data from a database is to use a JTable. Read the section from the Swing tutorial on How to Use Tables.

Now whenever you want to replace the data you can simple create a new DefaultTableModel. For each row in the ResultSet you use the DefaultTableModel.addRow(..) method to add the data to the model. When you are finished reading the ResultSet you just add the model to the table using:

table.setModel(...);
camickr