0

I wrote a simple program to see the effects of the add and remove methods in java and for whatever reason the following code does not display the OK button. Can anyone tell me why? I am thoroughly confused as it should work just fine.

import javax.swing.*;

public class MyFrameWithComponents {
        public static void main(String[] args){
        JFrame frame = new JFrame("Adding and removing components.");
        JButton OK = new JButton("OK");
        JButton Cancel = new JButton("Cancel");

        frame.add(OK);
        frame.add(Cancel);

        frame.remove(Cancel);

        frame.setSize(400 , 400);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}
alex2410
  • 10,904
  • 3
  • 25
  • 41

2 Answers2

0

You need to set the size and the location >>

    JButton OK = new JButton("OK");
    OK.setSize(50,50);
    OK.setLocation(175, 170);
  • Java GUIs might have to work on a number of platforms, on different screen resolutions & using different PLAFs. As such they are not conducive to exact placement of components. To organize the components for a robust GUI, instead use layout managers, or [combinations of them](http://stackoverflow.com/a/5630271/418556), along with layout padding & borders for [white space](http://stackoverflow.com/q/17874717/418556). – Andrew Thompson Nov 24 '13 at 00:11
  • you are also wrong his `JFrame` has a layoutManager he must not to set size and position – alex2410 Nov 24 '13 at 01:36
  • @alex2410 i can't see that "layoutManager" in his code can you please show us ? – Mutasim Ali Nov 24 '13 at 06:45
  • His frame has borderlayout as default – alex2410 Nov 24 '13 at 12:16
0

Seems your problem in next:

Your JFrame has a BorderLayout as default you call frame.add(OK); for adding your button as default to Center of container, then you call frame.add(Cancel); it "override" your first addition, because of that you don't see your button, because you delete cancel button.

For example, if you use frame.add(OK,BorderLayout.WEST); you see your button.

Also read more about LayoutManager and BorderLayout

alex2410
  • 10,904
  • 3
  • 25
  • 41