调用非静态类java
我试图注意到,当我的java应用程序中发生特别的事情时,我试图让窗口闪烁(在mac和windows上)。然而,我是Java新手,对静态/非静态方法感到失望
不管我有多沮丧,我该如何称呼我的toggleVisible课程
我已经删除了不必要的代码:
public static void main(String args[]) {
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
checkAlerts();
}
}, 30000, 30000);
}
public static Boolean checkAlerts(){
if(count == 0){
JOptionPane.showMessageDialog(null, "No results");
} else {
toggleVisible();
JOptionPane.showMessageDialog(null, "Some results back");
}
}
public void toggleVisible() {
setVisible(!isVisible());
if (isVisible()) {
toFront();
requestFocus();
setAlwaysOnTop(true);
try {
//remember the last location of mouse
final Point oldMouseLocation = MouseInfo.getPointerInfo().getLocation();
//simulate a mouse click on title bar of window
Robot robot = new Robot();
robot.mouseMove(mainFrame.getX() + 100, mainFrame.getY() + 5);
robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
//move mouse to old location
robot.mouseMove((int) oldMouseLocation.getX(), (int) oldMouseLocation.getY());
} catch (Exception ex) {
//just ignore exception, or you can handle it as you want
} finally {
setAlwaysOnTop(false);
}
}
}
toggleVisible给了我一个错误:不能从静态上下文引用非静态方法toggleVisible()
# 1 楼答案
停止不必要地使用
简单地说,考虑这个例子:static
关键字。相反,只需在main
方法内创建类的一个对象,并调用一个方法,就可以利用这个方法来推进应用程序的流程此外,你似乎正在处理
Swing
。出于这个原因,考虑javax.swing.Timer,^ ^ {CD4}},因为前者假设将GUI相关的任务自动放在^ {< CD5> },尽管后者的责任纯粹是与程序员有关。p>下面是一个使用
Swing
的Timer
类的小例子: