在我的钟面上添加JLabel是不行的

时间:2017-01-12 02:36:19

标签: java jpanel jlabel

我试过,在其他答案中添加了flowlayout,但它仍然没有用。

我也尝试将我的JLabel代码移动到构造函数中,但这也不起作用。

public class Paint {

    public static void main(String[] args) {
        JFrame frame = new JFrame("Paint");
        frame.setSize(500,500);
        frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);

        Draw draw = new Draw();
        frame.add(draw);
        frame.setVisible(true);
    }
}


public class Draw extends JPanel{

    public Draw(){
        JLabel one = new JLabel("12",JLabel.CENTER);
        setLayout(new FlowLayout());
        add(one);
    }

    public void paint(Graphics g){
        g.drawOval(70, 60, 190, 190);

        g.setColor(Color.BLACK);
        g.drawLine(90, 160, 170, 160);
        g.drawLine(120, 190,170 , 160);

        g.setColor(Color.GRAY);
        g.fillOval(155, 153, 20, 20);
    }
}

1 个答案:

答案 0 :(得分:1)

  • 更改paint以覆盖paintComponent
  • 在进行任何自定义绘画之前调用super.paintComponent

enter image description here

import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Paint {

    public static void main(String[] args) {
        JFrame frame = new JFrame("Paint");
        frame.setSize(500, 500);
        frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);

        Draw draw = new Draw();
        frame.add(draw);
        frame.setVisible(true);
    }

    public static class Draw extends JPanel {

        public Draw() {
            JLabel one = new JLabel("12", JLabel.CENTER);
            setLayout(new FlowLayout());
            add(one);
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g); 
            g.drawOval(70, 60, 190, 190);

            g.setColor(Color.BLACK);
            g.drawLine(90, 160, 170, 160);
            g.drawLine(120, 190, 170, 160);

            g.setColor(Color.GRAY);
            g.fillOval(155, 153, 20, 20);
        }
    }
}