Java没有执行正确编写的代码。可能有什么不对? (包括截图)

时间:2012-02-26 19:08:28

标签: java eclipse swing jframe jpanel

import java.awt.*; 

import java.awt.event.*;

import javax.swing.*;

public class Stickman extends JPanel{

    public void paintComponent(Graphics g)
    {
        super.paintComponent(g);
        //Color SKY = new Color(135, 206, 235);
        this.setBackground(Color.WHITE);

        g.setColor(Color.BLUE);
        g.fillRect(30, 100, 10, 5);

        g.setColor(Color.gray);
        g.fillRect(30, 120, 10, 5);

    }
}

import javax.swing.*;

public class WindowPerameters {

    public static void main (String[] args)
    {
        JFrame f = new JFrame ("Hangman");

        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        Stickman s = new Stickman();

        f.add(s);

        f.setSize(600, 300);

        f.setVisible(true);

    }

}

1 个答案:

答案 0 :(得分:3)

您没有在事件派发线程中执行Swing代码。请参阅http://docs.oracle.com/javase/6/docs/api/javax/swing/package-summary.html#threading

此外,您不应在paintComponent方法中更改面板的背景。使用此方法绘制组件,但不修改其属性。