简体   繁体   中英

Size of JPanel in JFrame

I am trying to add a JPanel into my JFrame with a specific size. But whatever size I add to the JPanel, it always fills the whole entire JFrame. And I also tried to reposition the JButton according to my set position but it also doesn't work. Any recommendations or explanations anyone? Tq:P

import javax.swing.*;
import java.awt.event.*;
import java.awt.; 
import java.awt.image.;

public class Login {

//Creating a method just for the login page0
static void Login(){
    JFrame LoginFrame = new JFrame();
    JPanel Panel = new JPanel();

    Panel.setBounds(40,80,100,50);
    Panel.setBackground(Color.black);

    JButton Enter = new JButton();
    Enter.setBackground(Color.cyan);
    Enter.setBounds(50,100,80,30);
    Enter.setText("Enter");

    JButton Enter2 = new JButton();
    Enter.setBackground(Color.cyan);
    Enter.setBounds(50,100,80,30);
    Enter.setText("Enter");

    LoginFrame.setSize(420,720);
    LoginFrame.setBackground(Color.white);
    LoginFrame.setTitle("LoginFrame");
    LoginFrame.setVisible(true);
    LoginFrame.setLayout(null);
 }

public static void main(String[]args) {
    Login();
}
}

First of all, variable names should NOT start with an upper case character. These are Java conventions you will find in any text book or tutorial. Follow the examples.

I am trying to add a JPanel into my JFrame with a specific size

Why use a random size? Swing is designed so that each component will determine its own size so it will work on any platform with any Look and Feel.

Any recommendations

Don't use a null layout. Don't use setBounds(). Swing was designed to be used with layout managers. Layout managers make coding easier and more maintainable. Read the Swing tutorial on Layout Managers

Also, you actually need to "add" the buttons to the panel and "add" the panel to the frame. The above tutorial demos show how to do that.

If you are simply trying to change the size of the buttons then use:

button.setMargin( new Insets(20, 20, 20, 20) );

The button will be sized properly based on the text AND the extra space specified.

If you want your panel to have extra space then you can use:

panel.setBorder( new EmptyBorder(20, 20, 20, 20) );

Read the Swing tutorial on How to Use Borders for more information and examples.

or explanations

The JPanel uses a FlowLayout by default. So the layout manager is resetting the size/location based on the rules of the layout manager. If you want a different layout, then use a different layout manager.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM