我有一个带有多个Object(自定义类扩展Jpanel)对象的JPanel。 JPanel的网格布局有7行1列。我正在尝试将带有7个对象的JPanel添加到另一个JScrollPane中,这样我就可以滚动查看所有对象,但它做的很奇怪。无论JPanel中有多少个对象,滚动条都不会显示。有任何想法吗?提前谢谢。
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.ScrollPaneLayout;
public class Main {
@SuppressWarnings("deprecation")
public static void main(String[] args) {
JFrame frame = new JFrame("Test");
frame.setLayout(new BorderLayout());
JLabel title = new JLabel("Game", JLabel.CENTER);
title.setPreferredSize(new Dimension(60,60));
title.setBorder(BorderFactory.createLineBorder(Color.black,5));
frame.add(title,BorderLayout.NORTH);
frame.setSize(850,480);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Grid g = new Grid();
JPanel jp = new JPanel();
jp.setLayout(new GridLayout(1,3));
jp.add(g);
JPanel test = new JPanel();
test.setLayout(new GridLayout(7,1));
test.add(p1);
test.add(p2);
test.add(p3);
test.add(p4);
test.add(p5);
test.add(p6);
test.add(p7);
JScrollPane jsp = new JScrollPane(test);
jsp.setViewportView(test);
jsp.getVerticalScrollBar().setUnitIncrement(50);
jsp.setCorn
jsp.setVerticalScrollBarPolicy(22);
jp.add(jsp,BorderLayout.EAST);
frame.add(jp);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
答案 0 :(得分:2)
jp JPanel使用JPanel的默认FlowLayout,这可能会阻止您调整JScrollPane的大小并确保它实际上正常工作。为什么不将JScrollPane添加到JFrame的contentPane或者让jp使用BorderLayout?此外,您不需要设置JScrollPane的viewportView,因为您已经通过将“test”传递到其构造函数中来实现此目的。
答案 1 :(得分:1)
您的代码无法编译。请查看以下代码。它可以垂直和水平滚动。
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
class MyPanel extends JPanel {
MyPanel(Color c) {
setBackground(c);
}
}
public class Test {
public static void main(String[] args) {
JPanel panel = new JPanel();
// the size of this panel is larger than the frame
panel.setPreferredSize(new Dimension(500, 2000));
panel.setLayout(new GridLayout(7, 1));
// add 7 sub panels
panel.add(new MyPanel(Color.magenta));
panel.add(new MyPanel(Color.cyan));
panel.add(new MyPanel(Color.blue));
panel.add(new MyPanel(Color.green));
panel.add(new MyPanel(Color.yellow));
panel.add(new MyPanel(Color.orange));
panel.add(new MyPanel(Color.red));
JScrollPane scroll = new JScrollPane(panel);
scroll.setViewportView(panel);
scroll.getVerticalScrollBar().setUnitIncrement(50);
JFrame frame = new JFrame("Test");
frame.setSize(400, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(scroll);
frame.setVisible(true);
}
}