我无法更新JtextArea的文本来自数据库,我在运行时手动插入数据库的表格中,
我真正需要的是显示在同一帧中运行时插入的记录 System.out.println("") //this statement works fine but
textArea.insert("", 0);
鉴于是我的代码
public class Test extends JFrame {
JPanel menuBarPan ,eastNav,westNav,mPanel ,ctrPanel;
JTextArea textArea;
JTextField textField;
String userName;
Connection conn;
ResultSet rs;
PreparedStatement stmt;
public Test(String userName , Connection con){
this.userName = userName;
this.conn = con;
setSize(900,670);
setLayout(new BorderLayout());
textArea = new JTextArea();
textArea.setEditable(false);
textArea.setText("kop");
try {
stmt = conn.prepareStatement("select * from mydb.tabel");
rs = stmt.executeQuery();
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null,ex.getMessage());
}
mPanel =new MyPanel();
add(mPanel,BorderLayout.CENTER);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[]args){
Runnable runnable =new Runnable(){
@Override
public void run(){
Connect co=new Connect();
Test obj=new Test("SUL" ,co.conn);
java.util.Timer timer=new java.util.Timer();
timer.schedule(obj.new TimerClass(), 1000, 1000);
}
};
SwingUtilities.invokeLater(runnable);
}
public class MyPanel extends JPanel{
MyPanel(){
setLayout(new BorderLayout());
ctrPanel = new JPanel();
ctrPanel.setBorder(BorderFactory.createEtchedBorder());
JScrollPane jsp=new JScrollPane(textArea);
jsp.setBorder(BorderFactory.createEmptyBorder());
textField = new JTextField();
add(ctrPanel,BorderLayout.WEST);
add(jsp,BorderLayout.CENTER);
add(textField,BorderLayout.SOUTH);
}
}
public class TimerClass extends TimerTask{
@Override
public void run() {
Runnable runnable =new Runnable(){int replyLength=0;
@Override
public void run() {
try {
stmt = conn.prepareStatement("select * from mydb.tabel");
rs = stmt.executeQuery();
textArea = new JTextArea();
textArea.setEditable(false);
textArea.setText("kop");
while(rs.next()){
System.out.println(rs.getString("rep"));
String reply = rs.getString("rep");
System.out.println("rep : "+reply);
textArea.insert(reply, 0);
replyLength=reply.length();
textArea.insert("\n",replyLength);
}
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null,ex.getMessage());
}
mPanel = new MyPanel();
}
};
SwingUtilities.invokeLater(runnable);
}
}
}
答案 0 :(得分:0)
//确保新文本可见,即使在那里也是如此 //是文本区域中的一个选择。
textArea.setCaretPosition(textArea.getDocument().getLength());
如果在上述选项之后显示相同的结果,那么, 唯一的原因可能是你传递的字符串可能是null。 否则罚款。