1

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);

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());

Add the button to my scrollerPane:

scroller.add(jButton1);

And finally adds my scrollpane to my container:

scrollerContainer.add(scroller);

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 :)

Howard
  • 38,639
  • 9
  • 64
  • 83
Rasmus
  • 47
  • 1
  • 6

1 Answers1

2

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.

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

camickr
  • 321,443
  • 19
  • 166
  • 288
  • 1
    Thanks a lot for the quick answer - In the future I will make sure to post a shorter, better question (thanks for the link mre!) – Rasmus Aug 09 '11 at 20:50