Java 具有多个带有滚动窗格的面板
我创建了两个面板和一个主面板。每个面板都包含一个非常大的图像,我希望它们都能够滚动查看图像的其余部分。但是当我在主面板中添加两个面板并运行它时,第一个面板非常大,它覆盖了第二个面板。如何为这两个面板实现ScrollPane 每个面板包含一个非常大的图像> 您可能希望使用GridLayout,以便每个滚动窗格占据一半的框架,以便尽可能多地显示每个图像Java 具有多个带有滚动窗格的面板,java,user-interface,jpanel,jscrollpane,Java,User Interface,Jpanel,Jscrollpane,我创建了两个面板和一个主面板。每个面板都包含一个非常大的图像,我希望它们都能够滚动查看图像的其余部分。但是当我在主面板中添加两个面板并运行它时,第一个面板非常大,它覆盖了第二个面板。如何为这两个面板实现ScrollPane 每个面板包含一个非常大的图像> 您可能希望使用GridLayout,以便每个滚动窗格占据一半的框架,以便尽可能多地显示每个图像 //JScrollPane scrollPane = new JScrollPane(); JScrollPane scrollPane2 = n
//JScrollPane scrollPane = new JScrollPane();
JScrollPane scrollPane2 = new JScrollPane(jPanelNorth);
使用滚动窗格最简单的方法是创建一个滚动窗格,其中显示您想要显示的组件,滚动窗格将为您将组件添加到视口中
//mainPanel.add(jPanelNorth, BorderLayout.NORTH);
mainPanel.add(scrollPane); // don't need the constraint when using GridLayout.
然后将滚动窗格添加到主面板,因为滚动窗格包含带有图像的面板。在这种情况下,使用网格布局似乎比使用边框布局要好得多:
import java.awt.BorderLayout;
import javax.swing.*;
public class BoardFrame extends JFrame {
//1. use GridLayout with 2 rows and 1 column .
JPanel mainPanel = new JPanel(new GridLayout(2,1));
JLabel jLabel = new JLabel();
JPanel jPanelNorth = new JPanel();
JScrollPane scrollPane = new JScrollPane();
JLabel jLabel2 = new JLabel();
JPanel jPanelSouth = new JPanel();
JScrollPane scrollPane2 = new JScrollPane();
public BoardFrame() {
jLabel.setIcon(new ImageIcon("an image here"));
jPanelNorth.add(jLabel);
jLabel2.setIcon(new ImageIcon("an image here"));
jPanelSouth.add(jLabel2);
//2.you should place .setViewportView() here :
scrollPane.setViewportView(jPanelNorth);
scrollPane2.setViewportView(jPanelSouth);
mainPanel.add(scrollPane);//is in the top ("North")
mainPanel.add(scrollPane2);//next ("South")
//3.use setContentPane instead of add()
setContentPane(mainPanel);
}
}
非常感谢你。这正是我想做的!理解和正确的观点!再次感谢:)!!
//mainPanel.add(jPanelNorth, BorderLayout.NORTH);
mainPanel.add(scrollPane); // don't need the constraint when using GridLayout.
import java.awt.BorderLayout;
import javax.swing.*;
public class BoardFrame extends JFrame {
//1. use GridLayout with 2 rows and 1 column .
JPanel mainPanel = new JPanel(new GridLayout(2,1));
JLabel jLabel = new JLabel();
JPanel jPanelNorth = new JPanel();
JScrollPane scrollPane = new JScrollPane();
JLabel jLabel2 = new JLabel();
JPanel jPanelSouth = new JPanel();
JScrollPane scrollPane2 = new JScrollPane();
public BoardFrame() {
jLabel.setIcon(new ImageIcon("an image here"));
jPanelNorth.add(jLabel);
jLabel2.setIcon(new ImageIcon("an image here"));
jPanelSouth.add(jLabel2);
//2.you should place .setViewportView() here :
scrollPane.setViewportView(jPanelNorth);
scrollPane2.setViewportView(jPanelSouth);
mainPanel.add(scrollPane);//is in the top ("North")
mainPanel.add(scrollPane2);//next ("South")
//3.use setContentPane instead of add()
setContentPane(mainPanel);
}
}