我需要做的是在关闭JFrame时设置变量。我的项目中有一个主题。我希望只有当另一个类中的静态变量设置为true时才运行此线程。 这是我将设置变量的类(sliderActivated):
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Toolkit;
import javax.swing.JFrame;
import javax.swing.JSlider;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class ZoomSlider extends JFrame implements ChangeListener{
private static final long serialVersionUID = -9026587156796382276L;
private JSlider slider;
private static boolean sliderActivated = false;
public ZoomSlider(){
//setSliderActivated(true);
Container contentPane = getContentPane();
this.setTitle("Zoom");
this.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
this.setAlwaysOnTop(true);
Toolkit mioToolkit = Toolkit.getDefaultToolkit();
Dimension dimensioniSchermo = mioToolkit.getScreenSize();
int larghezzaFrame, altezzaFrame;
larghezzaFrame = 80;
altezzaFrame = (int)(dimensioniSchermo.getHeight() - 70);
this.setSize(larghezzaFrame, altezzaFrame);
this.setLocation(0,50);
slider = new JSlider(JSlider.VERTICAL, 50, 200, 100);
slider.setMajorTickSpacing(50);
slider.setMinorTickSpacing(10);
slider.setPaintTicks(true);
slider.setPaintLabels(true);
slider.addChangeListener(this);
contentPane.add(slider);
this.setVisible(true);
}
@Override
public void stateChanged(ChangeEvent arg0) {
//setSliderActivated(true);
int value = ((JSlider)arg0.getSource()).getValue();
EarthPanel.SCALE = value/100.0;
//setSliderActivated(false);
}
public static boolean isSliderActivated() {
return sliderActivated;
}
public static void setSliderActivated(boolean sliderActivated) {
ZoomSlider.sliderActivated = sliderActivated;
}
}
这是使用变量的线程的run方法:
public void run() {
while(true){
if(ZoomSlider.isSliderActivated()){
this.setPreferredSize(new Dimension((int)(width * SCALE),(int)(height * SCALE)));
repaint();
}
}
}
我的想法是仅在JFrame ZoomSlider.java可见时重绘主要面板(此问题中不存在代码)。在那一刻,sliderActivated将设置为true。相反,当我关闭JFrame时,sliderActivated将设置为false并且线程将停止运行。 我怎么能这样做?
答案 0 :(得分:0)
基本上,您需要向JFrame添加一个WindowListener,它响应已关闭或关闭的事件:
jFrame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosed(WindowEvent e) {
// Do something
}
@Override
public void windowClosing(WindowEvent e) {
// Do something
}
});
答案 1 :(得分:0)
您应该在框架实例中添加WindowListener
或WindowStateListener
。 WindowStateListener的示例:
public class ZoomSlider extends JFrame implements ChangeListener, WindowStateListener {
private static volatile boolean sliderActivated = false;
[...]
public void windowStateChanged(WindowEvent e) {
if (e.getNewState() == WindowEvent.WINDOW_CLOSED) {
setSliderActivated(false);
} else if (e.getNewState() == WindowEvent.WINDOW_OPENED) {
setSliderActivated(true);
}
}
}
请注意,您必须将该字段声明为volatile,因为写入/读取时会涉及两个不同的线程。