2015-10-13 163 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); 

您想了解和使用布局管理器,因为它会让你的生活变得更轻松。