circle class
This is a simple circle class with only with a constructor.
public class Circle {
private int radius;
public Circle(int radius) {
this.radius = radius;
}
public int getRadius() {
return radius;
}
public void setRadius(int radius) {
this.radius = radius;
}
public double getArea() {
return Math.PI * radius * radius;
}
@Override
public String toString() {
return "cicle [radius=" + radius + ", getRadius()=" + getRadius() + ", getArea()=" + getArea() + ", getClass()="
+ getClass() + ", hashCode()=" + hashCode() + ", toString()=" + super.toString() + "]";
}
}
Rock class
This is Rock class extends JPanel
, that only have circle as variable. and overridden paintComponent
.
import javax.swing.*;
import java.awt.*;
public class Rock extends JPanel {
private Circle circle;
public Rock(Circle circle) {
this.circle=circle;
}
public Circle getCircle() {
return circle;
}
public void setCircle(Circle circle) {
this.circle = circle;
}
@Override
public void paintComponent(Graphics j) {
super.paintComponent(j);
j.setColor(Color.black);
int radius=new Circle(100).getRadius();
j.fillOval(5, 5, radius, radius);
}
/*
* public void paintcomponent(Graphics g) { super.paintComponent(g);
* g.setColor(Color.black); int radius=new Circle(100).getRadius();
* g.fillOval(0, 0, radius, radius); }
*/
}
Gui Stuff
This is the class where I was trying to construct everything.
but when I added the Rock object to the layout, it would not appear.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
@SuppressWarnings("serial")
public class Gui extends JFrame implements ActionListener {
JFrame topFrame = null;
GridBagLayout grid=new GridBagLayout();
GridBagConstraints cons=new GridBagConstraints();
Graphics j;
Circle circle=new Circle(100);
Rock rock;
public Gui() {
rock=new Rock(circle);
RockGold h=new RockGold(circle);
JLabel lblResult=new JLabel(" Result ");
this.setLayout(grid);
cons=new GridBagConstraints();
cons.gridx=1;
cons.gridy=7;
cons.insets=new Insets(10,10,10,0);
this.add(rock,cons);
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
}
Main
This is the main with frames settings.
import javax.swing.JFrame;
public class main {
public static void main(String[] args) {
Gui gui=new Gui();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setSize(900, 900);
gui.setVisible(true);
}
}
question from:
https://stackoverflow.com/questions/66066540/hello-i-am-trying-to-draw-a-circle-by-using-paintcomponent 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…