我正在创建一个ui,其中有两个JTextField,我可以从文本文件中读取数据 JTextField1.But数据不会更新到JTextField2,除非i 在JTextField1.Please指南中输入一个数字
这是我的代码:
public class Cc extends JFrame
{
public Cc()
{
JPanel panel = new JPanel();
getContentPane().add(panel);
final JTextField field = new JTextField(10);
panel.add(field);
try{
InputStream ips=new FileInputStream("test.txt");
InputStreamReader ipsr=new InputStreamReader(ips);
BufferedReader br=new BufferedReader(ipsr);
String line;
while ((line=br.readLine())!=null){
field.setText(line);
}
br.close();
}
catch (Exception e){
e.printStackTrace();
}
final JTextField field1 = new JTextField(10);
panel.add(field1);
field.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void changedUpdate(DocumentEvent e) {
updateLabel(e);
}
@Override
public void insertUpdate(DocumentEvent e) {
updateLabel(e);
}
@Override
public void removeUpdate(DocumentEvent e) {
updateLabel(e);
}
private void updateLabel(DocumentEvent e) {
String text = field.getText();
String text1 = field1.getText();
if (!text.isEmpty()) {
int p = Integer.parseInt(text);
int i = (p + 1);
String s = String.valueOf(i);
field1.setText(s);
} else {
field1.setText(null);
}
}
});
((AbstractDocument) field.getDocument()).setDocumentFilter(new DocumentFilter() {
@Override
public void insertString(FilterBypass fb, int off, String str, AttributeSet attr)
throws BadLocationException {
fb.insertString(off, str.replaceAll("\\D++", ""), attr); // remove non- digits
}
@Override
public void replace(FilterBypass fb, int off, int len, String str, AttributeSet attr)
throws BadLocationException {
fb.replace(off, len, str.replaceAll("\\D++", ""), attr); // remove non-digits
}
});
}
public static void main(String[] args)
{
Cc c = new Cc();
c.setDefaultCloseOperation(EXIT_ON_CLOSE);
c.pack();
c.setVisible(true);
}
}
答案 0 :(得分:0)
1)你为什么宣称field1为final? 2)编写SwingUtilities.updateComponentTreeUI(面板);将setText设置为field1后,这将刷新UI以反映新文本
答案 1 :(得分:0)
在field1.setText()
之后尝试panel.repaint()