I want to change the size of a JPanel
. I tried setSize
(solutions proposed in this forum) but it did not work for me.
JFrame
code:
JFrame f =new JFrame();
f.setTitle("test");
f.setSize(300,400);
f.setLocationRelativeTo(null);
f.setResizable(false);
f.setLayout(null);
JPanel
code:
JPanel display= new JPanel();
display.setLayout(null);
JTextField txt = new JTextField(30);
display.add(txt,BorderLayout.NORTH);
display.setBackground(Color.gray);
display.setSize(30,17);
CodePudding user response:
Here is a complete and compilable example doing what you're trying to do.
import javax.swing.*;
import java.awt.*;
public class ResizableJPanel{
public static void main(String[] args){
JFrame frame = new JFrame(" with a panel");
Container content = frame.getContentPane();
content.setLayout(null);
JPanel panel = new JPanel();
panel.setOpaque( true);
panel.setBackground( Color.BLACK );
panel.setBounds( 200, 200, 400, 400);
content.add(panel);
frame.setSize(800, 800);
frame.setVisible(true);
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
}
You can change the values of the setBounds to move or resize the panel.
You've left out some important bits: How you add the panel to the JFrame? What is wrong with your current method?
If you're text field isn't showing up, it is because your JPanel is very small, and it has a null layout.
panel.setLayout(null);
JTextField field = new JTextField(30);
panel.add(field);
field.setBounds( 50, 110, 30, 17 );
That would add the field and give it a size. It's bad to use a null layout here because a layout manager will take care of the size of the TextField.