2013-03-08 14 views
7

Sto provando a cambiare il mio pulsante dicendo "Start" a "Stop" quando clicco su di esso. Il mio tentativo di farlo è sotto, l'ho cercato e ho provato a copiare le guide ma non vedo cosa sto sbagliando. Potrei mancare un po '"}" perché ho lasciato fuori molto del codice che è irrilevante. Qualcuno può vedere cosa sto facendo male?Rinominare un pulsante dopo aver cliccato - Java JButton

import java.awt.*; 
import java.awt.event.*; 
import javax.swing.*; 
import javax.swing.event.*; 

public class PipeGameApp extends JFrame implements ActionListener { 

    private static int BOARD_SIZE = 11; 
    private PipeGame game;  // The model 
    private PipeGameView view;  // The view 

    // This constructor builds the window 
    public PipeGameApp(String title) { 
     super(title); 

     game = new PipeGame(BOARD_SIZE); 
     view = new PipeGameView(game); 

     //THE TOP BAR 
     JPanel topBar = new JPanel(); 
     JButton startButton = new JButton("Start"); 
     startButton.addActionListener(this); 



     ButtonGroup bg1 = new ButtonGroup(); 
     JRadioButton rb1 = new JRadioButton("2 minutes", true); 
     rb1.addActionListener(this); 


     JRadioButton rb2 = new JRadioButton("10 minutes", false); 
     JRadioButton rb3 = new JRadioButton("No Time Limit", false); 
     bg1.add(rb1); 
     bg1.add(rb2); 
     bg1.add(rb3); 





     topBar.add(startButton); 
     topBar.add(rb1); 
     topBar.add(rb2); 
     topBar.add(rb3); 
     //END OF TOP BAR 

     //THE BOTTOM BAR 
     JPanel bottomBar = new JPanel(); 
     JLabel timeLeft = new JLabel("Time Left: "); 
     JProgressBar bar = new JProgressBar(); 
     bottomBar.add(timeLeft); 
     bottomBar.add(bar); 
     bottomBar.setVisible(false); 
     //end of bottom 

     /* 
     //bottom 2 
     int fscore=10; 
     JPanel bottomBar2 = new JPanel(); 
     JLabel score = new JLabel("Final score:" + fscore); 
     bottomBar2.add(score); 
     bottomBar2.setVisible(false); 
     */ 


     getContentPane().add(view); //CHANGE LOCATION OF BOARD GAME HERE BorderLayout.SOUTH 

     getContentPane().add(topBar, BorderLayout.NORTH); 
     getContentPane().add(bottomBar, BorderLayout.SOUTH); 

     //getContentPane().add(bottomBar2, BorderLayout.SOUTH); 



     // Add the listeners to the view's buttons 
     for (int r = 0; r < BOARD_SIZE; r++) { 
      for (int c = 0; c < BOARD_SIZE; c++) { 
       view.getButton(r, c).addActionListener(new ActionListener() { 
        public void actionPerformed(ActionEvent e) { 
         handleTileSelection(e); 
        } 
       }); 
      } 
     } 

     setDefaultCloseOperation(EXIT_ON_CLOSE); 
     //setSize(446,466); 
     setSize(446, 530); 
     setResizable(false); 
    } 

    // Handle a Tile Selection. Just change the model and update the view. 
    private void handleTileSelection(ActionEvent e) { 
     // Find the row and column of the pressed button, then make the change 
     int r = 0, c = 0; 
     for (int i = 0; i < BOARD_SIZE; i++) { 
      for (int j = 0; j < BOARD_SIZE; j++) { 
       if (e.getSource() == view.getButton(i, j)) { 
        if (game.placePipe(i, j)) { 
         view.update(); 
        } 
        return; 
       } 
      } 
     } 
    } 

    // This is where it all begins 
    public static void main(String[] args) { 
     new PipeGameApp("The Frantic Pipe Layer").setVisible(true); 
    } 

    @Override 
    public void actionPerformed(ActionEvent ae) { 
     startButton.setText("asdf"); 
    } 
} 
+0

Vedere la modifica alla mia risposta. Il tuo non è un problema di ombreggiamento variabile ma piuttosto di portata variabile. Sono sorpreso che il tuo codice venga compilato poiché non hai un riferimento di classe a startButton. O in effetti non è compilabile? –

risposta

5

Il problema è uno di portata variabile limitata. La variabile startButton viene dichiarata nel costruttore e quindi è visibile solo nel costruttore. Devi dichiararlo nella classe e non riscriverlo nel costruttore, permettendo al resto della classe di "vedere" la variabile e usarla.

cioè, cambiare questo:

public class PipeGameApp extends JFrame implements ActionListener { 

    private static int BOARD_SIZE = 11; 
    private PipeGame game;  // The model 
    private PipeGameView view;  // The view 

    public PipeGameApp(String title) { 

     JButton startButton = new JButton("Start"); 
     startButton.addActionListener(this); 
     // etc... 

a questo:

public class PipeGameApp extends JFrame implements ActionListener { 

    private static int BOARD_SIZE = 11; 
    private PipeGame game;  // The model 
    private PipeGameView view;  // The view 
    private JButton startButton; // *** note change *** 

    public PipeGameApp(String title) { 

     startButton = new JButton("Start"); // *** note change *** 
     startButton.addActionListener(this); 
     // etc... 

alternativa:

  • utilizzare Un JToggleButton
  • Oppure utilizzare l'oggetto restituito dal metodo del ActionEvent getSource() e impostare il suo nuovo stato basato su i ts corrente stato.

Per esempio,

@Override 
public void actionPerformed(ActionEvent ae) { 
    Object source = ae.getSource(); 
    if (source instanceof JButton) { 
     if (ae.getText().equals("Start")) { 
      ae.setText("Stop"); 
      // do other stuff 
     } else if (ae.getText().equals("Stop")) { 
      ae.setText("Start"); 
      // do more stuff 
     } 
    } 
} 

Per quanto riguarda "I might be missing some "}" because I left out a lot of the code that's irrelevant." Si prega di mettere nello sforzo in modo che ciò non accada. Quel "}" mancante non dovrebbe mancare e rende più difficile per noi capire il tuo codice e aiutarti. Se stai chiedendo agli altri di impegnarti per aiutarti nel loro tempo libero, non ti sta chiedendo troppo di non pubblicare il junk code.

+0

Grazie mille, terrò a mente di pubblicare tutto il mio codice. Penso che userò il metodo getSource poiché ho bisogno dei pulsanti per spostarmi. – user1692517

+0

@ user1692517: felice che tu abbia risolto. Per favore comprendi però che "tutto il mio codice" è spesso troppo. La cosa più importante è che non pubblichi il codice junk come hai fatto inizialmente. Quella coppia mancante non è irrilevante, ma in realtà è abbastanza importante. Ha causato un aiutante, Ravindra, a sprecare il suo prezioso tempo libero cercando di aiutarti con un non-problema, il che non è giusto per lui. –

2

È stata mantenuta la parentesi graffa del costruttore dopo il metodo main. Ecco il codice corretto.

public PipeGameApp(String title) { 
    super(title); 

    JPanel topBar = new JPanel(); 
    JButton startButton = new JButton("Start"); 
    startButton.addActionListener(this); 
} 

public static void main(String[] args) { 
    new PipeGameApp("The Frantic Pipe Layer").setVisible(true); 
} 

@Override 
public void actionPerformed(ActionEvent ae) { 
    startButton.setText("asdf"); 
} 
Problemi correlati