java - Swing 图形重新定位 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
所以点方法被调用,我已经x, y
在paint方法内部打印,它似乎也被更新了,所以图形有问题不想要绘制一个新字符串。
解决方案
只需完全删除您的 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 );
}
}
推荐阅读
- c# - Xamarin 从视图模型传递列表数据以进行视图绑定
- sqlite - 在一个事务中执行准备语句,而另一个事务在同一个数据库中运行
- php - 如何使用 file_put_contents 添加 php 数组?- PHP
- google-cloud-platform - 为什么云构建说我缺少我的项目所需的“compute.instances.create”权限?
- robotframework - 找不到 AutoItLibrary.MouseClick
- python - 将熊猫数据帧整数转换为日期时间的错误消息
- java - 如何在 Builder 设计模式中实现方法的条件可见性?
- python - 服务器在 vscode 上工作正常,但在 cmd 中不行
- firefox - Firefox 从缓存中保存视频——而不是重新下载
- javascript - 仅当类存在时才执行加载窗口