简体   繁体   English

我有一个JLabel和JPanel的BorderLayout的问题

[英]I have an issue with a JLabel and the BorderLayout of a JPanel

I was working on this drawing program project, (more like, extending it) and I came upon a nasty bug. 我正在制作这个绘图程序项目,(更像是,扩展它),我遇到了一个讨厌的bug。 I added a JLabel on a JPanel, on the South of the BorderLayout, but not only it does not get added into the south of the JPanel, it also gets blurry after I paint something on the JPanel. 我在BorderLayout南边的JPanel上添加了一个JLabel,但不仅没有添加到JPanel的南部,在我在JPanel上绘制内容后它也变得模糊了。 What I do not understand is why these two things are happening. 我不明白的是为什么这两件事情正在发生。

Code of the Class: 班级代码:

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

First problem can be solved by calling setLayout(new BorderLayout); 第一个问题可以通过调用setLayout(new BorderLayout)来解决; as the first line of your constructor 作为构造函数的第一行

2nd problem can be solved by removing the 's' from paintComponents and just calling paintComponent 第二个问题可以通过从paintComponents中删除's'并只调用paintComponent来解决

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM