-2
// Creating buttons
JButton b1 = new JButton();
    b1.setText("Add");
    b1.setSize(100, 130);
    b1.setLocation(330, 70);
    b1.setBackground(Color.red);
    b1.setVisible(true);

// Creating second button       
JButton b2 = new JButton();
    b2.setText("Add");
    b2.setSize(100,100);
    b2.setLocation(0, 0);
    b2.setBackground(Color.blue);
    b2.setVisible(true);

//adding buttons to Jframe
f.add(b1);
f.add(b2);

The buttons don't appear when I run the program or sometimes, they do appear, but take up the whole JFrame completely

Paolo Forgia
  • 6,572
  • 8
  • 46
  • 58
user392500
  • 37
  • 8
  • 1
    1) For better help sooner, post a [MCVE] or [Short, Self Contained, Correct Example](http://www.sscce.org/). 2) Java GUIs have to work on different OS', screen size, screen resolution etc. using different PLAFs in different locales. As such, they are not conducive to pixel perfect layout. Instead use layout managers, or [combinations of them](http://stackoverflow.com/a/5630271/418556) along with layout padding and borders for [white space](http://stackoverflow.com/a/17874718/418556). 3) Setting a BG color will fail in some look and feels. Solution: use a colored icon instead. 4) Why .. – Andrew Thompson Jun 07 '17 at 04:59
  • .. do both buttons have the same text? 5) `b2.setVisible(true);` is only necessary for top level containers like `JFrame`, `JWindow`, `JDialog` etc. – Andrew Thompson Jun 07 '17 at 04:59

1 Answers1

2

Guess #1

Like almost all questions on the subject, you are calling f.setVisible(true) BEFORE you add the components to the UI

So, something like this should fix it

// In some other part of your code you've not provided us
//f.setVisible(true);

JButton b1 = new JButton();
b1.setText("Add");
b1.setBackground(Color.red);

JButton b2 = new JButton();
b2.setText("Add");
b2.setBackground(Color.blue);

f.add(b1);
f.add(b2);
f.setVisible(true);

Guess #2

You've not change the default layout manager of the JFrame, so it's still using a BorderLayout

Something like this should at least allow both buttons to be displayed without overlapping each other

f.setLayout(new FlowLayout());
f.add(b1);
f.add(b2);
f.setVisible(true);

I would recommend spending some time going through Laying out Components within a Container for more details

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • I would guess the last one as he mention that _"The buttons [...] take up the whole Jframe completely"_ – AxelH Jun 07 '17 at 05:13