读书人

有关GUI的一个有关问题

发布时间: 2012-01-09 21:05:42 作者: rapoo

有关GUI的一个问题

Java code
import java.awt.FlowLayout;import javax.swing.JButton;import javax.swing.JFrame;public class Test111{    public static void main(String[] args) {        JFrame jf = new JFrame();        for(int i=0;i<100;i++){            JButton jb = new JButton("helloworld!");            jf.add(jb);        }        jf.setLayout(new FlowLayout(0));        jf.setSize(400, 300);        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);        jf.setVisible(true);    }}


上述代码:将100个JButton加入到一个JFrame中。
我想问下,怎样只实现垂直方向的滚动条?(水平方向不要滚动条,里面的Button随着窗口大小自动调整就可以了)
要求不用JScrollPane,因为这样它一行就给你排完了,不好看,getPreferredSize用着也不大方便。

[解决办法]
楼主没看过布局管理器?
Java code
 
package test.org.ross.util;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CardLayoutDemo implements ActionListener{
JPanel p1,p2,p3,p4;
int i=1;
JFrame f;
public CardLayoutDemo(){
f=new JFrame();//当做top-level组件
Container contentPane=f.getContentPane();
contentPane.setLayout(new GridLayout(2,1));

p1=new JPanel();
Button b=new Button("Change Card");
b.addActionListener(this);//当按下"Change Card"时,进行事件监听,将会有系统操作产生。
p1.add(b); //处理操作在52-64行.
contentPane.add(p1);

p2=new JPanel();
p2.setLayout(new FlowLayout());
p2.add(new JButton("first"));
p2.add(new JButton("second"));
p2.add(new JButton("third"));

p3=new JPanel();
p3.setLayout(new GridLayout(100,1));
for (int i = 0; i < 100; i++) {
p3.add(new JButton(""+i));
}

p4=new JPanel();
p4.setLayout(new CardLayout());
p4.add("one",p2);
p4.add("two",new JScrollPane(p3));
/*要显示CardLayout的卡片,除了用show(Container parent,String name)这个方法外
*,也可试试first(Container),next(Container),previous(Container),last(Container)这
*四个方法,一样可以达到显示效果。
*/
((CardLayout)p4.getLayout()).show(p4,"one");

contentPane.add(p4);

f.setTitle("CardLayout");
f.pack();
f.setVisible(true);

f.addWindowListener(
new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
}
);

}
public void actionPerformed(ActionEvent event){
switch(i){
case 1:
((CardLayout)p4.getLayout()).show(p4,"two");
break;
case 2:
((CardLayout)p4.getLayout()).show(p4,"one");
break;
}
i++;
if (i==3) i=1;
f.validate();
}
public static void main(String[] args){
new CardLayoutDemo();
}
}


[解决办法]
first(Container),next(Container),previous(Container),last(Container)

读书人网 >J2SE开发

热点推荐