[英]Issue with adding a JPanel onto another JPanel
I am making a game and I have it so when I press a button on a menu I made, it loads the game. 我正在制作游戏,因此拥有该游戏,因此当我按制作的菜单上的按钮时,它将加载游戏。 Both the game and the menu are
JPanel
s. 游戏和菜单均为
JPanel
。 The problem is when I click the button it loads the JPanel but the keyboard input doesn't work. 问题是,当我单击该按钮时,它将加载JPanel,但是键盘输入不起作用。 Why might this be happening?
为什么会这样呢? Here is the my code:
这是我的代码:
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();
}
}
When the button is clicked in, it adds a JPanel
on top of the current JPanel
. 当单击该按钮,它增加了一个
JPanel
在当前的顶部JPanel
。
Read this post JPanel not responding to keylistener that is asked in the same context. 阅读这篇文章, JPanel无法响应在相同上下文中被要求的键侦听器 。
Override paintComponent()
method of JPanel
instead of overriding paint()
method. 重写
paintComponent()
的方法JPanel
而不是压倒一切的paint()
方法。
Sample code: 样例代码:
@Override public void paintComponent(Graphics g){ super.paintComponent(g); // your custom painting }
Override getPreferredSize() method instead of setPreferredSize()
method. 重写getPreferredSize()方法,而不是
setPreferredSize()
方法。 Don't set the size of the component and just hand over it to Layout Manager to set the size and position of the components that why it's made for. 不要设置组件的大小,只需将其交给Layout Manager即可设置组件的大小和位置,以说明其用途。
Sample code: 样例代码:
@Override public Dimension getPreferredSize(){ return new Dimension(100,50); }
Read more Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing? 阅读更多我应该避免在Java Swing中使用set(Preferred | Maximum | Minimum)Size方法吗?
Use SwingUtilities.invokeLater()
to make sure that EDT is initialized properly. 使用
SwingUtilities.invokeLater()
确保EDT正确初始化。
Read more 阅读更多
Try adding play.setFocusable(true); 尝试添加play.setFocusable(true); and play.requestFocus();
和play.requestFocus(); after you have created the new JPanel.
创建新的JPanel之后。 This should put the focus in the new panel and allow keyboard input
这应该将焦点放在新面板上并允许键盘输入
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.