Swing graphics reposition drawString

问题描述 投票:0回答:1

我正在用户屏幕上绘制一个字符串,我想移动该字符串,但它不会改变位置,这是我的代码

public static int x = 200, y = 200;

    public static Window draw() {
    Window w = new Window(null) {
        @Override
        public void paint(Graphics g) {
            super.paint(g);
            System.out.println("repainting");
            final Font font = getFont().deriveFont(48f);
            g.setFont(font);
            g.setColor(Color.WHITE);
            final String message = "Hello";
            FontMetrics metrics = g.getFontMetrics();
            g.drawString(message, x, y);
        }

        @Override
        public void update(Graphics g) {
            paint(g);
        }
    };
    w.setAlwaysOnTop(true);
    w.setBounds(w.getGraphicsConfiguration().getBounds());
    w.setBackground(new Color(0, true));
    w.setVisible(true);
    return w;
}


  public static void main(String[] args) throws AWTException {
        Window window = draw();
        x = 500;
        y = 500;
        window.repaint();
        window.invalidate();
        }
    }

[它似乎没有改变文本位置,它打印出repainting,因此调用了point方法,并且我已经在paint方法中打印了x, y,并且它似乎也已更新,所以有一些东西不想绘制新字符串的图形有问题。

java swing graphics2d
1个回答
0
投票

只需完全删除您的Window类,然后将其替换为JFrame。然后,自定义类应为JPanel并仅覆盖paintComponent。我猜想它不起作用,所以您正在研究使它起作用的方法,并且最终得到了一些漂亮的代码。

import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.Graphics;
import javax.swing.Timer;
import java.awt.EventQueue;

public class Confusion{
    static int x = 100;
    static int y = 0;
    static double theta = 0;

    public static void startGui(){
        JFrame frame = new JFrame("title");

        JPanel panel = new JPanel(){
            public void paintComponent(Graphics g){
                g.drawString("string", x, y);
            }
        };
        frame.setSize(640, 480);
        frame.add(panel);
        frame.setVisible(true);
        Timer timer = new Timer( 30, (e)->{
            x = (int)(300 + Math.sin(theta)*200);
            y = (int)(300 - Math.cos(theta)*200);
            theta += 0.1;
            panel.repaint();        
        } );
        timer.start();
    }
    public static void main(String[] args) throws Exception {
        EventQueue.invokeAndWait( Confusion::startGui );   
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.