问题描述
我正在尝试从用户那里获取输入并使用此输入来调整 JFrame 中的圆圈大小。
import java.awt.*;
import java.util.Scanner;
import javax.swing.*;
public class CircleResize extends JFrame {
public static void main(String[] args) {
CircleResize frame = new CircleResize();
frame.setTitle("Tutorial 9");
frame.setSize(800,400);
frame.setDefaultCloSEOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeto(null); // Center the frame
frame.setVisible(true);
}
public CircleResize() {
add(new Drawing());
}
static class Drawing extends JPanel {
protected void paintComponent(Graphics g) {
Scanner input = new Scanner(system.in);
System.out.print("Enter x: ");
int a = input.nextInt();
System.out.print("Enter y: ");
int b = input.nextInt();
g.drawoval(200,50,a,b);
}
}
}
不知道为什么,但它一直要求输入即使认为它不是一个循环。我不明白为什么。 当前输出示例:
Enter x: 50
Enter y: 50
Enter x: 50
Enter y: 50
Enter x: 50
Enter y: 50
解决方法
您正在覆盖 paintComponent
,每次更改 Graphics
时都会调用它。在那里您需要输入并调用 drawOval
。这会导致更改,因此事件调度程序调用 paintComponent
。这是你的循环。
将您的输入输入 main
。在 a
和 main 的范围内声明 b
和 paintComponent
。然后调用 repaint ()
或 revalidate ()
。这将导致调用paintComponent(),不是直接或立即,而是很快。
不要在paintComponent内部调用改变绘画时使用的事物状态的事物。
编辑:
哦,好吧,我开始只发布一些内容,但很快就变成了大部分内容,所以这里是我编写的一些工作代码,虽然不是完美的专业标准,但我认为它会对你有所帮助。
public class SandBox {
public static void main (String [] args) {
CircleResize frame = new CircleResize ();
frame.setTitle ("Tutorial 9");
frame.setSize (800,400);
frame.setLocation (100,100);
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
// frame.setLocationRelativeTo (null); // Center the frame
frame.setVisible (true);
Scanner input = new Scanner (System.in);
System.out.print ("Enter a: ");
frame.a = input.nextInt ();
System.out.print ("Enter b: ");
frame.b = input.nextInt ();
frame.repaint ();
}
}
class CircleResize extends JFrame {
int a = 100;
int b = 100;
public CircleResize () {
add (new Drawing ());
}
class Drawing extends JPanel {
@Override
protected void paintComponent (Graphics g) {
g.drawOval (200,50,a,b);
}
}
}