亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

JLabel 復制自身,如果窗口被調整大小

JLabel 復制自身,如果窗口被調整大小

喵喵時光機 2021-12-30 17:27:04
我正在編寫一個簡單的圖表,您可以在 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);    }標簽在應用程序啟動時顯示。如果我調整應用程序窗口的大小,標簽將顯示在整個窗口中。(見截圖)如何避免標簽重復?我假設,在窗口重新粉刷后,程序會在面板中添加相同的標簽。如果我寫add(jLabelY);repaint();在該paintComponent()方法中,此錯誤發生在應用程序啟動時。我也嘗試將面板放入一個FlowLayout,但沒有做任何更改。
查看完整描述

1 回答

?
倚天杖

TA貢獻1828條經驗 獲得超3個贊

paintComponent()Swing 幾乎可以在任意時間調用(每當組件需要重繪時;例如在調整大小時)。因此,它通常應該是無副作用的。但是,您習慣于paintComponentadd()標簽標記為面板的子項,而您永遠不會刪除這些子項。因此,每次您的面板被重繪時,都會為其子項添加兩個標簽。super.paintComponent()然后將它們全部涂上。

對此的一種解決方案是將兩個標簽保留為面板的字段,并且僅在paintComponent(調用之前super.paintComponent())更新它們的位置


查看完整回答
反對 回復 2021-12-30
  • 1 回答
  • 0 關注
  • 165 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號