[英]Issue with adding a JPanel onto another JPanel
我正在制作游戏,因此拥有该游戏,因此当我按制作的菜单上的按钮时,它将加载游戏。 游戏和菜单均为JPanel
。 问题是,当我单击该按钮时,它将加载JPanel,但是键盘输入不起作用。 为什么会这样呢? 这是我的代码:
public class Menu extends JPanel {
static boolean load = false;
JButton play = new JButton("play");
GamePanel panel = new GamePanel();
public Menu(){
setLayout(new FlowLayout());
add(play);
setVisible(true);
play.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Runner.panel.setPreferredSize(new Dimension(570,700));
add(Runner.panel,0,0);
//repaint();
validate();
}
});
}
public void paint(Graphics g){
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
draw(g2d);
}
public void draw(Graphics2D g2d){
g2d.drawImage(getBulletImage(),0,0,null);
}
// gets the image file for the player class
public Image getBulletImage(){
ImageIcon ic = new ImageIcon("Menu.png");
return ic.getImage();
}
}
当单击该按钮,它增加了一个JPanel
在当前的顶部JPanel
。
阅读这篇文章, JPanel无法响应在相同上下文中被要求的键侦听器 。
重写paintComponent()
的方法JPanel
而不是压倒一切的paint()
方法。
样例代码:
@Override public void paintComponent(Graphics g){ super.paintComponent(g); // your custom painting }
重写getPreferredSize()方法,而不是setPreferredSize()
方法。 不要设置组件的大小,只需将其交给Layout Manager即可设置组件的大小和位置,以说明其用途。
样例代码:
@Override public Dimension getPreferredSize(){ return new Dimension(100,50); }
阅读更多我应该避免在Java Swing中使用set(Preferred | Maximum | Minimum)Size方法吗?
使用SwingUtilities.invokeLater()
确保EDT正确初始化。
阅读更多
尝试添加play.setFocusable(true); 和play.requestFocus(); 创建新的JPanel之后。 这应该将焦点放在新面板上并允许键盘输入
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.