0

this is a very easy code because I just started learning java. how do I move the button to specific position/points. Please be brief and make your answer simple and easy to understand because I just started learning java.

this is my code:

            import javax.swing.*;
            import java.awt.*;
            import java.awt.event.*;
            public class finals extends JFrame implements ActionListener{
                JButton login = new JButton("Log-In");
                JButton enroll = new JButton("Enroll");
                JPanel con = new JPanel();
                JFrame frame = new JFrame();
                public finals(){
                    frame.setTitle("Enrollment");
                    setContentPane(con);
                    setLayout(new FlowLayout());
                    login.setLocation(122, 120);
                    con.add(login);
                    System.out.println(login.getLocation());
                    frame.add(con);

                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.setSize(300,150);
                    frame.setVisible(true);
                }
                public void actionPerformed(ActionEvent e){

                }
                public static void main(String Args[]){
                    new finals();
                }
            }
camickr
  • 321,443
  • 19
  • 166
  • 288

2 Answers2

2

make your answer simple and easy to understand

Don't attempt to specify a pixel location of a component! What is so special about (122, 12)? Nothing, its just a random number you picked.

Let the layout manager do its job. For example you can use a FlowLayout and set the alignment to CENTER so the component is centered on the row.

Or if you don't like that you can use a BoxLayout, and add a "horizontal strut" to the panel to help control positioning.

Read the section from the Swing tutorial on Layout Managers for more information and working examples.

I just started learning java.

Don't forget to check out the Table of Contents from the above tutorial link for more basic information about creating GUI's.

camickr
  • 321,443
  • 19
  • 166
  • 288
-1

You have to put your JPanel layout to "null". Just add this : con.setLayout(null);

  • It might be helpful describing why this fixes the problem and where exactly your code should be placed. – keeehlan Mar 05 '15 at 22:03
  • Please refrain from giving advice on GUI layout until you understand why that advice should not be offered (ever). Java GUIs have to work on different OS', screen size, screen resolution etc. 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 Mar 06 '15 at 02:24