有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在没有CardLayout的JFrame中切换JPanel

如何在框架中切换带有滚动窗格的面板?我已经尝试了很多可能的方法,但没有找到解决问题的办法

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

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) 个答案

  1. # 1 楼答案

    How can I switch Panels with ScrollPanes in a Frame?

    scrollPane.setViewportView( anotherPanel );