我想画简单的椭圆形。在下面的代码中,如果我在 Jpanel 上添加了一个椭圆,那么它不起作用但是如果我在框架上绘制它就可以正常工作。以下是有效的代码。
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.LineBorder;
public class Controller {
public Controller() {
View view = new View();
Model model = new Model(100, 100, 100, 100);
view.paintModel(model);
}
public static void main(String[] args) {
Controller c = new Controller();
}
public class View extends JFrame {
private JPanel jpanel;
public View() {
this.setBounds(0, 0, 500, 500);
this.setLayout(new BorderLayout());
jpanel = new JPanel();
jpanel.setBackground(Color.WHITE);
jpanel.setLayout(null);
this.add(jpanel, BorderLayout.CENTER);
this.setVisible(true);
this.validate();
}
public void paintModel(Model model) {
jpanel.add(new ModelView(model));
jpanel.validate();
jpanel.repaint();
}
}
public class Model {
public int xPos;
public int yPos;
public int height;
public int width;
public Model(int xPos, int yPos, int height, int width) {
super();
this.xPos = xPos;
this.yPos = yPos;
this.height = height;
this.width = width;
}
}
public class ModelView extends JComponent {
private Model model;
public ModelView(Model model) {
super();
setBorder(new LineBorder(Color.RED));
this.model = model;
}
@Override
public Dimension getPreferredSize() {
return new Dimension(model.xPos + model.width, model.yPos
+ model.height);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.black);
g.fillOval(model.xPos, model.yPos, model.width, model.height);
}
}
}