我正在使用Java的xchart库,我正在创建一个图表,如下所示:
XYChart chartHR = QuickChart.getChart("Title", "Time", "y", "randomWalk", new double[] { 0 }, new double[] { 0 });
chartHR.getStyler().setLegendVisible(false);
chartHR.getStyler().setXAxisTicksVisible(false);
SwingWrapper<XYChart> swHR = new SwingWrapper<XYChart>(chartHR);
swHR.displayChart().setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
我正在从我的主类启动的线程中创建此图表。每次关闭图表时,我的整个申请都会关闭。我该如何防止这种情况?
以下是最小的工作示例:
package test;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
TestThread testThread = new TestThread();
testThread.start();
String input = "";
Scanner scanner = new Scanner(System.in);
while (!input.equals("q")) {
System.out.print("Enter 'q' for termination.");
input = scanner.nextLine();
}
scanner.close();
}
}
package test;
import javax.swing.JFrame;
import org.knowm.xchart.QuickChart;
import org.knowm.xchart.SwingWrapper;
import org.knowm.xchart.XYChart;
public class TestThread extends Thread {
private SwingWrapper<XYChart> swHR;
private XYChart chartHR;
public void run() {
chartHR = QuickChart.getChart("Test", "Time", "y", "randomWalk", new double[] { 0 }, new double[] { 0 });
chartHR.getStyler().setLegendVisible(false);
chartHR.getStyler().setXAxisTicksVisible(false);
swHR = new SwingWrapper<XYChart>(chartHR);
swHR.displayChart().setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
while(true) {}
}
}
答案 0 :(得分:2)
如果检查源代码,SwingWrapper
将设置EDT上JFrame的默认关闭操作。你不是,所以你设置值,然后它被覆盖。要解决此问题,请将更改发布到EDT,它应该可以正常工作。
JFrame frame = swHR.displayChart();
javax.swing.SwingUtilities.invokeLater(
()->frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE)
);
这应该进入队列并在SwingWrapper进行更改后发生。