为了账号安全,请及时绑定邮箱和手机立即绑定

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 关注
  • 212 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号