在没有CardLayout的JFrame中切换JPanel

时间:2014-04-03 18:03:35

标签: java swing jframe jpanel jscrollpane

如何在框架中使用ScrollPanes切换面板?我已经尝试了很多可能的方法,但无法提出解决方案。

实际上这是我教授给我的Java问题之一,我需要通过不使用其他布局(例如CardLayout)来实现这一点,我应该只使用null布局。只要我维护这三个类和滚动窗格,就允许其他类。

public class MainDriver {

public static void main(String[] args) {

    JFrame frame = new JFrame("Frame");
    panel1 p1 = new panel1();
    panel2 p2 = new panel2();

    JScrollPane jsp = new JScrollPane(panel1.panel);
    Container c = frame.getContentPane();
    jsp.getVerticalScrollBar().setUnitIncrement(10);
    c.add(jsp);

    //codes for panel switching from panel1 to panel2 vice versa


    frame.setDefaultCloseOperation(JFrame.exit_ON_CLOSE);
    frame.setSize(1058, 600);
    frame.setLocation(100, 50);
    frame.setVisible(true);

}
}

---------------------------------------------

public class panel1{
    public JPanel panel(){
         JPanel fore = new JPanel();
         fore.setLayout(null);
         fore.setPreferredSize(new Dimension (1024, 600));
         fore.setBackground(Color.decode("#004050"));
         fore.setVisible(true);

         JButton but = new JButton();
         but.setLocation(425, 300);
         but.setSize(100, 35);
         //button action/mouse listener
         fore.add(but);

         return fore;
    }
}

---------------------------------------------

public class panel2{
    public JPanel panel(){
         JPanel fore = new JPanel();
         fore.setLayout(null);
         fore.setPreferredSize(new Dimension (1024, 600));
         fore.setBackground(Color.decode("#004050"));
         fore.setVisible(true);

         JButton but = new JButton();
         but.setLocation(425, 300);
         but.setSize(100, 35);
         //button action/mouse listener
         fore.add(but);

         return fore;
    }
}

1 个答案:

答案 0 :(得分:2)

  

如何在框架中使用ScrollPanes切换面板?

scrollPane.setViewportView( anotherPanel );