2016-12-25 1 views
0

(이 질문이 제대로 수행되지 않은 경우 죄송합니다, 나는 새로운 해요. 그러나 적어도 나는 내 자신의 질문 요청하기 전에 많은 연구)새 구성 요소를 작성하고 여러 번 jpose를 삭제하는 방법은 무엇입니까?

안녕하세요. 나는 자바에서 블랙 잭 게임을 쓰고 있는데 꽤 거대한 회전을하고있다. 내 문제은 스윙 구성 요소의 여러 인스턴스를 처리하는 방법입니다. 호출 할 수 있습니다. 클래스 레벨이나 특정 메소드에서 컴포넌트 (예 : jpanels 및 jbutton)를 만드는 것이 더 낫지는 않습니다.

해당 메소드에서 해당 메소드를 작성하면 조치 리스너에서 볼 수 없지만 클래스 레벨로 작성하면 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 인 것처럼 전체 코드를 게시 할 수 있습니다.

편집 : Dan의 답은 실제로 정답 이었기 때문에 Daniel의 답변이 받아 들여졌으며 특정 프로그램에서 잘 작동했습니다. 고마워요, 메리 크리스마스! 내가 코드를 오해하지 않았다면

+0

들어 난 당신이 여기 http://stackoverflow.com/questions/11273267/java-open-a-new-window-by-clicking-a-button – IAmBlake

답변

1

첫째, menuPane.dispose()는 같은 menuPane을 사용하려는 경우 수행 할 작업을 할 dispose()

가장 좋은 방법이라는 기능이 없습니다 JPanel대로 작동하지합니다 메뉴. 대신 menuPane.dispose(); 사용 remove(menuPane); 다음 add(yourOtherPanel);

작업 예제의 의견

에 대한

import java.awt.Color; 
import java.awt.EventQueue; 
import java.awt.GridBagConstraints; 
import java.awt.GridBagLayout; 
import java.awt.Insets; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 

import javax.swing.JButton; 
import javax.swing.JFrame; 
import javax.swing.JLabel; 
import javax.swing.JPanel; 

@SuppressWarnings("serial") 
public class BlackjackGame extends JFrame implements ActionListener { 
    private JPanel menuPane; 
    private JLabel menuTitle; 
    private JButton playButton; 
    private JButton exitButton; 
    private JButton rulesButton; 

    private JPanel otherPane; 
    private JLabel otherTitle; 
    private JButton otherButton; 

    public BlackjackGame() { 
     mainMenu(); 
     otherPanel(); 
     setSize(400, 400); 
     setVisible(true); 
    } 

    private void mainMenu() { 

     menuPane = new JPanel(new GridBagLayout()); 
     GridBagConstraints c = new GridBagConstraints(); 
     menuPane.setBackground(new Color(125,0,0)); 
     menuPane.setBounds(620,220,175,250); 

     menuTitle = new JLabel("Welcome to Blackjack!"); 
     c.gridx = 1; 
     c.gridy = 0; 
     c.insets = new Insets(0,0,20,0); 
     menuPane.add(menuTitle, c); 

     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); 

     exitButton = new JButton("Exit!"); 
     exitButton.addActionListener(this); 
     c.gridx = 0; 
     c.gridy = 2; 
     c.gridwidth = 3; 
     menuPane.add(exitButton, c); 

     rulesButton = new JButton("Set rules."); 
     rulesButton.addActionListener(this); 
     c.gridx = 0; 
     c.gridy = 3; 
     c.gridwidth = 3; 
     menuPane.add(rulesButton, c); 

     add(menuPane); 
    } 

    private void otherPanel() { 
     otherPane = new JPanel(new GridBagLayout()); 
     GridBagConstraints c = new GridBagConstraints(); 
     otherPane.setBackground(new Color(125,0,0)); 
     otherPane.setBounds(620,220,175,250); 

     otherTitle = new JLabel("Welcome to Second Pane!"); 
     c.gridx = 1; 
     c.gridy = 0; 
     c.insets = new Insets(0,0,20,0); 
     otherPane.add(otherTitle, c); 

     otherButton = new JButton("Go Back!"); 
     otherButton.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); 
     otherPane.add(otherButton, c); 
    } 

    public void actionPerformed (ActionEvent event) { 
     if(event.getSource() == playButton) { 
      remove(menuPane); 
      add(otherPane); 
      validate(); 
      repaint(); 

     } else if(event.getSource() == otherButton) { 
      remove(otherPane); 
      add(menuPane); 
      validate(); 
      repaint(); 
     } 
    } 

    public static void main(String[] args) { 
     EventQueue.invokeLater(() -> new BlackjackGame()); 
    } 
} 

