向JScrollpane添加按钮 [英] Adding buttons to JScrollpane

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

问题描述

我正在使用Java和SWING,并且有一个添加了相当大图像的滚动窗格,它现在可以正常工作,这意味着滚动功能正在按预期工作.但是,在此图像上的不同位置,我需要添加jButton并能够对这些按钮进行鼠标单击

I am using Java and SWING, and I have a scrollpane with a rather large image added to it which works just fine right now, which means the scrolling functionality is working as intended. However in different locations on this image I need to add jButtons and be able to act on mouseclicks on these

此刻,我得到了以下代码:(摘要,如果您需要其他内容,请告诉我)

At the moment I got the following bit of code: (snippets, let me know if you require anything else)

jButton1 = new JButton("CLICK");
jButton1.setBounds(0, 0, 100, 100);

此后,我添加了动作监听器,效果很好,然后使用img创建了滚动窗格:

After that I add my actionlistener, which works fine, I then create my scrollpane with the img:

BufferedImage wp = ImageIO.read(new File("Main_background.jpg"));

JLabel image = new JLabel(new ImageIcon(wp));

scrollerContainer.setSize(screen_width-50,screen_height-50);
scrollerContainer.setLayout(new BorderLayout());

将按钮添加到我的scrollerPane中:

Add the button to my scrollerPane:

scroller.add(jButton1);

最后将我的滚动窗格添加到我的容器中:

And finally adds my scrollpane to my container:

scrollerContainer.add(scroller);

发生的事情是该按钮出现在非常意外的时间和地点.首先,它不会一直显示,它似乎是在Java调用重绘/绘画时发生的,其次是按钮与我的滚动窗格滚动",这意味着如果我应该将图像移到最右边,则该按钮仍会出现,即使它只出现在0,0处也是如此.我在想我不应该将jButton添加到滚动对象,而是添加到其他对象?但是我不知道是什么.

What happens is that the button shows up at pretty unexpected times and places. First up it doesnt show all the time, it seems to happen when a redraw/paint is called by java, and secondly the button "scrolls" with my scrollpane, meaning that if I should the image to the far right, the button will still show up, even if it should only show up at 0,0. I am thinking I am not supposed to add the jButton to my scroller object, but to something else? But I can't figure out what.

希望这个问题很有意义,有人可以帮助我:)

Hope the problem makes sense and someone can help me out :)

推荐答案

永远不要将组件直接添加到滚动窗格中.

You should never add a component directly to the scroll pane.

该按钮需要添加到您在滚动窗格的视口中显示的标签中.

The button needs to be added to the label which you display in the viewport of the scroll pane.

以后,请在您的SSCCE上发布问题,以便我们无需猜测.

In the future post your SSCCE with the question so we don't need to guess.

这篇关于向JScrollpane添加按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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