4
我是初學java的高中生,我必須製作一個簡單的盒子和鬍鬚。我無法得到我在JPanel上繪製的東西以顯示在JFrame上。該圖只是不顯示。任何人都可以幫我嗎?在JPanel上繪製圖像並將其添加到JFrame
public class BoxPlot extends JFrame {
public final int MIN;
public final double Q1;
public final double MEDIAN;
public final double Q3;
public final int MAX;
public BoxPlot(int[] data){
this.setLayout(new GridBagLayout());
this.MIN = Statistics.min(data);
this.Q1 = Statistics.lowerQuartile(data);
this.MEDIAN = Statistics.median(data);
this.Q3 = Statistics.upperQuartile(data);
this.MAX = Statistics.max(data);
this.addBox(data);
this.addSummary();
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(800, 600);
this.setResizable(true);
this.setVisible(true);
}
// Adds a panel with the boxplot
private void addBox(int[] data) {
Box box = new Box(data);
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
c.weighty = 1;
this.add(box, c);
}
// Adds a panel with the five number summaries as JLabels
// to the bottom of the JFrame
private void addSummary() {
JPanel summary = new JPanel();
summary.setLayout(new GridLayout());
JLabel l = new JLabel("Minimum: "+this.MIN, JLabel.CENTER);
summary.add(l);
l = new JLabel("First Quartile: "+this.Q1, JLabel.CENTER);
summary.add(l);
l = new JLabel("Median: "+this.MEDIAN, JLabel.CENTER);
summary.add(l);
l = new JLabel("Third Quartile: "+this.Q3, JLabel.CENTER);
summary.add(l);
l = new JLabel("Maximum: "+this.MAX, JLabel.CENTER);
summary.add(l);
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 1;
c.weightx = 1;
c.ipady = 10;
c.fill = GridBagConstraints.HORIZONTAL;
c.anchor = GridBagConstraints.PAGE_END;
this.add(summary, c);
}
``
public class Box extends JPanel{
private int min;
private double q1;
private double median;
private double q3;
private int max;
public Box(int[] data) {
this.min = Statistics.min(data);
this.q1 = Statistics.lowerQuartile(data);
this.median = Statistics.median(data);
this.q3 = Statistics.upperQuartile(data);
this.max = Statistics.max(data);
}
// paints the box onto the JPanel
public void paintComponent(Graphics g){
int d1 =10 * (int) (this.q1-this.min);
int d2 =10 * (int) (this.median-this.q1);
int d3 =10 * (int) (this.q3-this.median);
int d4 =10 * (int) (this.max-this.q3);
g.drawLine(100, 150, 100+d1, 150);
g.drawLine(100+d1+d2+d3, 150, 100+d1+d2+d3+d4, 150);
g.setColor(Color.RED);
g.fillRect(100+d1, 100, d2, 100);
g.setColor(Color.BLUE);
g.fillRect(100+d1+d2, 100, d3, 100);
}