2013-06-17 2 views
1

так что у меня мои JButtonsКак я могу различать два разных JButtons в actionPerformed?

public static JButton textYes = new JButton("Yes"); 
public static JButton textNo = new JButton("No"); 

моего меню

public static String choiceReroll = ""; 
public static String menu = ""; 

и мой основной метод()

public static void main(String[] args) throws IOException { 
    Greed gui = new Greed(); 
    gui.launchFrame(); 
    redirectSystemStreams(); 

    Container contentPane = f.getContentPane(); 
    contentPane.add(new Greed()); 

    Scanner is = new Scanner(System.in); 
    System.out.println("Welcome to Greed..."); 
     do { 
    System.out.println("Would you like to play? (yes/no)"); 
    menu = is.next(); 
      switch (menu) { 
       case "yes": 
        jTextArea1.setText(null); 
        diceOne = 0; 
        diceTwo = 0; 
        diceThree = 0; 
        diceFour = 0; 
        diceFive = 0; 
        System.out.println("Rolling..."); 
        Game(); 

        break; 
       case "no": 
        System.out.println("Goodbye..."); 
        System.exit(0); 

        break; 
       default: 
        invalidInput(); 

        break; 
      } 
     } while (!"yes".equals(menu) || !"no".equals(menu)); 
} 

, то у меня есть мои actionListeners

textYes.addActionListener(this); 
textNo.addActionListener(this); 

как я могу сделать так, чтобы, когда я нажимаю одну кнопку или другую, он вводит текст, где он запрашивает ввод пользователя по адресу menu = is.next();

Я также хочу, чтобы он просто вводил текст, в зависимости от того, на какую кнопку он нажал. и он ввести текст, независимо от того, что переменная не задаёте

, например:

menu = is.next();

против

choiceReroll = is.next();

EDIT: подробнее ...

и у меня также есть мой методАкции()

