滚动JPanel [英] Scrolling a JPanel

查看:109
本文介绍了滚动JPanel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个具有大小和定义位置的JPanel。在JPanel内部,我有一定数量的元素(按钮)水平插入。因为我的JPanel有一个已定义的宽度,如果我添加了很多按钮,我就看不到了。在这种情况下,我需要一个这个JPanel的滚动条。但是这个JPanel必须是JFrame中某个位置的特定尺寸。 JPanel的滚动条水平放置在它下面。有人可以帮帮我吗?我尝试过没有成功!

I want a JPanel with a size and defined position. Inside the JPanel, I've certain number of elements (buttons) inserted horizontally. Because my JPanel has a defined width, if I add much buttons, I couldn't see that. In this case, I need a scrollbar for this JPanel. But this JPanel must be a CERTAIN SIZE IN A CERTAIN POSITION inside a JFrame. The scrollbar of the JPanel has positioned under it horizontally. Someone can help me? I've tried it without success!

推荐答案

使用JScrollPane并将其preferredSize强制为给定大小(或将scrollPane容器LayoutManager设置为null并调用setBounds()在滚动窗格上)。还要设置滚动条策略。以下是一个小样本:

Use a JScrollPane and force its preferredSize to your given size (or set the scrollPane container LayoutManager to null and call setBounds() on the scrollpane). Also set the scrollbar policies. Here is a small sample of that:

import java.awt.Dimension;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;

public class Test {

    public static void main(String... args) {
        JFrame frame = new JFrame();
        JPanel panel = new JPanel();
        for (int i = 0; i < 10; i++) {
            panel.add(new JButton("Hello-" + i));
        }
        JScrollPane scrollPane = new JScrollPane(panel);
        scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);
        scrollPane.setBounds(50, 30, 300, 50);
        JPanel contentPane = new JPanel(null);
        contentPane.setPreferredSize(new Dimension(500, 400));
        contentPane.add(scrollPane);
        frame.setContentPane(contentPane);
        frame.pack();
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.setVisible(true);
    }
}

这篇关于滚动JPanel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