Gasert
Gasert

Reputation: 35

Java swing - wrong size

so I have this problem. I wrote this code in Java Eclipse SDK 4.2.1. I haven't wrote it all here, actionPerformed method is irrelevant now and it is called from Main once. The problem is sometimes when I run it, one of the components just fills the whole window and overlaps all others. I tried changing sizes by random numbers for example from 400 to 350 and sometimes it worked and then it broke again. I'm probably missing something, I just don't know what. I searched other forums, but found nothing about it.

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Collections;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;


public class Window extends JFrame implements ActionListener
{
    JTextField field1;
    JTextField field2;

    public Window()
    {
        super("Main Window");
        setVisible(true);
        setSize(500, 500);
        setResizable(false);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        Initialize();
    }
    private void Initialize()
    {
        field1 = new JTextField();
        field2 = new JTextField();
        field1.setBounds(0, 0, 400, 100);
        field2.setBounds(0,100,400,100);
        add(field1);
        add(field2);
        field1.setBackground(Color.PINK);
        field1.setForeground(Color.RED);
        field2.setBackground(Color.PINK);
        field2.setForeground(Color.RED);
        JButton button = new JButton("Create");
        button.setBounds(0, 200, 400, 100);
        add(button);
        button.setBackground(Color.BLACK);
        button.setForeground(Color.YELLOW);
        button.addActionListener(this);

    }

Upvotes: 3

Views: 892

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285430

Your problem is that your code does not respect the layout manager being used as you're trying to add components as if the layout being used were null when in fact it isn't. The solution is to read up on and learn about layout managers, and use them; this includes avoiding calling setBounds(...). Note that a JFrame's contentPane uses BorderLayout by default. This information should help you get started. Also note that a wrong solution is to use a null layout. So if anyone suggests this, I urge you to ignore them.

Upvotes: 4

Related Questions