小编Ian*_*Ian的帖子

即使使用SwingWorker,Java GUI也会冻结

我正在尝试使用SwingWorker执行冗长的任务并使用结果更新JLabel:

button.addActionListener(new ActionListener() {

    @Override
    public void actionPerformed(ActionEvent arg0) {
        new SwingWorker<String, Void>() {

            @Override
            protected String doInBackground() throws Exception {
                return doCalculation();
            }

            protected void done() {
                try {
                    label.setText(get());
                } catch (InterruptedException e) {
                    System.out.println("thread was interrupted");
                } catch (ExecutionException e) {
                    System.out.println("there was an ExecutionException");
                }
            }

        }.execute();

    }

});
Run Code Online (Sandbox Code Playgroud)

我可以随意点击按钮多次,Gui将保持响应,直到两个线程完成,此时Gui在线程运行时冻结.如果我一次只运行一个线程,则仍会出现此问题.

如果有人能指出我是否错误地使用了SwingWorker,或者是否有其他我不知道的问题,我会很高兴.谢谢你的时间.伊恩

编辑

doCalculation()只是耗费时间:

private String doCalculation() {
    for (int i = 0; i < 10000000; i++) {
        Math.pow(3.14, i);
    }
    return threads++ + "";
}
Run Code Online (Sandbox Code Playgroud)

java swing multithreading swingworker

6
推荐指数
1
解决办法
2369
查看次数

宽度和高度相等的视图

我想在视图中做的是有一个textview,在它的右边,有另一个自定义视图X,其高度与textview相同,并且width = height:

+---------------------+---+
|A flexible string    | X |
+---------------------+---+
Run Code Online (Sandbox Code Playgroud)

我到目前为止的尝试是:

里面的X类:

@Override
protected void onMeasure (int widthMeasureSpec, int heightMeasureSpec) {
    int height = getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec);
    setMeasuredDimension(height,height);
    Log.v("measure","width:"+height + " height:"+height);
}
Run Code Online (Sandbox Code Playgroud)

和我的xml:

<RelativeLayout
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content">

    <TextView android:id="@+id/mytext"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_alignParentLeft="true"/>

    <mystuff.X
     android:layout_width="wrap_content"
     android:layout_height="fill_parent"
     android:layout_toRightOf="@id/mytext"/>

</RelativeLayout>
Run Code Online (Sandbox Code Playgroud)

日志语句打印出来:

width:1073741823 height:1073741823
width:37 height:37
width:1073741823 height:1073741823
width:37 height:37
width:1073741823 height:1073741823
width:37 height:37
Run Code Online (Sandbox Code Playgroud)

创建视图并填充屏幕宽度时:

+---------------------+-----------------+
|A flexible string    |      X          |
+---------------------+-----------------+
Run Code Online (Sandbox Code Playgroud)

我非常感谢任何帮助.谢谢!伊恩

android android-layout

1
推荐指数
1
解决办法
6463
查看次数