Java 将JFrame从起始方法转换为另一个方法
我遇到一个问题,我试图从同一类中的另一个方法(addAButton)开始调用公共菜单方法中的JFrame,但该方法不起作用。我试着在公共菜单中调用addAButton,但我不能,因为我不能在该类中放置容器。代码:Java 将JFrame从起始方法转换为另一个方法,java,swing,jframe,Java,Swing,Jframe,我遇到一个问题,我试图从同一类中的另一个方法(addAButton)开始调用公共菜单方法中的JFrame,但该方法不起作用。我试着在公共菜单中调用addAButton,但我不能,因为我不能在该类中放置容器。代码: public class Menu { public Menu(Component component) { JFrame frame = new JFrame("..."); frame.setSize(new Dimension(1050
public class Menu {
public Menu(Component component) {
JFrame frame = new JFrame("...");
frame.setSize(new Dimension(1050, 700));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(component);
// Set up the content pane.
try {
frame.setContentPane(new JLabel(new ImageIcon(ImageIO
.read(new File("res/menuBackground.png")))));
} catch (IOException e) {
e.printStackTrace();
}
addComponentsToPane(frame.getContentPane());
// Display the window.
frame.pack();
frame.setVisible(true);
}
public static void addComponentsToPane(Container pane) {
//some code...
pane.setLayout(new BoxLayout(pane, BoxLayout.Y_AXIS));
addAButton("SP", "res/Singleplayer.png",
"res/Singleplayer_pressed.png", pane, true);
//other buttons...
}
public static void addAButton(final String text, String BtnIcon,
String PressBtnIcon, Container container, Boolean isEnabled) {
//stuff for buttons...
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (button.getText().equals("Q")) {
System.exit(0);
} else if (button.getText().equals("SP")) {
Component component = new Component();
//here I want to put frame.dispose to close this window for when the game window opens.
component.start();
} else if(button.getText().equals("O")) {
//here I want to put frame.dispose to close this window for when the options window opens.
Component.Options();
}
}
});
}
}
首先,公共
菜单
代码块不是一种方法。这是一个构造函数。它的功能是初始化和准备该类的新对象的字段
frame
变量是一个局部变量。如果在代码块内声明变量,则只能在该代码块内使用。局部变量在声明它的代码块结束时立即被丢弃
如果希望能够从不同的方法访问数据项,则表示该项是对象状态的一部分。也就是说,对象应该在其生存期内保持该项在其中,以便对其调用的下一个方法将使该项可用
当数据项是对象状态的一部分时,应将其声明为字段。也就是说,它不应该在任何方法或构造函数中声明,而是应该在所有方法和构造函数之前声明
声明字段后,可以在构造函数中对其进行初始化。然后可以从同一类中的任何方法访问该字段
public class Menu {
private JFrame frame; // This is the field declaration
public Menu( Component component ) {
frame = new JFrame("..."); // Here you just initialize, not declare.
... // Do the rest of your initializations
}
... // Other methods
}
现在,您可以在任何方法中使用
框
。如果Real怀疑论者的答案不能回答您的问题,请通过更详细的解释进一步澄清您的问题,如果可能,请更清楚地解释到底是什么错了。我不确定我是否能处理好你的问题(但我希望Real怀疑论者能做到!)。他做到了,我尽可能地解释清楚,但我自己几乎无法理解。当我试图解决它时,我遇到了更多的问题。太好了。我已经有一个加了他的答案,因为他的建议很好。谢谢你,我已经完全忘记了这一点。我只需要在JFrame中添加static,否则其他方法无法识别它。你太棒了。@animegaing:不要让JFrame或任何其他键非常量变量保持静态。这样做的基本原理是向后解决问题。更好的解决方案是修复其他代码,这样就不需要将JFrame变量设置为静态。@将JFrame设置为静态的原因是其他方法都是静态的。但它们不应该是——它们应该是访问对象当前状态的方法。