我正在編寫一個簡單的圖表,您可以在 x、y 軸上顯示一些點。public class GraphPlotter extends JPanel { private static final long serialVersionUID = 1L; /** Default frame size X for frame in pixels */ private final int DEFAULT_FRAME_SIZE_X = 800; /** Default frame size Y for frame in pixels */ private final int DEFAULT_FRAME_SIZE_Y = 600; /** Padding to Frame */ private final int PAD = 30; /** Radius of dot */ private final int DOT_RADIUS = 3; /** Padding of label */ private final int LABEL_PAD = 10; /** Height of label */ private final int LABEL_HEIGHT = 10; /** Width of label */ private final int LABEL_WIDTH = 100; /** Max value for x to print */ private int maxValueForX; /** Scale factor depending to y*/ private int maxValueForY; /** Label for the x axis */ private String labelForX = "time"; /** Label for the y axis */ private String labelForY; /** * List with points to draw. It holds the y coordinates of points. x * coordinates are spaced */ private List<Integer> dataPoints = new ArrayList<>(); /** * * Constructor of this class * */ public GraphPlotter(ArrayList<Integer> dataPoints, String labelForY) { this.dataPoints = dataPoints; this.maxValueForX = dataPoints.size(); this.maxValueForY = Collections.max(dataPoints); this.labelForY = labelForY; JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.getContentPane().add(this); f.setSize(this.DEFAULT_FRAME_SIZE_X + PAD, this.DEFAULT_FRAME_SIZE_Y + PAD); f.setLocationRelativeTo(null); f.setVisible(true); }標(biāo)簽在應(yīng)用程序啟動時顯示。如果我調(diào)整應(yīng)用程序窗口的大小,標(biāo)簽將顯示在整個窗口中。(見截圖)如何避免標(biāo)簽重復(fù)?我假設(shè),在窗口重新粉刷后,程序會在面板中添加相同的標(biāo)簽。如果我寫add(jLabelY);repaint();在該paintComponent()方法中,此錯誤發(fā)生在應(yīng)用程序啟動時。我也嘗試將面板放入一個FlowLayout,但沒有做任何更改。
1 回答

倚天杖
TA貢獻(xiàn)1828條經(jīng)驗 獲得超3個贊
paintComponent()
Swing 幾乎可以在任意時間調(diào)用(每當(dāng)組件需要重繪時;例如在調(diào)整大小時)。因此,它通常應(yīng)該是無副作用的。但是,您習(xí)慣于paintComponent
將add()
標(biāo)簽標(biāo)記為面板的子項,而您永遠(yuǎn)不會刪除這些子項。因此,每次您的面板被重繪時,都會為其子項添加兩個標(biāo)簽。super.paintComponent()
然后將它們?nèi)客可稀?/p>
對此的一種解決方案是將兩個標(biāo)簽保留為面板的字段,并且僅在paintComponent
(調(diào)用之前super.paintComponent()
)更新它們的位置
添加回答
舉報
0/150
提交
取消