簡體   English   中英

java swing更新框架中的內容

[英]java swing updating content in frame

我目前正在使用Java開發示例應用程序。 在使用Java之前,我還沒有真正使用過Java,因此請多多包涵。 我已經設置了應用程序,因此正在輪詢mysql數據庫以獲取信息。 我現在遇到的問題與更新框架中的內容有關。 目前,我可以根據每個請求打開一個包含內容的新窗口。 這是由於我對Java的了解有限。 我想在不創建新窗口的情況下更新框架中的內容。 這是代碼:

// 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) {}
        }
    }
}

您可以將框架及其組件放在一個類中,並提供該類方法來更改組件。 因此,一個類具有對框架及其組件的引用。

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

然后,您可以編寫這樣的方法:

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

而不是在每次更新時都創建新標簽。 據我所知,當您在JComponents上調用這些set方法時,它們將自動更新。

從數據庫顯示數據的一種更好的方法是使用JTable。 閱讀Swing教程中有關如何使用表的部分

現在,無論何時要替換數據,都可以簡單地創建一個新的DefaultTableModel。 對於ResultSet中的每一行,請使用DefaultTableModel.addRow(..)方法將數據添加到模型中。 閱讀完ResultSet后,只需使用以下方法將模型添加到表中:

table.setModel(...);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM