如何在小程序中的 JPanel 之间切换?在 JFrame 中的 JPanel 之间切换非常简单,我这样做:
frame.remove(mainMenu); //remove the old jpanel
frame.add(game); //add the new jpanel
game.createImage(); //runs createVolatileImage(width, height)
//in the other class (JPanel)
frame.revalidate();
frame.repaint();
requestFocus();
但是,如何在小程序中复制此内容?当我在小程序中尝试此操作时,当我尝试在新 JPanel 中创建的图像上运行 image.getGraphics()
时,我收到 nullPointerException。
最佳答案
- 切换 JPanel 的最佳方法是使用 CardLayout ( tutorial )。如果操作正确,无论您的 GUI 是 JFrame、JDialog、JApplet...等,这都将起作用。
- 您的 NullPointerException 可能与您的交换 View 无关。要调试此问题,您需要更多信息。
- 这可能是由于您的图像变量为空,可能是由于尝试将其作为文件而不是资源读取。
关于java - 如何在小程序中的 JPanel 之间切换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25125848/