gpt4 book ai didi

java - 将 JLabel 添加到我的钟面不起作用

转载 作者:行者123 更新时间:2023-12-01 09:01:51 25 4
gpt4 key购买 nike

我尝试添加其他答案中所示的流程布局,但它仍然不起作用。

我还尝试将 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);
}
}

最佳答案

  • 更改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);
}
}
}

关于java - 将 JLabel 添加到我的钟面不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41604217/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com