JPanel 填充所有 JFrame 空间
我编写了这段代码来显示面板中的一组颜色:
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Palette {
public static void main(String[] args) {
JFrame frame = new JFrame("Panel");
palette.add(new Color(255, 0, 0));
palette.add(new Color(0, 255, 0));
palette.add(new Color(0, 0, 255));
int width = 100;
int height = 250;
int x = 0;
for (Color color : palette) {
JPanel panel = new JPanel();
panel.setSize(width, height);
panel.setLocation(x, 750);
panel.setBackground(new java.awt.Color(color.getColor()));
frame.add(panel);
x+=width;
}
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(1000, 1000);
frame.setVisible(true);
}
}
第两个面板位于正确的位置且尺寸正确。但最后一个将所有框架填充为蓝色。怎么了?
I have write this code for displaying some set of colors from panel:
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Palette {
public static void main(String[] args) {
JFrame frame = new JFrame("Panel");
palette.add(new Color(255, 0, 0));
palette.add(new Color(0, 255, 0));
palette.add(new Color(0, 0, 255));
int width = 100;
int height = 250;
int x = 0;
for (Color color : palette) {
JPanel panel = new JPanel();
panel.setSize(width, height);
panel.setLocation(x, 750);
panel.setBackground(new java.awt.Color(color.getColor()));
frame.add(panel);
x+=width;
}
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(1000, 1000);
frame.setVisible(true);
}
}
Two first panels in the right place and with right dimensions. But the last one fills all frame in blue color. What's wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您必须使用适当的布局管理器。默认情况下,JFrame 有一个
BorderLayout
。查看 LayoutManager 教程:
http://docs.oracle.com/ javase/tutorial/uiswing/layout/visual.html
You have to use the appropriate Layout Manager. A JFrame by default has a
BorderLayout
.Check out this tutorial for LayoutManagers:
http://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html