我正在编写一个简单的图表,您可以在 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 几乎可以在任意时间调用(每当组件需要重绘时;例如在调整大小时)。因此,它通常应该是无副作用的。但是,您习惯于paintComponent将add()标签标记为面板的子项,而您永远不会删除这些子项。因此,每次您的面板被重绘时,都会为其子项添加两个标签。super.paintComponent()然后将它们全部涂上。
对此的一种解决方案是将两个标签保留为面板的字段,并且仅在paintComponent(调用之前super.paintComponent())更新它们的位置
添加回答
举报
0/150
提交
取消
