(很抱歉,如果這個問題沒有正確地做,我是新的,但至少我問我自己的問題之前研究了很多)如何多次創建新的和部署jcomponents?
你好。我正在用java編寫一個二十一點遊戲,並且它變得非常龐大。 我的問題是如何處理擺動組件的多個實例,我想你可以調用它。我無法弄清楚如何創建組件(如jpanels和jbuttons)作爲類級別或特定的方法。
如果我在他們相應的方法中創建它們,那麼我的動作偵聽器將無法看到它們,但是如果我將它們創建爲類級別,那麼當我調用dispose()
時,它們會被刪除。
class BlackjackGame extends JFrame implements ActionListener{
public void mainMenu(){
JPanel menuPane = new JPanel(new GridBagLayout()); //Init of main menu
GridBagConstraints c = new GridBagConstraints();
menuPane.setBackground(new Color(125,0,0));
menuPane.setBounds(620,220,175,250);
JLabel menuTitle = new JLabel("Welcome to Blackjack!");//Main menu-content
c.gridx = 1;
c.gridy = 0;
c.insets = new Insets(0,0,20,0);
menuPane.add(menuTitle, c);
JButton playButton = new JButton("Play!");
playButton.addActionListener(this);
c.gridx = 0;
c.gridy = 1;
c.gridwidth = 3;
c.ipadx = 25;
c.ipady = 25;
c.insets = new Insets(0,0,0,0);
menuPane.add(playButton, c);
JButton exitButton = new JButton("Exit!");
exitButton.addActionListener(this);
c.gridx = 0;
c.gridy = 2;
c.gridwidth = 3;
menuPane.add(exitButton, c);
JButton rulesButton = new JButton("Set rules.");
rulesButton.addActionListener(this);
c.gridx = 0;
c.gridy = 3;
c.gridwidth = 3;
menuPane.add(rulesButton, c);
this.add(menuPane,0);
}
//This is where I get problems
public void actionPerformed (ActionEvent event){
if(event.getSource() == playButton){
//I want the menuPane to disappear, and a transition into the game.
menuPane.dispose();
//Call method for the rest of the game.
}else if(event .getSource() etcetera etcetera){
etcetera etcetera
}
}
}
當這樣做時,actionlistener找不到我的組件,比如playButton或menuPane。但是,如果我曾經引進了他們作爲一流水平的對象:
class BlackjackGame extends JFrame implements ActionListener{
JPanel menuPane = new JPanel(new GridBagLayout());
JLabel menuTitle = new JLabel("Welcome to Blackjack!");
JButton playButton = new JButton("Play!");
JButton exitButton = new JButton("Exit!");
JButton rulesButton = new JButton("Set rules.");
public void mainMenu(){
//Rest of code
}
public void actionPerformed(ActionEvent event){
menuPane.dispose();
//Rest of code
}
}
...然後我打電話menuPane.dispose()
,我怎麼能找回來,當我想再次呼籲mainMenu()
?如果我想回到主菜單,那麼我需要創建一個menuPane的新實例,以及所有的按鈕,但是因爲它們是課程級別並且已經處理了,所以我不能。
請幫助我,謝謝!
PS。如果它有幫助,我可以發佈完整的代碼,因爲它是atm。
編輯:丹的答案已被接受,因爲它確實是正確的答案,它的工作對我的具體方案非常好。謝謝你,聖誕快樂!
我想你可以從這裏http://stackoverflow.com/questions/11273267/java-open-a-new-window-by-clicking-a-button – IAmBlake