Jframe is setting everything in the middle of the screen

Viewed 28

My Jframe is setting every component at the middle of the screen even if i set a specific location... for exmaple, the button and the searchbar are right next to each other. Here is the image of the program:

https://i.stack.imgur.com/NMKn1.png

thanks! It really seems easy but i can't figure out why it doesn't work

private String msg;
private JFrame frame;
private JButton button;
private JPanel panel;
private JTextField searchBar;
private JLabel name;
private JLabel logo;

public GUI() {
    this.frame = new JFrame();
    
    this.panel = new JPanel();
    this.panel.setBorder(BorderFactory.createEmptyBorder(300, 300, 300, 300));
    //this.panel.setLayout(new GridLayout(10, 10));
    
    this.frame.add(panel, BorderLayout.CENTER);
    this.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.frame.setTitle("emdb (ezon's movie database)");
    
    Icon icon = new ImageIcon("images/search.png");
    this.button = new JButton(icon);
    this.button.setBounds(100, 20, 25, 25);
    this.button.addActionListener(this);
    
    this.searchBar = new JTextField(30);
    this.searchBar.setBounds(100, 20, 200, 25);
    
    this.name = new JLabel();
    this.name.setBounds(50, 20, 80, 25);
    
    ImageIcon log = new ImageIcon("images/logo.png");
    this.logo = new JLabel(log);
    this.logo.setBounds(100, 0, 300, 150);
}

public void clearScreen() {
    this.panel.removeAll();
    this.panel.revalidate();
    this.panel.repaint();
}

public void searchScreen() {
    this.panel.add(this.searchBar);
    this.panel.add(this.button);
    this.panel.add(this.logo);
    this.frame.pack();
    this.frame.setVisible(true);
}

public void searchedScreen() {
    this.panel.add(this.name);
}

public String getMsg() {
    return(this.msg);
}

@Override
public void actionPerformed(ActionEvent e) {
    System.out.println("Searched: " + this.searchBar.getText());
    this.name.setText(this.searchBar.getText());
    this.msg = this.searchBar.getText();
    clearScreen();
    searchedScreen();
}
1 Answers

Swing was designed to be used with layout managers.

even if i set a specific location.

The job of the layout manager is to set the size and location of the component based on the rules of the layout manager. So your setBounds() statements will be overridden. Don't attempt to use setBounds().

the button and the searchbar are right next to each other

The default layout manager for a JPanel is the FlowLayout, which does exactly that.

this.frame.add(panel, BorderLayout.CENTER);

Change the above statement to:

this.frame.add(panel, BorderLayout.PAGE_START);

to see a difference.

Read the section from the Swing tutorial on Layout Managers for more information and examples. Decide which layout manager (or combination of layout managers on different panels) will achieve your desired layout.

Related