java中往JFrame添加Panel控件只显示一个,求解
publicclassMapGridextendsPanel{//地图格子坐标intx;inty;//格子颜色Colorcolor;publicvoidpaint(Gra...
public class MapGrid extends Panel {
//地图格子坐标
int x;
int y;
//格子颜色
Color color;
public void paint(Graphics g) {
g.setColor(color);
g.fill3DRect(x, y, 20, 20, true);
}
public MapGrid(int x,int y,Color color)
{
this.x=x;
this.y=y;
this.color=color;
}
}
public class Test {
public static void main(String[] args) {
JFrame frame=new JFrame();
frame.setBounds(200, 200, 300, 300);
//MapGrid继承Panel
MapGrid g1=new MapGrid(0,0,Color.gray);
MapGrid g2=new MapGrid(20,0,Color.blue);
MapGrid g3=new MapGrid(40,0,Color.green);
frame.add(g1);
frame.add(g2);
frame.add(g3);
frame.setVisible(true);
}
} 展开
//地图格子坐标
int x;
int y;
//格子颜色
Color color;
public void paint(Graphics g) {
g.setColor(color);
g.fill3DRect(x, y, 20, 20, true);
}
public MapGrid(int x,int y,Color color)
{
this.x=x;
this.y=y;
this.color=color;
}
}
public class Test {
public static void main(String[] args) {
JFrame frame=new JFrame();
frame.setBounds(200, 200, 300, 300);
//MapGrid继承Panel
MapGrid g1=new MapGrid(0,0,Color.gray);
MapGrid g2=new MapGrid(20,0,Color.blue);
MapGrid g3=new MapGrid(40,0,Color.green);
frame.add(g1);
frame.add(g2);
frame.add(g3);
frame.setVisible(true);
}
} 展开
展开全部
因为JFrame默认的布局管理器为BorderLayout,其默认添加在BorderLayout.CENTER上,以上你的代码,你是想要同时显示3个panel,可以按照以下来设置
farme.add(BorderLayout.NORTH,g1);
frame.add(BorderLayout.CENTER,g2);
frame.add(BorderLayout.SOUTH,g3);
若这样不能达到你的效果,还可以这样
JFrame frame = new JFrame(new FlowLayout());
frame.add(g1);
frame.add(g2);
frame.add(g3);
希望对你有帮助
farme.add(BorderLayout.NORTH,g1);
frame.add(BorderLayout.CENTER,g2);
frame.add(BorderLayout.SOUTH,g3);
若这样不能达到你的效果,还可以这样
JFrame frame = new JFrame(new FlowLayout());
frame.add(g1);
frame.add(g2);
frame.add(g3);
希望对你有帮助
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询