gpt4 book ai didi

java - 无法更新从数据库获取的 JtextArea 文本同时手动插入(运行时)

转载 作者:太空宇宙 更新时间:2023-11-04 12:20:14 27 4
gpt4 key购买 nike

我无法更新从数据库获取的 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);
}
}

}

最佳答案

//确保新文本可见,即使有//是文本区域中的一个选择。

    textArea.setCaretPosition(textArea.getDocument().getLength());

如果即使在上述选项之后仍然显示相同的结果,唯一的原因可能是您传递的字符串可能为空。否则没问题。

关于java - 无法更新从数据库获取的 JtextArea 文本同时手动插入(运行时),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38929342/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com