0
我們不能完全弄清楚如何可以讓這個餅圖顯示:我們該如何畫這個餅圖課?
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;
}
}
,並從調用所有視圖「視圖」
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);
}
}
我認爲這個問題是該方法的油漆()。我們無法從其他地方調用它,但我確信我們應該採取不同的方式,因爲它是面板而不是框架。有誰知道我們如何解決這個問題?
我知道,你正在使用的Swing畫,但JavaFX提供一定圖表,例如一個[PieChart](https://docs.oracle.com/javase/8/javafx/api/javafx/scene/chart/PieChart.html)。只是想提到這一點。 – pzaenger
@pzaenger很有幫助;) –
感謝您的提示,我們現在有一個與javaFX一起的餅圖:) –