我正在制作这个绘图程序项目,(更像是,扩展它),我遇到了一个讨厌的bug。我在BorderLayout南边的JPanel上添加了一个JLabel,但不仅没有添加到JPanel的南部,在我在JPanel上绘制内容后它也变得模糊了。我不明白为什么会发生这两件事。
班级代码:
import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Painter extends JPanel{
private int pointCount = 0; // count the number of points
// array of 10000 java.awt.Point references
private Point[] points = new Point[10000];
JLabel myCount = new JLabel();
// set up GUI and register mouse event handler
public Painter() {
myCount.setText("Points so far: " + pointCount);
add(myCount, BorderLayout.SOUTH);
// handle frame mouse motion event
addMouseMotionListener(
new MouseMotionAdapter() { // anonymous inner class
public void mouseDragged(MouseEvent event) {
if (pointCount < points.length) {
points[pointCount] = event.getPoint(); // find the point
++pointCount; // increment number of points in the array
repaint();
myCount.setText("Points so far: " + pointCount);
} // end if
} // end of mouseDragged method
} // end anonymous inner class
); // end of addMouseMotionListener
}// end Painter constructor
// draw ovals in a 4-by-4 bounding box at specified locations on window
public void paintComponent(Graphics g) {
super.paintComponents(g); // clears drawing area
// draw all points in the array
for (int i = 0; i < pointCount; i++) {
g.fillOval(points[i].x, points[i].y, 12, 12);
} // end for loop
} // end method paintComponent
} // end of Painter class
答案 0 :(得分:3)
第一个问题可以通过调用setLayout(new BorderLayout)来解决;作为构造函数的第一行
第二个问题可以通过从paintComponents中删除's'并只调用paintComponent
来解决