我在网上搜索过,据说有很多方法可以在开始新绘图之前清除 jPanel 但是,在尝试了所有之后我仍然没有成功 - 结果是面板根本不清除并且下一个绘图只是重叠第一个或我的paintComponent()根本不会执行。
从 GUI 执行绘图的代码:
private void BTCGraphActionPerformed(java.awt.event.ActionEvent evt) {
Graphics2D gfx = (Graphics2D) jPanel2.getGraphics();
WebScraper WSBTC = new WebScraper();
float[] HBTC = WSBTC.HScrapeBTC();
Graph graphExecute = new Graph();
graphExecute.CurrentValues(HBTC);
graphExecute.IndexLarge(HBTC);
graphExecute.IndexSmall(HBTC);
graphExecute.Plotter(HBTC);
graphExecute.paintComponent(gfx);
}
private void LTCGraphActionPerformed(java.awt.event.ActionEvent evt) {
Graphics2D gfx = (Graphics2D) jPanel2.getGraphics();
WebScraper WSLTC = new WebScraper();
float[] HLTC = WSLTC.HScrapeLTC();
Graph graphExecute = new Graph();
graphExecute.CurrentValues(HLTC);
graphExecute.IndexLarge(HLTC);
graphExecute.IndexSmall(HLTC);
graphExecute.Plotter(HLTC);
graphExecute.paintComponent(gfx);
}
private void ETHGraphActionPerformed(java.awt.event.ActionEvent evt) {
Graphics2D gfx = (Graphics2D) jPanel2.getGraphics();
WebScraper WSETH = new WebScraper();
float[] HETH = WSETH.HScrapeETH();
Graph graphExecute = new Graph();
graphExecute.CurrentValues(HETH);
graphExecute.IndexLarge(HETH);
graphExecute.IndexSmall(HETH);
graphExecute.Plotter(HETH);
graphExecute.paintComponent(gfx);
}
代码paintComponent():
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
super.paintComponent(g2);
int DotSize = 10;
int width = g2.getFontMetrics().stringWidth("Today");
int middle = width / 2;
g2.setColor(Color.BLACK);
/* g2.drawLine(10, 10, 10, 410); //Frame Boundaries
g2.drawLine(410, 10, 10, 10); //Frame Boundaries
g2.drawLine(410, 10, 410, 410); //Frame Boundaries
g2.drawLine(410, 410, 10, 410); //Frame Boundaries */
//Axis
g2.drawLine(30, 30, 30, 370);
g2.drawLine(370, 370, 30, 370);
//Points & Connections
PlotPoints(g2, 98, DistanceDay1, DotSize);
g2.drawLine(98, DistanceDay1, 166, DistanceDay2);
PlotPoints(g2, 166, DistanceDay2, DotSize);
g2.drawLine(166, DistanceDay2, 234, DistanceDay3);
PlotPoints(g2, 234, DistanceDay3, DotSize);
g2.drawLine(234, DistanceDay3, 302, DistanceDay4);
PlotPoints(g2, 302, DistanceDay4, DotSize);
g2.drawLine(302, DistanceDay4, 370, DistanceDay5);
PlotPoints(g2, 370, DistanceDay5, DotSize);
//Labels
g2.drawString("Today", 370 - middle, 390);
/* g2.drawString("Test", 98 - middle, 40);
g2.drawString("Test", 146, 25); */
}
我应该调用什么方法以及必须将其放置在哪里,以便每次按下按钮绘制新图形时它都会在绘制之前清除面板