把组件放到一个Panel上面,想达到FlowLayout的效果,让组件从左到又排列,到边界了就自动换行!
但组件太多,整个画面都没办法把所有组件显示出来,所以我想把这个Panel放到JScrollPane里面,用滚动条来显示所有组件,但放进去的结果是,窗口的宽度被认为是无限的,组件都摆成很长的一行了。两边的都看不见了,窗口只显示中间那部分组件了!
各位大哥,麻烦帮帮忙!我怎样保留JScrollPane的垂直滚动效果,而去掉水平的滚动? 
如果单纯使用HORIZONTAL_SCROLLBAR_NEVER,只是不显示滚动条而已,但效果还是在的。

解决方案 »

  1.   

    你设置一下panel的preferredSize属性试试
      

  2.   

    import java.awt.*;
    import javax.swing.*;
    import java.io.*; public class text
    { public static void main(String args[])
    {
    JFrame frm = new JFrame("test");
    FlowLayout  f = new FlowLayout(FlowLayout.LEFT,0,5);
    JPanel practicePanel = new JPanel();
    JPanel panel = new JPanel();
    panel.setLayout(f);
    practicePanel.setBackground(Color.yellow);
    JTextArea ta = new JTextArea(8,50);
    ta.setLineWrap(true);

    JScrollPane jScrollPane1 = new JScrollPane(panel,
    JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
    JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    jScrollPane1.getViewport().add(panel, null);  JScrollPane jScrollPane2 = new JScrollPane(ta,
    JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
    JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    jScrollPane2.getViewport().add(ta, null); 
        
    JButton bt = new JButton("结束本次练习");


    String str = "";
    int length; 

    try{ 
    FileReader reader = new FileReader("test.txt"); 
    BufferedReader br = new BufferedReader(reader); 
    String line;
    line = br.readLine();
            while (line != null) {
    str+=line;
    line = br.readLine();
            } br.close(); 
    reader.close(); 
    }catch(IOException e){  } 

    char c[] = new char[1];
    length = str.length();

    JLabel label[];
    label = new JLabel[length];
    for(int i = 0;i<length;i++){
    label[i] = new JLabel("");
    panel.add( label[i] );
    str.getChars(i,i+1,c,0);
    label[i].setText( String.valueOf(c) );
    }

    practicePanel.add(jScrollPane1);
    practicePanel.add(jScrollPane2);
    practicePanel.add(bt);

    frm.getContentPane().add(practicePanel);
    frm.setSize(650,420);
    frm.setLocationRelativeTo(null);
    frm.setVisible(true);}
    }
    只要建一个test.txt的文件,保存一篇长点的英语文章进去就可以见到效果了!!!代码可以运行的了!!!
    麻烦各位帮一下忙,我想把上面Label组成的Panel弄得跟下面的JTextArea一样大小,我是在做一个打字的软件!谢谢!
      

  3.   

    在practicePanel.add(jScrollPane1)前加上如下几句:int lines = length/50;  //其中50是你创建JTextArea时的列数。
    Dimension dim = ta.getPreferredSize();//获得ta大小//将panel的宽设置为ta的宽,高为所有Label加在一起的高度
    panel.setPreferredSize(new Dimension(dim.width,lines×ta.getFont().getSize()));
    //将jScrollPanel设置成和jScrollPane2一样
    jScrollPane1.setPreferredSize(jScrollPane2.getPreferredSize());