简体   繁体   English

使用Java的executor服务和非静态方法

[英]using java's executor service with a non-static method

I've been writing a programm, which opens a window and if you close it,it will open two new ones. 我一直在编写一个程序,它将打开一个窗口,如果您将其关闭,它将打开两个新窗口。 It's working fine, but I tried to change the color of all windows by using the executor service, which is calling my function ColorChanger. 它工作正常,但是我尝试使用执行程序服务来更改所有窗口的颜色,该服务正在调用我的函数ColorChanger。

The Problem is : If I want to use the executor service, I need a static method, but if I want to use the this.getContentPane().setBackground(Color.blue); 问题是 :如果要使用执行程序服务,则需要静态方法,但是如果要使用this.getContentPane().setBackground(Color.blue); command, I have to use a non-static function. 命令,我必须使用非静态功能。

If you need further information, please have look at my code, everything should by self-explaining: 如果您需要更多信息,请查看我的代码,所有内容都应自解释:

public class SplittingWindow extends JFrame implements WindowListener,KeyListener {

    int width = (int)Toolkit.getDefaultToolkit().getScreenSize().getWidth();
    int height = (int)Toolkit.getDefaultToolkit().getScreenSize().getHeight ();
    Random rand = new Random();
    String Input = new String();
    static ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();

    public static void main(String[] args) {
        executorService.scheduleAtFixedRate(() -> ColorChanger(), 0, 1, TimeUnit.SECONDS);
        new SplittingWindow();
    }  

    SplittingWindow(){
        addWindowListener(this);
        addKeyListener(this);
        setResizable(false);
        setSize(100,100);
        setVisible(true);
        setLocation(rand.nextInt(width-150),rand.nextInt(height-200)+50);
    }

    public void ColorChanger(){
        getContentPane().setBackground(Color.blue);
    }

    public void windowClosing(WindowEvent arg0) {  
        System.out.println("closing");
        new SplittingWindow();
        new SplittingWindow();
        dispose(); 
    }

    public void keyTyped(KeyEvent e) {
        Input = Input + e.getKeyChar();
        if(Input.contains("JayJay")==true){
            System.exit(0);
        }
    }


    // Removed various interface methods  
}

THe fqct is you need to instanciate the object if you want to use a method of hs class without making it static :) 如果您想使用hs类的方法而不使其成为静态,则需要实例化该对象:)

public static void main(String[] args) {
        SplittingWindow sp = new SplittingWindow();
        executorService.scheduleAtFixedRate(() -> sp.ColorChanger(), 0, 1, TimeUnit.SECONDS);
    }  

try this and it should work 试试这个,它应该工作

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

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