为 JFrame 创建滚动条

Create Scroll Bar for JFrame

您好,我正在尝试为我的 JFrame 创建滚动条。我创建了 JPanel 对象并将组件设置到 JPanel 中。然后为面板创建一个 JScrollPane 对象。然后将 ScrollPane 对象添加到 JFrame。我没有看到任何滚动条。另外我想知道 JPanel 中是否有一个选项可以根据 JPanel 的缩放级别自动调整 Jpanel 中对象的大小。任何帮助将不胜感激。

public class 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);        
}

这个:

pane.setLayout(null);

将完全禁用您的 JScrollPane 并阻止其工作,因为它将阻止 JScrollPane 正确显示和操作其视口。 JScrollPanes 有自己非常特殊的布局管理器,除非您非常聪明并且知道自己在做什么,否则您永远不想弄乱它。作为一般规则,您几乎不应该使用空布局。

这也是不正确的:

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

您将窗格设为 contentPane,然后 add 窗格本身。


这让你很困惑:

frmCreateXml.getContentPane().setLayout(null);

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