can#39;t draw on JFrame(无法在 JFrame 上绘图)
问题描述
I'm trying to make a simle java program that draws a circle at the mouse localization, it gets the mouse X and Y coordinates but it doesn't draw anything, i tried to draw a String, a circle and a line but nothing worked, i changed the code a bit but it still doesn't works
class Test4 {
public static String a;
public static JFrame frame = new JFrame();
public static Point Gett(){
PointerInfo h = MouseInfo.getPointerInfo();
Point b = h.getLocation();
return b;
}
public void paintComponent(int x, int y, Graphics g) {
g.drawOval(x, y, 10, 10);
}
public static void main(String[] args) throws InterruptedException {
int h = 250;
int f = 200;
frame.setVisible(true);
frame.setSize(h, f);
frame.setLocationRelativeTo(null);
while(true){
Point b = Gett();
int x = (int) b.getX();
int y = (int) b.getY();
System.out.println(x);
System.out.println(y);
frame.repaint();}}}
Don't perform custom painting directly on a
JFrame
. Always do it on aJComponent
overriding thepaintComponent
method if you can.Don't use an infinite loop for this purpose. There is the
MouseMotionListener
for Mouse Motion listening
public class Test4 {
public static String a;
public static CustomDrawingPanel content;
public static JFrame frame = new JFrame();
final static int OVAL_WIDTH = 10;
final static int OVAL_HEIGHT = 10;
static int x = -20, y = -20;
public static MouseMotionListener listener = new ContentListener();
public static void main(String[] args) throws InterruptedException {
int h = 250;
int f = 200;
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
content = new CustomDrawingPanel();
content.addMouseMotionListener(listener);
frame.add(content);
frame.getContentPane().setPreferredSize(new Dimension(h, f));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
//class that performs custom drawing
static class CustomDrawingPanel extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponent(g); //Always call this
g.drawOval(x, y, 10, 10);
}
}
//listener to the mouse motion
static class ContentListener implements MouseMotionListener {
@Override
public void mouseDragged(MouseEvent e) {
mouseMoved(e); //if you delete this line, when you drag your circle will hang
}
@Override
public void mouseMoved(MouseEvent e) {
x = e.getX() - OVAL_WIDTH / 2;
y = e.getY() - OVAL_HEIGHT / 2;
content.repaint();
}
}
}
这篇关于无法在 JFrame 上绘图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:无法在 JFrame 上绘图
基础教程推荐
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01