use*_*626 0 java user-interface swing
所以我是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
Run Code Online (Sandbox Code Playgroud)
主要:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
您的paintSun和paintPlanet方法永远不会被神奇地调用.相反,您的JPanel需要覆盖paintComponent方法,因为所有绘图都在那里完成.你甚至可以在paintComponent中调用paintSun和paintPlanet方法,但是我建议super.paintComponent(g)只调用一次,只能在paintComponent方法中覆盖它自己.
例如,
// 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
Run Code Online (Sandbox Code Playgroud)