我的JPanel出了问题。我用界面构建了一个html / css scraper。该接口有一个JTextArea,它使用刮刀完成的步骤进行更新,如#34;找到HTML"和#34;保存的文件成功"。我想在代码运行时将这些消息添加到JTextArea。一个简单的检查显示更新正在使用observerpattern,但所有消息都不会显示,直到所有代码完成。
来自可观察类的示例代码(触发100次):
private void addItem(String line, char type, String classOrId) {
String[] lineSplit = line.split(classOrId+"="+type);
lineSplit = lineSplit[1].split(""+type);
lineSplit = lineSplit[0].split(" ");
for (String a : lineSplit) {
if(classOrId == "id"){
if (!usedIds.contains(a)) {
usedIds.add(a);
}
}
else if(classOrId == "class"){
if (!usedClasses.contains(a)) {
usedClasses.add(a);
}
}
consoleText = consoleText + "Class \"" + a + "\" is found.";
setChanged();
notifyObservers();
}
}
来自观察者类的示例代码:
public class ScraperView extends JPanel implements Observer {
Scraper scraper;
public ScraperView(Scraper scraper){
this.scraper = scraper;
scraper.addObserver(this);
this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
refresh();
}
private void refresh() {
System.out.println("TrIGGER");
removeAll();
int removedClasses = scraper.getRemovedClasses();
int totalClasses = scraper.getTotalClasses();
JLabel classesText = new JLabel(" Total Classes: "+ Integer.toString(totalClasses));
JLabel removedClassesText = new JLabel(" Removed Classes: "+ Integer.toString(removedClasses));
this.add(classesText);
this.add(removedClassesText);
this.revalidate();
this.repaint();
}
@Override
public void update(Observable o, Object arg) {
refresh();
}
}
有没有办法等到jPanel更新?我注意到代码每次都被触发,但是没有更新..
答案 0 :(得分:1)
您应该查看SwingWorker类,它旨在同时更新UI时在线程中执行任务。
答案 1 :(得分:0)
您每次更新时都在创建和添加新的 JLabel ,这是一个坏主意,您应该创建一次标签,然后更新它们,您还应该确保在更新时更新它们您可以使用SwingUtilities.invokeLater(Runnable)
public class ScraperView extends JPanel implements Observer {
Scraper scraper;
JLabel classesText = new JLabel();
JLabel removedClassesText = new JLabel();
public ScraperView(Scraper scraper){
this.scraper = scraper;
scraper.addObserver(this);
this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
this.add(classesText);
this.add(removedClassesText);
refresh();
}
private void refresh() {
System.out.println("TrIGGER");
int removedClasses = scraper.getRemovedClasses();
int totalClasses = scraper.getTotalClasses();
classesText.setText(" Total Classes: "+ Integer.toString(totalClasses));
removedClassesText.setText(" Removed Classes: "+ Integer.toString(removedClasses));
}
@Override
public void update(Observable o, Object arg) {
SwingUtilities.invokeLater(this::refresh);
}
}