0

I'm trying to write a program in which there are two buttons on a JFrame, with different actions for clicking them. But when I run my program, there is only one button, a "no" button when I want a yes and no button. My code:

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JFrame;

public class YesNoButton extends JButton{

  private static final int HEIGHT = 400;
  private static final int WIDTH = 400;

  public static void main(String[] args){

    JFrame jf = new JFrame();
    JButton yesButton = new JButton("YES");
    JButton noButton = new JButton("NO");
    jf.add(yesButton);
    jf.add(noButton);

    class PushListener implements ActionListener{

      public void actionPerformed(ActionEvent e){

        if (e.getSource() == yesButton) {
          System.out.println("YOU CLICKED YES");
        } else if (e.getSource() == noButton) {
          System.out.println("YOU CLICKED NO");
        }

      }

    }

    ActionListener listen = new PushListener();
    noButton.addActionListener(listen);
    yesButton.addActionListener(listen);

    jf.setSize(WIDTH,HEIGHT);
    jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    jf.setVisible(true);

  }

}

I want a "yes" and "no" button.

Derry
  • 371
  • 1
  • 13
  • 2
    `JFrame` has a `BorderLayout` by default. Place them in their respective locations (e.g. `jf.add(yesButton, BorderLayout.NORTH)` and `jf.add(yesButton, BorderLayout.SOUTH)`. If you don't specify this, the default is `BordeLayout.CENTER` and thus you are replacing the `JButton`. A more elegant solution is to make use of a `JPanel`. – Jyr Jun 20 '17 at 21:11
  • Or try a different layout, such as a `FlowLayout`: `jf.setLayout(new FlowLayout());` Or set the frame's layout to `null` and then use `setLocation` and `setSize` on the buttons to position and size them yourself. Try [here](https://docs.oracle.com/javase/tutorial/uiswing/layout/index.html) for more info on layout. – Kevin Anderson Jun 20 '17 at 21:19
  • I added the NORTH/SOUTH parameters to the jf.add(button, direciton), and it compiles but does not run; gives an IllegalComponentPosition exception – Derry Jun 20 '17 at 21:27
  • The way your code is written is the issue. You do not specify any sizes/formatting/layout for the buttons. When the JFrame is rendered, both buttons are added but no button occupies the whole frame over Yes button. Try formatting the buttons to co-exist inside JFrame and they will be accessible. – digidude Jun 20 '17 at 21:52

0 Answers0