我创建了两个面板和一个主面板。每个面板都包含一个非常大的图像,我希望它们都可以滚动以查看图像的其余部分。但是当我在主面板中添加两个面板并运行它时,第一个面板太大了,它覆盖了第二个面板。我如何为两个面板实现ScrollPane?
import java.awt.BorderLayout;
import javax.swing.*;
public class BoardFrame extends JFrame {
JPanel mainPanel = new JPanel(new BorderLayout());
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);
mainPanel.add(jPanelNorth, BorderLayout.NORTH);
mainPanel.add(jPanelSouth, BorderLayout.SOUTH);
add(mainPanel);
//where would I use this?
//scrollPane.setViewportView();
}
}
答案 0 :(得分:2)
每个面板包含非常大的图像>
//JPanel mainPanel = new JPanel(new BorderLayout());
JPanel mainPanel = new JPanel(new GridLayout(0, 1));
您可能希望使用GridLayout,以便每个滚动窗格占据一半帧,以便显示尽可能多的每个图像。
//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.
然后将scrollPane添加到主面板,因为滚动窗格包含带有图像的面板。
答案 1 :(得分:0)
似乎使用网格布局比使用边框布局要好得多,在这种情况下:
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);
}
}