[英]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.