[英]Swing graphics reposition drawString
我正在用戶屏幕上繪制一個字符串,我想移動該字符串,但它不會改變位置,這是我的代碼
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
所以點方法被調用,我在paint方法中打印了x, y
,它似乎也被更新了,所以圖形有問題不想繪制新字符串。
只需完全刪除您的 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 );
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.