我正在研究一个非常基本的条形图,它必须显示6个值。我遇到的问题是,当我将屏幕放在屏幕上时,我将它们放在屏幕上,而我无法将它们关闭。我尝试过使用删除,重绘和重新验证功能,但这些都不起作用。
我需要做些什么才能移除这些条以防止它们堵塞?
我的代码:
conio.h
答案 0 :(得分:2)
对于您当前的代码,您需要致电private void initPaints()
{
waypointPaint = new Paint();
waypointPaint.setColor(Color.GREEN);
waypointPaint.setStyle(Paint.Style.FILL);
currentCoordinatePaint = new Paint();
currentCoordinatePaint.setColor(Color.RED);
currentCoordinatePaint.setStyle(Paint.Style.FILL);
linePaint = new Paint();
linePaint.setColor(Color.BLACK);
linePaint.setStyle(Paint.Style.STROKE);
startCoordinatePaint = new Paint();
startCoordinatePaint.setColor(Color.BLUE);
startCoordinatePaint.setStyle(Paint.Style.FILL);
}
,然后removeAll()
并且JPanel上的revalidate()
会“解决”您的问题,但您还有其他无关的问题:
repaint()
布局,这是一件非常危险的事情相反,请考虑使用更灵活的代码,以适应您提供的任何大小的数据并避免空布局。例如,考虑以下代码在JPanel的paintComponent方法中绘制条形码:
null
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import javax.swing.*;
@SuppressWarnings("serial")
public class TestBarChart extends JPanel {
private static final int[] INIT_DATA = { 1, 2, 4, 5, 6, 9 };
protected static final int MIN_DATA_lENGTH = 5;
protected static final int MAX_DATA_LENGTH = 9;
private static final int MAX_VALUE = 9;
private static final int PREF_W = 300;
private static final int PREF_H = 240;
private BarChart2 barChart2 = new BarChart2(INIT_DATA, MAX_VALUE, PREF_W, PREF_H);
public TestBarChart() {
barChart2.setBorder(BorderFactory.createLineBorder(Color.BLUE));
JPanel chartsPanel = new JPanel(new GridLayout(1, 0));
chartsPanel.setLayout(new GridLayout(1, 0));
chartsPanel.add(barChart2);
JButton resetDataBtn = new JButton(new AbstractAction("Reset Data") {
@Override
public void actionPerformed(ActionEvent e) {
int dataLength = (int) ((MAX_DATA_LENGTH - MIN_DATA_lENGTH) * Math.random()) + MIN_DATA_lENGTH;
int[] data = new int[dataLength];
for (int i = 0; i < data.length; i++) {
data[i] = (int) (MAX_VALUE * Math.random()) + 1;
}
barChart2.setData(data, MAX_VALUE);
}
});
JPanel btnPanel = new JPanel();
btnPanel.add(resetDataBtn);
setLayout(new BorderLayout());
add(chartsPanel);
add(btnPanel, BorderLayout.PAGE_END);
}
private static void createAndShowGui() {
TestBarChart mainPanel = new TestBarChart();
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
请注意,如果重新调整GUI大小,条形图会重新调整大小以填充GUI。请注意,该图表可容纳任意数量的数据条,所有这些都取决于传入其中的数据数组的长度。
答案 1 :(得分:0)
您需要重新绘制组件。
getContentPane().validate();
getContentPane().repaint();