我在互联网上发现了一些例子,涉及获取图像或文本框来显示滚动条,但它们都涉及一个基本上在滚动窗格中显示其全部内容的程序。我需要让它做的就是在某处粘贴一个 JPanel,在该面板中堆放一堆文本、图标等,直到它对于我所拥有的空间来说太大,然后滚动它。
我可能也需要能够对该面板进行空布局,因为我可能迟早必须手动在其中放置内容。
因此,我尝试制作一个非常简单的程序,将三个彩色块放入一个足够容纳两个块的空间中,并显示一个滚动条,让您向下滚动以查看第三个块。它不添加滚动条。
导入有点混乱和多余,因为这是由几个不同的文件拼凑而成的,但它们不会产生任何错误。
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
public class ScrollDemo extends JFrame {
JScrollPane scrollpane;
public ScrollDemo() {
super("JScrollPane Demonstration");
setSize(800, 600);
setDefaultCloseOperation(EXIT_ON_CLOSE);
init();
setVisible(true);
}
public void init() {
setLayout(null);
JPanel innerPanel = new JPanel();
JPanel outerPanel = new JPanel();
getContentPane().setBounds(0,0,800,600);
outerPanel.setBounds(400,0,400,400);
innerPanel.setBounds(0,0,600,600);
innerPanel.setLayout(null);
JPanel greenPanel = new JPanel();
JPanel yellowPanel = new JPanel();
JPanel bluePanel = new JPanel();
greenPanel.setBounds(0,0,200,200);
yellowPanel.setBounds(0,200,200,200);
bluePanel.setBounds(0,400,200,200);
greenPanel.setBackground(Color.GREEN);
yellowPanel.setBackground(Color.YELLOW);
bluePanel.setBackground(Color.BLUE);
innerPanel.add(greenPanel);
innerPanel.add(yellowPanel);
innerPanel.add(bluePanel);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setViewportView(innerPanel);
scrollPane.setBounds(200,0,200,400);
add(scrollPane);
}
public static void main(String args[]) {
new ScrollDemo();
}
}