所以我正在玩 JPanel 和 JFrames,我注意到当我将它添加到 Jframe 对象时,我创建的 JPanel 没有显示。请注意,当我在我的 Jframe 构造函数中创建一个 JPanel 并在添加到 Jframe 之前提供 jpanel 参数时,它起作用了。但是现在我正在使用我创建的 JPanel 对象,它不再工作了。这就是我所做的。
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class MyGui extends JFrame {
MyMouseListener listen = new MyMouseListener();
public MyGui() {
setSize(500, 500);
//setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
getContentPane().setBackground(Color.WHITE);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
Panel panel = new Panel();
add(panel, BorderLayout.WEST);
//setVisible(true);
show();
}
public static void main(String[] a) {
MyGui gui = new MyGui();
}
}
class Panel extends JPanel {
MyMouseListener listen = new MyMouseListener();
public Panel() {
setPreferredSize(new Dimension(300, 300));
addMouseListener(listen);
setBackground(Color.YELLOW);
setLayout(new GridLayout(3, 1));
}
public void paint(Graphics g) {
super.paintComponents(g);
g.drawOval((int) Math.round(listen.p.getX()),
(int) Math.round(listen.p.getX()), 1, 1);
}
}
class MyMouseListener implements MouseListener {
Point p = new Point();
@Override
public void mouseClicked(MouseEvent e) {
System.out.println("Mouse was clicked");
}
@Override
public void mousePressed(MouseEvent e) {
p = e.getPoint();
System.out.println(p);
}
@Override
public void mouseReleased(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
}
编辑:实际上我认为我发现了错误。JPanel 有它的paint 方法,当被删除时允许Jframe 显示面板。但是我需要能够在 JPanel 上绘制东西。