当数据多出了范围的时候自动会有滚动条。

解决方案 »

  1.   


    import java.awt.AWTEvent;
    import java.awt.Dimension;
    import java.awt.event.WindowEvent;import javax.swing.JFrame;
    import javax.swing.JList;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    public class Frame1 extends JFrame {
      JPanel contentPane;
      //JList jList1 = new JList();
      String[] str = {"Math","English","Physics","Chemic","Biology","Politics"};
      JList jList1 = new JList(str);
      JScrollPane listScrollPane = new JScrollPane(jList1);
      //Construct the frame
      public Frame1() {
        enableEvents(AWTEvent.WINDOW_EVENT_MASK);
        try {
          jbInit();
        }
        catch(Exception e) {
          e.printStackTrace();
        }
      }
      //Component initialization
      private void jbInit() throws Exception  {
        contentPane = (JPanel) this.getContentPane();
        //contentPane.setLayout(xYLayout1);
        this.setSize(new Dimension(30, 100));
        this.setTitle("Frame Title");
        jList1.setVisibleRowCount(4);
        //contentPane.add(jList1,  new XYConstraints(72, 86, 213, 73));
        contentPane.add(listScrollPane);
        
      }
      //Overridden so we can exit when window is closed
      protected void processWindowEvent(WindowEvent e) {
        super.processWindowEvent(e);
        if (e.getID() == WindowEvent.WINDOW_CLOSING) {
          System.exit(0);
        }
      }
    }
    import javax.swing.UIManager;
    import java.awt.*;/**
     * @author qzw
     */public class Application1 {
      boolean packFrame = false;  //Construct the application
      public Application1() {
        Frame1 frame = new Frame1();
        //Validate frames that have preset sizes
        //Pack frames that have useful preferred size info, e.g. from their layout
        if (packFrame) {
          frame.pack();
        }
        else {
          frame.validate();
        }
        //Center the window
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        Dimension frameSize = frame.getSize();
        if (frameSize.height > screenSize.height) {
          frameSize.height = screenSize.height;
        }
        if (frameSize.width > screenSize.width) {
          frameSize.width = screenSize.width;
        }
        frame.setLocation((screenSize.width - frameSize.width) / 2, (screenSize.height - frameSize.height) / 2);
        frame.setVisible(true);
      }
      //Main method
      public static void main(String[] args) {
        try {
          UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        }
        catch(Exception e) {
          e.printStackTrace();
        }
        new Application1();
      }
    }