简体   繁体   English

将数据插入数据库正在冻结我的应用程序

[英]Inserting data to database is freezing my app

I have got class with timer. 我上课了。 This class is adding new items for my Array of points. 这个类正在为我的Array点添加新项。 That points are moving and from a body of timer im repainting a panel to draw them in new positions. 这些点正在移动,并从计时器的主体重新绘制一个面板以在新的位置绘制它们。 Im connected to database sqlite. 我连接到数据库sqlite。 when im calling an insert function to add point to the table - apps freeze for 1s. 当我调用一个插入函数来添加点到表 - 应用程序冻结1秒。

I want to ask is there any way to not stoping drawing/repainting? 我想问有没有办法不停止绘画/重新绘画? i want that operation of inserting will be doing in background. 我希望插入操作将在后台进行。

any ideas? 有任何想法吗?

Ps: i heard about swing worker but idk is it suitable to my sitaution Ps:我听说过摇摆工作者但是idk适合我的情况

EDIT: 编辑:

class Generator{
    ChangeListener listener;
    ArrayList<String> s;
    JPanel p;
    Timer generatorTimer;
    MyDatabase b;


    public Generator(){
    this.s = new ArrayList<String>();
    this.b = new MyDatabase();
      generatorTimer = new Timer(40, new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent e) {
              addItem();     
              p.repaint();
      }
    });
    generatorTimer.start();
    }
    private void addItem(){
        String newString = new String("sampleText");
        s.add(newString);
        b.insert(newString);  //inserting new item do database
        listener.stateChanged(new ChangeEvent(this));
    }
    public void setPanel(JPanel p){
        this.p = p;
    }

    public ArrayList<String> getArray(){
        return s;
    }   
    public void addListener(ChangeListener list){
        this.listener = list;
    }
}

Can u give me example how to replace my Timer with a SwingWorker ? 你能举例说明如何用SwingWorker替换我的Timer吗?

Change your addItem method to something like this: 将addItem方法更改为以下内容:

private void addItem() {
    final String newString = new String("sampleText");
    s.add(newString);
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            // inserting new item to database
            b.insert(newString);
        }
    };
    new Thread(runnable).start();
    listener.stateChanged(new ChangeEvent(this));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM