当前位置:编程学习 > JAVA >>

java初学者,求高手指教关于swing中。。。一个小问题

在下面的代码中,如何在container中改变panel的size?

import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.WindowConstants;


public class JRadioButtonDemo extends JFrame{
public JRadioButtonDemo(){
Container c= getContentPane();
JPanel jp= new JPanel(new FlowLayout(1,5,5));
JRadioButton jr1= new JRadioButton("red");
JRadioButton jr2= new JRadioButton("green");
JRadioButton jr3= new JRadioButton("yellow");
jp.add(jr1);
jp.add(jr2);
jp.add(jr3);
c.add(jp);

jp.setBackground(Color.BLUE);
setSize(400,200);
jp.setPreferredSize (new Dimension (200,50));
setTitle("whatever");
setVisible(true);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args){
new JRadioButtonDemo();
}
}
swing java --------------------编程问答-------------------- 你c.add(jp);默认是加到BorderLayout.CENTER,所以你无论怎么设置都是没有用的,api文档是这样说的
The components are laid out according to their preferred sizes and the constraints of the container's size. The NORTH and SOUTH components may be stretched horizontally; the EAST and WEST components may be stretched vertically; the CENTER component may stretch both horizontally and vertically to fill any space left over.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.WindowConstants;


public class JRadioButtonDemo extends JFrame{
public JRadioButtonDemo(){
Container c= getContentPane();
JPanel jp= new JPanel(new FlowLayout(1,5,5));
JRadioButton jr1= new JRadioButton("red");
JRadioButton jr2= new JRadioButton("green");
JRadioButton jr3= new JRadioButton("yellow");
jp.add(jr1);
jp.add(jr2);
jp.add(jr3);
c.add(jp);


jp.setBackground(Color.BLUE);
setSize(800,800);
jp.setPreferredSize (new Dimension (300,200));

jp.setMaximumSize(new Dimension(200,100));
jp.setMinimumSize(new Dimension(100,50));
jp.setSize(50,25);
c.remove(jp);
c.add(jp,BorderLayout.SOUTH);
setTitle("whatever");
setVisible(true);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);


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

你可以把c.remove(jp);
c.add(jp,BorderLayout.SOUTH);
这两行去掉,可以看到无论怎么设置大小都无济于事
把该panel加到SOUTH后,可以该表PrerrencedSize从而改变大小

JAVA的容器排列和大小问题其实很复杂的,可以看看这个
http://docs.oracle.com/javase/tutorial/uiswing/layout/problems.html
补充:Java ,  Java相关
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,