편집 그래서 자바 방법 remove()는이 경우에있는 컨테이너에서 개체를 제거합니다 JFrame. 이 메서드는 이동하는 개체에 영향을주지 않으므로 나중에 개체를 다시 사용할 수 있습니다. 따라서 위의 코드에서 remove()add() 메서드를 menuPaneotherPane을 다시 선언하거나 다시 작성하지 않고 사용할 수있는 이유는 무엇입니까?나는이

`private JPanel menuPane;` 

같은 개체를 선언하고 내가 그들을 똑바로 초기화하지 않고 객체를 참조 할 수 있도록 ActionListener를 원하기 때문에 다음 이것은이

menuPane = new JPanel(new GridBagLayout()); 

처럼 초기화하는 이유에 대해서는

떨어져. 줄 private JPanel menuPane;은 개체를 전역 변수로 만들고 줄 menuPane = new JPanel(new GridBagLayout());은 내가 사용하려고하는 것으로 만듭니다. JPanel menuPane = new JPanel(new GridBagLayout()); 대신이 방법을 사용하면 여러 변수에서 동일한 변수를 재사용 할 수 있습니다. 예를

private JPanel panel; 

private void createPanelOne() { 
    panel = new JPanel(new FlowLayout()); 
    ... 
    add(panel); 
} 

private void createPanelTwo() { 
    panel = new JPanel(new GridBagLayout()); 
    ... 
    add(panel); 
} 

를 들어이 일을 한 후, 당신은 당신의 JFrameJPanel들 것하고는 다를 수 있지만, 당신은 단지이가 그것을 선언하는 다른 방법 하나 JPanel

를 사용할 필요가 지역 변수를 만든다. 로컬 변수를 전달하지 않으면 사용중인 메서드 외부의 다른 메서드에서 로컬 변수를 볼 수 없습니다.

JPanel panel = new JPanel(); 

나는 이것이 사소한 일이라고 말하지 않을 것입니다. 나는 때로는 다른 메서드에서 볼 수 없어야하는 메서드에서 로컬 변수를 사용하는 것이 좋다고 생각합니다.

마지막으로 로컬 변수를 다른 메소드에 전달하면 사용자가 작성한 메소드에서 인수를 사용할 수 있습니다. 예를

public void setSomeValue(int val) { 
    someValue = val; 
} 
+0

좋아요 나를 보자로부터 도움을받을 수 있다고 생각 네가 한 짓을 내가 이해했다면. 먼저'public BlackjackGame()'에서'mainMenu()'와'otherPanel()'두 메소드를 호출하여 두 개의 창의 두 인스턴스를 생성했습니다. 그런 다음 필요에 따라'add()'와'remove()'를 사용하여 표시/비 표시합니다. 이것은 어떻게 작동하는지 오해 한 것 같습니다. 왜냐하면'remove()'가 창을 지우지 않고 사라지게 할 것이고, 다시 보길 원한다면 다시 시작해야하기 때문입니다. 나는. 'menuPane = new JPanel(); '도와 줘서 고마워! – heradsinn

+0

@heradsinn 물론. 나는 내 대답을 편집 할 뿐이다. 잠시 기다려주십시오. – Dan

+0

또 다른 것은 객체와 컴포넌트를 초기화하는 방법은'JPanel menuPane = new JPanel();', 처음에는'private JPanel menuPane;'을 선언하고 (JPanel infront가없는)'menuPane = 새 JPanel();'. 차이점과 찬성/반대 의견을 설명해 주시겠습니까? 감사합니다. – heradsinn

관련 문제