要提供一些可能有用的背景信息,我正在创建游戏pong,我决定添加一个转义/暂停菜单(当您按键盘上的ESC键时,会弹出一些设置菜单),我环顾四周,发现最好的方法是使用JLayeredPane并在顶部添加另一个JPanel。但是,当我将我的“ painter”类添加到JLayeredPane时,paint(Graphics g)方法停止被调用(将其添加到JFrame时效果很好)。
import javax.swing.*;
public class Game extends JFrame {
public static Painter painter;
public Game() {
setSize(500, 500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLayeredPane lp = getLayeredPane();
painter = new Painter();
add(lp);
}
public static void main(String[] args) {
Game frame = new Game();
frame.setVisible(true);
painter.repaint();
}
}
这是我的画家课
import java.awt.*;
import javax.swing.*;
public class Painter extends JPanel {
public void paint(Graphics g) {
System.out.println("Working");
super.paint(g);
}
}
我最初尝试使用add(lp);
而不是lp.add(painter);
,在这种情况下,paint方法从未被调用。通过执行add(lp)
,我得到了一个IllegalArgumentException,用于将容器的父代添加到自身。
答案 0 :(得分:0)
这是使用LayeredPane的方法:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;
public class Game extends JFrame {
public Game() {
setSize(250, 150);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLayeredPane lp = getLayeredPane();
//assign layout manager. otherwise you need to set content
//bounds (not recommended)
lp.setLayout(new BorderLayout());
Painter painter = new Painter();
lp.add(painter,1);
}
public static void main(String[] args) {
Game frame = new Game();
frame.setVisible(true);;
}
}
class Painter extends JPanel {
@Override
protected void paintComponent(Graphics g) { //do not override paint
super.paintComponent(g);
g.drawString("Working",50,50);
}
}