简体   繁体   中英

Java graphics not working in timer

I am programming a tiny game in java. For that I want to print a dialog-text-box with some text in it to talk to people inside the game.

    public static void printConBox(Graphics g, String firstLine, String secondLine, String thirdLine, String fourthLine){
    g.setColor(Color.WHITE);
    g.fillRect(x, y, 600, 180);
    g.setColor(Color.BLACK);
    Timer timer = new Timer();
    timer.schedule(new TimerTask(){

        @Override
        public void run() {
            if(i <= firstLine.length() - 1){
                char c = firstLine.charAt(i);
                i++;
                String s = "" + c;
                System.out.print(s);
                g.drawString(s, xdif, y + 25);
                xdif += 15;
            }else{
                timer.cancel();
            }
        }

    }, 0, 100);}

Don't worry about the graphics, this is working because the programm is painting the white Text-Box. But the letters in the String 'firstLine' arent there. In run this should be an animation for the text!

I think this has to do with der Timer! But the printing in the output-Console is working perfectly! I also try it with Thread.sleep in a for-loop, but still not working...

Any ideas?...

PS.: I have use paintComponent and that, so the graphics is working believe me ;)

    public void actionPerformed(ActionEvent e){ 
    if(Conversation.i <= firstLine.length() - 1){
        char c = firstLine.charAt(Conversation.i);
        Conversation.i++;
        String s = "" + c;
        System.out.print(s);
        g.drawString(s, Conversation.xdif, Conversation.y + 25);
        Conversation.xdif += 15;
        Conversation.timer.restart();
    }else{
        Conversation.timer.stop();
    }
}

But how do I get the Graphics in der actionPerformed, the Timer works with? By the way the System.out is working angain! Nice... ;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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