Search code examples
javaswinggraphics2d

Swing graphics reposition drawString


I am drawing a string on the users screen, and I want to move that string around, but it doesn't change position, This is my code

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();
        }
    }

It doesn't seem to change the text position, It prints out repainting so the point method is getting called, and I have printed x, y inside the paint method and it seems to be updated aswell, so there is something wrong with graphics that doesn't want to draw a new string.


Solution

  • Just delete your Window class altogether and replace it with a JFrame. Then the custom class should be a JPanel and just override the paintComponent. I am guessing it doesn't work so you're going through things to make it work and you've ended up with some pretty dodgy code.

    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 );   
        }
    }