Make JScrollPane control multiple components

后端 未结 3 918
被撕碎了的回忆
被撕碎了的回忆 2020-11-30 16:05

For my application I am designing a script editor. At the moment I have a JPanel which contains another JPanel that holds the line number (position

3条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-30 16:42

    Create an Outer Panel which holds the Line Number panel and Text Area.

    Then put this new panel into the Scroll Pane so you end up with this arrangement:

    enter image description here

    Which in code is something like:

    private ScriptEditor() {
    
        setBackground(Color.WHITE);
    
        JPanel outerPanel = new JPanel();
    
        lineNumPanel = new LineNumberPanel();
    
        scriptArea = new JTextArea();
        scriptArea.setLineWrap(true);
        scriptArea.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 15));
        scriptArea.setMargin(new Insets(3, 10, 0, 10));
    
        outerPanel.add(lineNumPanel, BorderLayout.WEST)
        outerPanel.add(scriptArea, BorderLayout.CENTER)
    
        JScrollPane scrollPane = new JScrollPane(outerPanel);
        scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        scrollPane.setPreferredSize(new Dimension(width, height));
    
        scriptArea.addKeyListener(this);
    
        add(lineNumPanel);
        add(scrollPane);
    }
    

提交回复
热议问题