-2

This is making a frame having jbutton having size equal to frame and the label is not getting at place which I desired.

public class Try extends JFrame {
    public Try(){
        JFrame f = new JFrame("TRY");
        JButton btn = new JButton(HI);
        JLabel l = new JLabel("label");
        btn.setBounds(50,100,100,50);
        l.setBounds(50,0,100,100);
        f.add(btn);
        f.add(l);***strong text***
        f.setSize(500,500);
        f.setVisible(true);
        f.getContentPane().setBackground(Color.white); 
    }

    public static void main(String[] args){
        Try t = new Try();
    }
} 
Donald Duck
  • 8,409
  • 22
  • 75
  • 99
  • 1
    you need try to use with a Layout Manager https://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html – Viet Feb 21 '17 at 07:05
  • Provide ASCII art or a simple drawing of the *intended* layout of the GUI at minimum size, and if resizable, with more width and height. (With the button and label positioned at those bounds, there is **lots** of extra space in the GUI, suggesting there will end up being more components. Show those extra components as well.) – Andrew Thompson Feb 21 '17 at 08:38
  • Indentation fixed – stealthjong Feb 21 '17 at 11:11

1 Answers1

-1

When You create a JFrame, by Default it comes with BorderLayout, so you need to specify which Layout you want to use for a frame.

f.setLayout(null);

Try null layout if you want to fully customise location and size of each JFrame component you will add. but remember that null layout is not the best choice :)

Helvijs
  • 160
  • 13
  • 2
    *"Try null layout if you want to.."* ..get lots of money for maintaining the buggy code (or want to get get fired). 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). – Andrew Thompson Feb 21 '17 at 14:26
  • I'm still learning Java in UNI , so my answers might not be perfect, just trying to help as much as I can. Thank you for correcting me, will remember it in future. – Helvijs Feb 21 '17 at 14:30
  • 2
    *"..just trying to help as much as I can"* The best help you could give at your current level of experience is to read the answers of the people who know Swing layout better than you (and refrain from answering). *"BUT REMEMBER THAT.."* Please stop SHOUTING at us. For **bold** use `**bold**` or for *italic* use `*italic*`. – Andrew Thompson Feb 21 '17 at 15:16
  • Thank you for correcting me. I highly respect your help and will refer to it in future. – Helvijs Feb 21 '17 at 15:20