Вложенный BoxLayout не работает?

Я создал два класса Java, один из которых является моим основным классом main.java, а другой — вспомогательным классом, который создает панель с некоторыми добавленными компонентами CPanel.java. Макет моего приложения выглядит следующим образом:
Основной класс создает главную панель с помощью BoxLayout и добавляет панель инструментов вверху, а затем создает объект CPanel (панель с добавленными компонентами) и добавляет его на главную панель. Объект CPanel также имеет BoxLayout для своих компонентов. Проблема в том, что панель CPanel не включает BoxLayout, а просто придерживается макета потока. Вот код моих классов..

public class MainFile extends JFrame {
        private JToolBar navbar ;
        private JButton backBtn, forwardBtn, homeBtn ;
        private CPanel content ;
        private static JPanel app = new JPanel() ;
        public MainFile(){
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        navbar = new JToolBar() ;
        navbar.setMaximumSize(new Dimension(1000, 50));
        setSize(500, 800) ;
        app.setLayout(new BoxLayout(app, BoxLayout.PAGE_AXIS));
        app.add(navbar , BorderLayout.NORTH ) ;

        ImageIcon leftButtonIcon = createImageIcon("images/right.gif");
        ImageIcon middleButtonIcon = createImageIcon("images/middle.gif");
        ImageIcon rightButtonIcon = createImageIcon("images/left.gif");

        backBtn = new JButton(leftButtonIcon) ;
        forwardBtn = new JButton(rightButtonIcon) ;
        homeBtn = new JButton(middleButtonIcon) ;
        navbar.add(forwardBtn) ;
        navbar.add(Box.createGlue());
        navbar.add(homeBtn) ;
        navbar.add(Box.createGlue());
        navbar.add(backBtn) ;

        content = new CPanel() ;
        app.add(content) ;
        setContentPane(app) ;

    }
    protected static ImageIcon createImageIcon(String path) {
        java.net.URL imgURL = MFrame.class.getResource(path);
        if (imgURL != null) {
            return new ImageIcon(imgURL);
        } else {
            System.err.println("Couldn't find file: " + path);
            return null;
        }
    }
    public static void showGUI(){
        MFrame Reader = new MFrame() ;
        //Reader.pack();
        //Reader.setContentPane(app);
        Reader.setVisible(true) ;
    }
    public static void main(String args[]){
        SwingUtilities.invokeLater(new Runnable(){
            @Override
            public void run(){
                showGUI() ;
            }
        });
    }
}



Вот мой класс CPanel

public class CPanel extends JPanel {
    private JScrollPane scrollPane ;
    private JPanel content ;
    private JEditorPane demo ;
    public CPanel(){
        scrollPane = new JScrollPane() ;
        content = new JPanel() ;
        scrollPane.setViewportView(content);
        content.setLayout(new BoxLayout(content, BoxLayout.Y_AXIS));
        try{
         java.net.URL text = CPanel.class.getResource("demo.txt") ;
        demo = new JEditorPane(text) ;
        }catch(Exception e){
            System.out.println("Something bad happened with the file") ;
        }
        add(demo) ;
        JButton demob = new JButton("Button 1") ;
        JButton demob2 = new JButton("Button 2") ;
        add(demob) ;
        add(demob2) ;
    }
}

person Kapil Garg    schedule 20.07.2015    source источник
comment
Макет CPanel отличается от BoxLayout. Это макет поля с именем content, которое находится внутри области прокрутки, но эта область прокрутки никуда не добавляется. Остальные компоненты добавляются непосредственно в CPanel, который по-прежнему использует FlowLayout по умолчанию.   -  person kiheru    schedule 20.07.2015
comment
Вы правы .. Спасибо за предложение   -  person Kapil Garg    schedule 21.07.2015


Ответы (1)


Кажется, вы хотите, чтобы CPanel имел JScrollPane, который отображается как компонент с BoxLayout. Вы были правы, создав JPanel, настроив его макет и добавив его к JScrollPane, но вам все равно нужно добавить JScrollPane к вашему CPanel и кнопкам и demo к content

public class CPanel extends JPanel {
    private JScrollPane scrollPane ;
    private JPanel content ;
    private JEditorPane demo ;

    public CPanel(){

        scrollPane = new JScrollPane() ;
        content = new JPanel() ;
        scrollPane.setViewportView(content); 
        content.setLayout(new BoxLayout(content, BoxLayout.Y_AXIS));

        try{
         java.net.URL text = CPanel.class.getResource("demo.txt") ;
        demo = new JEditorPane(text) ;
        }catch(Exception e){
            System.out.println("Something bad happened with the file") ;
        }

        //These need to be added to the contentpanel
        content.add(demo) ;
        JButton demob = new JButton("Button 1") ;
        JButton demob2 = new JButton("Button 2") ;
        content.add(demob) ;
        content.add(demob2) ;

        //Here we need to add the scrollPane, to which the JPanel 
        //with BoxLayout has been added
        this.setLayout(new BorderLayout());
        this.add(scrollPane, BorderLayout.CENTER);
    }
}
person milez    schedule 21.07.2015
comment
Приятно слышать, удачного кодирования! - person milez; 21.07.2015