[英]Custom drawing in JFrame Doesn't Display
我正在設計一個帶狀圖,但未顯示。 正在顯示其封裝的JFrame,並且正在調用paintComponent()
,但是沒有出現灰色網格線。 為什么是這樣?
class ChartArea extends JPanel {
private int Yscl, Xscl;
private static final Color BACKGROUND_COLOR = Color.BLACK;
private static final Color LINE_COLOR = Color.GREEN;
private static final Color GRIDLINE_COLOR = Color.GRAY;
ChartArea() {
setBackground(BACKGROUND_COLOR);
setForeground(LINE_COLOR);
Yscl = 20;
Xscl = 20;
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
int height = getHeight();
int width = getWidth();
double max = data.getMax(); //gets the maximum value in the data set
try {
g2d.setStroke(new BasicStroke(1f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER));
//put the origin in the bottom right. Positive is up and left
g2d.translate(width, height);
g2d.scale(-1d, -1d);
//if the data set exceeds the window height, scale it down
if (max > height) {
g2d.scale(1, height / max);
}
paintGrid(g2d);
paintLine(g2d);
} finally {
g2d.dispose();
}
}
private void paintGrid(Graphics2D g) {
g.setPaint(GRIDLINE_COLOR);
//Vertical Lines
for (double pos = 0; pos > getWidth(); pos += Xscl) {
Line2D line = new Line2D.Double(pos, 0d, pos, getHeight());
g.draw(line);
}
//Horizontal Lines
for (double pos = 0; pos > getHeight(); pos += Yscl) {
Line2D line = new Line2D.Double(0d, pos, getWidth(), pos);
g.draw(line);
}
}
private void paintLine(Graphics2D g) {
g.setPaint(LINE_COLOR);
Path2D plot2 = new Path2D.Double();
if (!data.isEmpty()) {
plot2.moveTo(0.0, data.get(0));
for (int i = 1; i < data.size(); i++) {
plot2.lineTo((double) i, data.get(i));
}
g.draw(plot2);
}
}
看起來在for
循環條件中有錯別字會畫線。 循環永遠不會在當前條件下執行。 如果將條件更改為pos < getWidth();
和pos < getHeight();
您應該看到網格。 這是一個完整的方法:
private void paintGrid(Graphics2D g) {
g.setPaint(GRIDLINE_COLOR);
//Vertical Lines
//for (double pos = 0; pos > getWidth(); pos += Xscl) {
for (double pos = 0; pos < getWidth(); pos += Xscl) {
Line2D line = new Line2D.Double(pos, 0d, pos, getHeight());
g.draw(line);
}
//Horizontal Lines
//for (double pos = 0; pos > getHeight(); pos += Yscl) {
for (double pos = 0; pos < getHeight(); pos += Yscl) {
Line2D line = new Line2D.Double(0d, pos, getWidth(), pos);
g.draw(line);
}
}
結果如下:
您要覆蓋paintComponent以便僅繪制您的自定義面板。 您只需要繪制父實例。
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
// custom painting
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.