我们无法弄清楚如何显示这个饼图:
import java.awt.*;
import java.awt.Graphics2D;
import java.awt.Graphics;
import javax.swing.*;
public class PieChart extends View {
public PieChart (Model model){
super(model);
MyComponent piechart = new MyComponent();
this.add(piechart);
}
public void updateView(){
repaint();
}
}
class MyComponent extends JComponent {
Slice[] slices = {
new Slice(5, Color.black), new Slice(33, Color.green), new Slice(20, Color.yellow), new Slice(15, Color.red)
};
MyComponent() {
setVisible(true);
}
public void paint(Graphics g) {
drawPie((Graphics2D) g, getBounds(), slices);
}
void drawPie(Graphics2D g, Rectangle area, Slice[] slices) {
double total = 0.0D;
for (int i = 0; i < slices.length; i++) {
total += slices[1].value;
}
double curValue = 0.0D;
int startAngle = 0;
for (int i = 0; i < slices.length; i++) {
startAngle = (int) (curValue * 360 / total);
int arcAngle = (int) (slices[i].value * 360 / total);
g.setColor(slices[i].color);
g.fillArc(area.x, area.y, area.width, area.height, startAngle, arcAngle);
curValue += slices[i].value;
}
}
}
class Slice {
double value;
Color color;
public Slice(double value, Color color) {
this.value = value;
this.color = color;
}
}
和它延伸的类#&#34;查看&#34;
import javax.swing.*;
@SuppressWarnings("serial")
public class View extends JPanel {
public Model model;
public View(Model model) {
this.model=model;
model.addView(this);
}
public void setModel(Model model) {
this.model=model;
}
public Model getModel() {
return model;
}
public void updateView() {
repaint();
}
}
最后是调用所有视图的类(仅显示适用的代码)
public class Simulator {
....
private View pieChart;
public Simulator(int floors, int rows, int places) {
//initialiseert Model
floornumber = floors;
rownumber = rows;
placenumber = places;
model=new Model(floornumber,rownumber,placenumber);
screen=new JFrame("Parkere simulatie");
screen.setTitle("Parkeer-control Screen");
screen.setSize(1600, 1000);
screen.setResizable(false);
screen.setLayout(null);
........
pieChart = new PieChart(model);
screen.getContentPane().add(pieChart);
pieChart.setBounds(840, 300, 300, 300);
}
}
我认为问题是方法paint()。我们无法从其他任何地方调用它,但我非常确定我们应该采用不同的方式,因为它是一个面板而不是一个框架。有谁知道我们如何解决这个问题?
答案 0 :(得分:1)
你没有显示&#39;屏幕&#39;在屏幕上。 (例如setVisible) - 它会根据需要自动调用子画面
再次: 使框架可见,儿童将被框架绘制