java拖动jpanel,JScrollPane中的Java JPanel?

I have a JFrame, in this JFrame I have a JPanel that I draw on, this Panel can be any size and so I placed it into a JScrollpane to let me scroll when the panel is larger than the window screen size.

Unfortunately does not work as I expected:

Making the JFrame window smaller than the JPanel size does not show scroll bars

The JScrollPane size now seems locked to the size of the JPanel I have added to it, where as before it resized to the bounds of it's JFrame window (it still kinda does this but only vertically now?!)

The JPanel seems to assume the size of the JScrollpane regardless of what I set for preferred size

I am sure I'm doing something stupid, if someone could point out what I would be most grateful!

JPanel _ImageCanvas = new JPanel(); // 'Canvas' to draw on

JScrollPane _ScrollPane = new JScrollPane();

// set size of 'canvas'

_ImageCanvas.setMinimumSize(new Dimension(100,100));

// Scroll pane smaller then the size of the canvas so we should get scroll bars right?

_ScrollPane.setMinimumSize(new Dimension(50,50));

// Add a border to 'canvas'

_ImageCanvas.setBorder(BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));

_ScrollPane.setViewportView(JPanel);

Many thanks

David

解决方案

setPreferredSize() is the trick, setMinimumSize() and even setSize() on the component will be ignored by JScrollPane. Here's a working example using a red border.

import java.awt.*;

import javax.swing.*;

public class Scroller extends JFrame {

public Scroller() throws HeadlessException {

final JPanel panel = new JPanel();

panel.setBorder(BorderFactory.createLineBorder(Color.red));

panel.setPreferredSize(new Dimension(800, 600));

final JScrollPane scroll = new JScrollPane(panel);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setLayout(new BorderLayout());

add(scroll, BorderLayout.CENTER);

setSize(300, 300);

setVisible(true);

}

public static void main(final String[] args) throws Exception {

SwingUtilities.invokeLater(new Runnable() {

@Override

public void run() {

new Scroller().setVisible(true);

}

});

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值