[英]JAVA : How to resize JPanel
i want to change size of jpanel, i tried setSize (solutions proposed in this forum) but it did not work for me JFrame code:我想更改 jpanel 的大小,我尝试了 setSize(本论坛中提出的解决方案),但它对我不起作用 JFrame 代码:
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);
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.您可以更改 setBounds 的值以移动或调整面板大小。
You've left out some important bits: How you add the panel to the JFrame?您遗漏了一些重要信息:如何将面板添加到 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.如果您的文本字段没有显示,那是因为您的 JPanel 非常小,并且它具有 null 布局。
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.在这里使用 null 布局很糟糕,因为布局管理器会处理 TextField 的大小。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.