有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

多线程当不仅仅执行主方法(Java)时意味着什么?

我创建了一个名为StickFigure的类,它扩展了JComponents,并使用paintComponent()绘制了一个棒状图形。在另一个类StickFigureRunner上,有一个main方法调用一个框架和一个面板,一个新的StickFigure被添加到框架中,框架打印出木棍图形。让我困惑的部分是绘制木棍图形的部分,尽管在main方法中没有调用paintComponent的方法。为什么会这样

以下是StickFigure类:

import javax.swing.*;
import java.awt.*;

/**
 * A new kind of component that displays a stick figure
 * 
 * @author Ilai Tamari
 */

public class StickFigure extends JComponent
{
    /**
     * Constructor for StickFigure, that extends the constructor of JComponent and
     * also sets the preferred size.
     */
    public StickFigure()
    {
        super();

        // Specify the preferred size for this component
        this.setPreferredSize(new Dimension(180, 270));
    }

    /**
     * This method paints the StickFigure on the frame
     * 
     * @param g The Graphics which is used to draw the figure
     */
    @Override
    public void paintComponent(Graphics g)
    {
        super.paintComponent(g);

        // paint the head
        g.setColor(Color.YELLOW);
        g.fillOval(60, 0, 60, 60);
        
        // paint the shirt
        g.setColor(Color.RED);
        g.fillRect(0, 60, 180, 30);
        g.fillRect(60, 60, 60, 90);

        // paint the pants
        g.setColor(Color.BLUE);
        g.fillRect(60, 150, 60, 120);
        g.setColor(Color.BLACK);
        g.drawLine(90, 180, 90, 270);
    }
}

以下是StickFigureRunner类:

import java.awt.Graphics;

import javax.swing.*;

/**
 * Create a StickFigure and display it in a frame.
 * 
 * @author Ilai Tamari
 *
 */

public class StickFigureRunner
{

    public static void main(String[] args)
    {
        // declare the objects to show
        JFrame frame = new JFrame();
        JPanel contents = new JPanel();
        StickFigure stickFig = new StickFigure();

        // set up the contents
        contents.add(stickFig);

        // display the contents in a frame
        frame.setContentPane(contents);
        frame.setTitle("Stick Figure");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocation(250, 100);
        frame.pack();
        frame.setVisible(true);
    }

}


共 (0) 个答案