public void actionPerformed(ActionEvent e) { 
    jTextArea1.setText(null); 
    if (box1.isSelected()) { 
     System.out.println("1 is selected"); 
     willRerollDiceOne = true; 
    } 
    else { 
     System.out.println("1 not selected"); 
     willRerollDiceOne = false; 
    } 
    if (box2.isSelected()) { 
     System.out.println("2 is selected"); 
     willRerollDiceTwo = true; 
    } 
    else { 
     System.out.println("2 not selected"); 
     willRerollDiceTwo = false; 
    } 
    if (box3.isSelected()) { 
     System.out.println("3 is selected"); 
     willRerollDiceThree = true; 
    } 
    else { 
     System.out.println("3 not selected"); 
     willRerollDiceThree = false; 
    } 
    if (box4.isSelected()) { 
     System.out.println("4 is selected"); 
     willRerollDiceFour = true; 
    } 
    else { 
     System.out.println("4 not selected"); 
     willRerollDiceFour = false; 
    } 
    if (box5.isSelected()) { 
     System.out.println("5 is selected"); 
     willRerollDiceFive = true; 
    } 
    else { 
     System.out.println("5 not selected"); 
     willRerollDiceFive = false; 
    } 

EDIT: я добавил actionPerformed для кнопок, но я только хочу показать один на данный момент

if (area == "menu") { 
     if(e.getSource() == textYes){ 
      menu = "yes"; 
     } 
     if(e.getSource() == textNo){ 
      menu = "no"; 
     } 
    } 

, но когда я нажимаю кнопку, он не обновляется, то почему? Как это исправить?

EDIT: добавлен «тест» распечатку внутри, если заявление

if ("menu".equals(area)) { 
      if(e.getSource() == textYes){ 
       menu = "yes"; 
       System.out.println("test"); 
      } 
      if(e.getSource() == textNo){ 
       menu = "no"; 
      } 

гравюр «тест» каждый раз, когда я нажимаю на кнопку Да

EDIT: Это остальная часть метода:

public static void main(String[] args) throws IOException { 
     Greed gui = new Greed(); 
     gui.launchFrame(); 
     redirectSystemStreams(); 

     Container contentPane = f.getContentPane(); 
     contentPane.add(new Greed()); 

     Scanner is = new Scanner(System.in); 
     System.out.println("Welcome to Greed..."); 
      do { 
     System.out.println("Would you like to play? (yes/no)"); 
     area = "menu"; 
     menu = is.next(); 
       switch (menu) { 
        case "yes": 
         jTextArea1.setText(null); 
         diceOne = 0; 
         diceTwo = 0; 
         diceThree = 0; 
         diceFour = 0; 
         diceFive = 0; 
         System.out.println("Rolling..."); 
         Game(); 

         break; 
        case "no": 
         System.out.println("Goodbye..."); 
         System.exit(0); 

         break; 
        default: 
         invalidInput(); 

         break; 
       } 
      } while (!"yes".equals(menu) || !"no".equals(menu)); 
     area = ""; 
    } 

    public static void Game() throws IOException { 
     rollDiceOne(); 
     rollDiceTwo(); 
     rollDiceThree(); 
     rollDiceFour(); 
     rollDiceFive(); 

     //displayDice(); 
     displayDiceValues(); 
     f.validate(); 
     f.repaint(); 

     choiceRerollDice(); 
    } 

    public static void choiceRerollDice() { 
     Scanner is = new Scanner(System.in); 
      do { 
       if (!canRerollDiceOne && !canRerollDiceTwo && !canRerollDiceThree && !canRerollDiceFour && !canRerollDiceFive) { 
       System.out.println("Sorry, but you may not reroll any more dice..."); 
       displayDiceValues(); 
       System.exit(0); 
      } 
      else { 
     System.out.println("Would you like to reroll any (more) dice? (yes/no)"); 
      choiceReroll = is.next(); 
       switch (choiceReroll) { 
        case "yes": 
         rerollDice(); 
         break; 
        case "no": 
         //endTurn(); 
         displayDiceValues(); 
         f.repaint(); 
         //calculatePlayer1Score(); 
         //System.out.println("Thank you for playing!"); 
         //System.out.println("Goodbye!"); 
         System.exit(0); 
        default: 
         invalidInput(); 
        } 
       } 
      } while (!"yes".equals(choiceReroll) || !"no".equals(choiceReroll)); 
    } 

    public static void rerollDice() { 
     Scanner is = new Scanner(System.in); 
     System.out.println("Which dice would you like to reroll? (Click the box under the dice!)"); 
     rollSel = is.next(); 
     switch (rollSel) { 
      case "roll": 
      if (willRerollDiceOne) { 
       if (canRerollDiceOne) { 
        diceOne = 0; 
        rollDiceOne(); 
        canRerollDiceOne = false; 
        box1.setEnabled(false); 
       } 
       else { 
        System.out.println("error"); 
       } 
      } 

      else { 
      } 
      if (willRerollDiceTwo) { 
       if (canRerollDiceTwo) { 
       diceTwo = 0; 
       rollDiceTwo(); 
       canRerollDiceTwo = false; 
       box2.setEnabled(false); 
       } 
       else { 
        System.out.println("error"); 
       } 
      } 
      else { 
      } 
      if (willRerollDiceThree) { 
       if (canRerollDiceThree) { 
       diceThree = 0; 
       rollDiceThree(); 
       canRerollDiceThree = false; 
       box3.setEnabled(false); 
       } 
      } 
      else { 
      } 
      if (willRerollDiceFour) { 
       if (canRerollDiceFour) { 
       diceFour = 0; 
       rollDiceFour(); 
       canRerollDiceFour = false; 
       box4.setEnabled(false); 
       } 
      } 
      else { 
      } 
      if (willRerollDiceFive) { 
       if (canRerollDiceFive) { 
       diceFive = 0; 
       rollDiceFive(); 
       canRerollDiceFive = false; 
       box5.setEnabled(false); 
       } 
      } 
      else { 
      } 
      box1.setSelected(false); 
      box2.setSelected(false); 
      box3.setSelected(false); 
      box4.setSelected(false); 
      box5.setSelected(false); 
      f.validate(); 
      f.repaint(); 
       break; 
      default: 
       System.out.println("Error..."); 
     } 

ответ

4

В вашем методе actionPerformed просто сделать:

public void actionPerformed(ActionEvent e) { 
    if(e.getSource() == textYes){ 
     //perform action when textYes clicked 
    } 
    if(e.getSource() == textNo){ 
     //perform action when textNo clicked 
    } 
} 

Вместо этого:

Scanner is = new Scanner(System.in); 
     System.out.println("Welcome to Greed..."); 
      do { 
     System.out.println("Would you like to play? (yes/no)"); 
     area = "menu"; 
     menu = is.next(); 
       switch (menu) { 
        case "yes": 
         jTextArea1.setText(null); 
         diceOne = 0; 
         diceTwo = 0; 
         diceThree = 0; 
         diceFour = 0; 
         diceFive = 0; 
         System.out.println("Rolling..."); 
         Game(); 

         break; 
        case "no": 
         System.out.println("Goodbye..."); 
         System.exit(0); 

         break; 
        default: 
         invalidInput(); 

         break; 
       } 
      } while (!"yes".equals(menu) || !"no".equals(menu)); 
     area = ""; 

Вы можете создать метод, который будет принимать входные данные в качестве параметра.

public void start(String menu){ 
       switch (menu) { 
        case "yes": 
         jTextArea1.setText(null); 
         diceOne = 0; 
         diceTwo = 0; 
         diceThree = 0; 
         diceFour = 0; 
         diceFive = 0; 
         System.out.println("Rolling..."); 
         Game(); 

         break; 
        case "no": 
         System.out.println("Goodbye..."); 
         System.exit(0); 

         break; 
        default: 
         invalidInput(); 

         break; 
       } 
} 

Затем в действие выполняется, просто сделать:

if(e.getSource() == textYes){ 
      start("yes"); 
     } 
     if(e.getSource() == textNo){ 
      start("no"); 
     } 
+0

, что помогло! и я также добавил другое редактирование внизу, если бы вы могли проверить это, это было бы потрясающе! Спасибо чувак! – pwnster1357

+0

Не сравнивайте строки с '=='. Используйте 'if (area.equals (" menu "))' –

+0

ok, я исправил его, но он по-прежнему не обновляется? Что я делаю не так? – pwnster1357

4

Как я могу различать два разных JButtons в actionPerformed? у меня есть мое actionListeners

textYes.addActionListener(this); 
textNo.addActionListener(this); 

Чистейший подход заключается в использовании отдельных слушателей. Вы можете сделать это с помощью анонимного внутреннего класса, как

textYes.addActionListener(new ActionListener() { 
    public void actionPerformed(ActionEvent e) { 
     // here you can do any necessary actions for the "Yes" button, 
     // like calling a specific method of the outer class which handles the event 
    } 
}); 

textNo.addActionListener(new ActionListener() { 
    public void actionPerformed(ActionEvent e) { 
     // here you can do any necessary actions for the "No" button, 
     // like calling a specific method of the outer class which handles the event 
    } 
}); 

Если вы хотите использовать только одно действие слушателя, то getSource() метод из ActionEvent позволяет получить доступ к источнику события, так как @ZouZou уже упоминалось.

См. Также How do you add an ActionListener onto a JButton in Java.

1

getSource() определяется классом объектСобытия, что ActionEvent является потомком (via java.awt.AWTEvent). Это дает ссылку на объект, событие пришло от

Или как установить команду для каждого JButton с помощью setActionComman(String command), а затем извлечь соответствующую команду действий Использование getActionCommand.

String cmd = event.getActionCommand(); 
1

Назначить разные ActionListener каждому полю. Я настоятельно рекомендую вам это сделать, а не расширять Контейнер, который имеет эти поля с ActionListener и передать его как this. Он сохраняет инкапсуляцию, он обеспечивает разделение проблем и его вопрос чистым, понятным кодом.

Таким образом, каждая кнопка должна иметь ActionListener добавил так:

textYes.addActionListener(new ActionListener() { 
    @Override 
    public void actionPerformed(Action event e) { 
     //logic 
    } 
}); 
Смежные вопросы