gpt4 book ai didi

java - 简单的打印圆圈 GUI 问题

转载 作者:行者123 更新时间:2023-12-01 16:55:17 25 4
gpt4 key购买 nike

所以我是 GUI 的新手,我想制作一个简单的程序来打印一个圆圈来代表太阳,然后在它附近我想打印另一个圆圈来代表一个行星。我的问题是,当我添加 PaintPlanet 方法时,GUI 窗口中返回的所有内容现在都是空白屏幕。即使当我注释掉paintPlanet时,太阳的圆圈也不会打印出来,并且留下一个空白窗口。有人可以帮我找出哪里出错了如何修复它以便两个圆圈都会打印出来吗?我对 GUI 很陌生,所以对我要轻松一点:)

import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;


public class PlanetsLogic extends JPanel
{
private static final long serialVersionUID = 1L;

public void paintSun(Graphics g)
{
super.paintComponent(g);

//create circle and fill it as yellow to represent the sun
g.setColor(Color.YELLOW);
g.drawOval(100, 75, 75, 75);
g.fillOval(100, 75, 75, 75);
} //end paintSun


public void paintPlanet(Graphics g)
{
super.paintComponent(g);
//create circle and fill it as yellow to represent the orbiting planet
g.setColor(Color.BLUE);
g.drawOval(75, 75, 75, 75);
g.fillOval(75, 75, 75, 75);


}//end paintPlanet

}//end class PlanetsLogic

主要:

import javax.swing.JFrame;

public class OrbitingPlants_main
{

public static void main(String[] args)
{

PlanetsLogic planet = new PlanetsLogic();
JFrame frame = new JFrame();

frame.setTitle("Orbiting Planets");
frame.setSize(300, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(planet); //add panel onto frame
frame.setVisible(true);
}

}

最佳答案

你的paintSun和paintPlanet方法永远不会被神奇地调用。相反,您的 JPanel 需要重写 PaintComponent 方法,因为所有绘图都在那里完成。您甚至可以从paintComponent 中调用paintSun 和paintPlanet 方法,但我建议仅在paintComponent 方法重写自身中调用super.paintComponent(g) 一次。

例如,

// use @Override to ask the compiler to check if this method is a true override
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g); // HERE!
paintSun(g);
paintPlanet(g);
}

public void paintSun(Graphics g) {
// super.paintComponent(g); // nope, not here!

//create circle and fill it as yellow to represent the sun
g.setColor(Color.YELLOW);
g.drawOval(100, 75, 75, 75);
g.fillOval(100, 75, 75, 75);
} //end paintSun


public void paintPlanet(Graphics g) {
// super.paintComponent(g); // NO don't call this here
//create circle and fill it as yellow to represent the orbiting planet
g.setColor(Color.BLUE);
g.drawOval(75, 75, 75, 75);
g.fillOval(75, 75, 75, 75);
}//end paintPlanet

关于java - 简单的打印圆圈 GUI 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33881022/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com