2015-10-13 165 views
1

嗨我正在嘗試爲我的JFrame創建滾動條。我創建了JPanel對象並將組件設置到JPanel中。然後爲面板創建一個JScrollPane對象。然後將ScrollPane對象添加到JFrame。我沒有看到任何滾動條。另外我想知道在JPanel中是否有一個選項會根據JPanel的縮放級別自動調整Jpanel中的對象的大小。任何幫助將不勝感激。爲JFrame創建滾動條

公共類xmlottgui {

private JPanel Container; 

private JFrame frmCreateXml; 

private JTextField titlename; 
private JLabel lbltitlename; 

public static void main(String[] args) { 
    EventQueue.invokeLater(new Runnable() { 
     public void run() { 
      try { 
       xmlottgui window = new xmlottgui(); 
       window.frmCreateXml.setVisible(true); 

      } catch (Exception e) { 
       e.printStackTrace(); 
      } 
     } 
    }); 
} 

/** 
* Create the application. 
*/ 
public xmlottgui() { 
    initialize(); 
} 

/** 
* Initialize the contents of the frame. 
*/ 
private void initialize() { 

    Container = new JPanel(); 
    Container.setLayout(null); 

    //JScrollPane pane=new JScrollPane(Container,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); 



    frmCreateXml = new JFrame(); 
    frmCreateXml.setTitle("Create XML"); 
    frmCreateXml.setBounds(100, 100, 1000, 1200); 
    frmCreateXml.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    frmCreateXml.getContentPane().setLayout(null); 

    //Create MenuBar 
    JMenuBar menuBar = new JMenuBar(); 
    Container.add(menuBar); 

    JMenu mnFile = new JMenu("File"); 
    menuBar.add(mnFile); 

    JMenuItem mntmImportFromCsv = new JMenuItem("Import From Excel File"); 
    //Add menu item Exit 
    JMenuItem mntmexit = new JMenuItem("Exit"); 
    mntmexit.addActionListener(new ActionListener() { 
     public void actionPerformed(ActionEvent event) { 
      System.exit(0); 
     } 
    }); 
    mnFile.add(mntmexit); 

    showform(); 

    JScrollPane pane=new JScrollPane(Container,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); 
    pane.setLayout(null); 
    frmCreateXml.setContentPane(pane); 
    frmCreateXml.getContentPane().add(pane); 

} 

private void showform(){ 

    titlename = new JTextField(); 
    titlename.setBounds(164, 27, 749, 26); 
    Container.add(titlename); 
    titlename.setColumns(10); 

    lbltitlename = new JLabel("Title Name"); 
    lbltitlename.setBackground(Color.GRAY); 
    lbltitlename.setBounds(22, 1000, 90, 16); 
    Container.add(lbltitlename);   
} 

回答

4

此:

pane.setLayout(null); 

將完全禁用JScrollPane中,並防止它的工作,因爲它會阻止JScrollPane的從顯示並正確操縱視口。 JScrollPanes擁有自己非常特別的佈局管理器,除非你非常聰明,並且知道自己在做什麼,否則你從來不想使用它。作爲一般規則,您幾乎不應該使用空佈局。

而且這是不正確的:

frmCreateXml.setContentPane(pane); 
    frmCreateXml.getContentPane().add(pane); 

你讓窗格中的contentPane然後添加窗格本身。


,這是搞亂您:

frmCreateXml.getContentPane().setLayout(null); 

您想了解和使用佈局管理器,因爲它會讓你的生活變得更輕鬆。