JButton未在屏幕上显示

时间:2015-03-13 17:27:34

标签: java swing jframe jbutton jlabel

我试图制作一个可以通过点击按钮来改变交通信号灯状态的应用程序。 我的代码:Main

import javax.swing.*;

public class PP416 
{
    public static void main(String[] args)
    {
        JFrame frame = new JFrame("Traffic light");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame.getContentPane().add(new TrafficPanel());
        frame.pack();
        frame.setVisible(true);
    }
}

JPanel Class:

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

public class TrafficPanel extends JPanel 
{
    private JButton button;
    private int indicator = 0; // Light is off

    public TrafficPanel()
    {
        button = new JButton("Change");

        this.add(button);
    }

    public void paint(Graphics g)
    {
        if (indicator == 0)
        {
            g.drawOval(30, 40, 30, 30);
            g.drawOval(30, 70, 30, 30);
            g.drawOval(30, 100, 30, 30);
        }
    }

}

按钮只是没有出现,只是ovalls。 有谁可以帮我这个?

1 个答案:

答案 0 :(得分:2)

不要覆盖paint,而是paintComponent最重要的,请调用超级方法。您缺少超级调用可能会阻止您的JPanel很好地绘制其子组件。

如,

@Override
protected void paintComponent(Graphics g) {
   super.paintComponent(g);
   if (indicator == 0) {
       g.drawOval(30, 40, 30, 30);
       g.drawOval(30, 70, 30, 30);
       g.drawOval(30, 100, 30, 30);
   }
}