[英]Getting a JFrame from the starting method into another method
我有一個問題,我試圖從同一類中的另一個方法( addAButton )的開頭調用公共Menu方法中的JFrame,但無法正常工作。 我試過在公共Menu內調用addAButton ,但是我不能,因為我不能在該類中放置容器。 代碼:
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();
}
}
});
}
}
首先,公共Menu
代碼塊不是方法。 它是一個構造函數。 它的功能是初始化並准備此類的新對象的字段。
frame
變量是局部變量 。 如果在代碼塊內聲明變量,則只能在該代碼塊內使用該變量。 聲明了它的代碼塊結束時,將立即丟棄局部變量。
如果您希望能夠通過不同的方法訪問數據項,則意味着該數據項是對象狀態的一部分。 也就是說,對象應在整個生命周期內一直保留該項目,以便在其上調用的下一個方法將使該項目可用。
當數據項是對象狀態的一部分時,應將其聲明為field 。 也就是說,不應在任何方法或構造函數內部聲明它,而應在所有方法和構造函數之前聲明它。
聲明字段后,可以在構造函數中對其進行初始化。 然后,您可以從同一類中的任何方法訪問該字段。
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
}
現在,您可以以任何方法使用場frame
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.