java - JViewport is not positioning its view? -


i'm using java swing application, , want make use of jviewport show fragment of canvas-like panel 'behind' port. somehow viewport never positions view, there must i'm doing. doing wrong, why code not working?

the following example of i'm doing on bigger , more complex scale.

public class myapp {   // temporary test viewport working   public static void main(string[] args)   {     jframe frame = new jframe();     jviewport viewport = new jviewport();     viewport.setopaque(true);     viewport.setbackground(color.gray);     frame.add(viewport, borderlayout.center);     jpanel canvas = new jpanel(null);     canvas.setbackground(color.cyan);     viewport.setview(canvas);     viewport.setviewsize(new dimension(500, 500));     viewport.setextentsize(new dimension(300, 300));     viewport.setpreferredsize(new dimension(300, 300));      // item 1     jlabel label = new jlabel("this 32x32 box");     label.setopaque(true);     label.setbackground(color.green);     label.seticon(sprites.box2.getsprite());     label.setbounds(0, 0, 200, 32); // position upper left, 200 wide     label.sethorizontalalignment(swingconstants.left);     canvas.add(label);      // item 2     jlabel label2 = new jlabel("this 32x32 wall");     label2.setopaque(true);     label2.setbackground(color.orange);     label2.seticon(sprites.wall1.getsprite());     label2.setbounds(300, 468, 200, 32); // position lower right, 200 wide     label2.sethorizontalalignment(swingconstants.right);     label2.sethorizontaltextposition(swingconstants.left);     canvas.add(label2);      // should scroll canvas left , up, box becomes invisible , wall visible     viewport.setviewposition(new point(200, 200));        frame.pack();     frame.setlocationrelativeto(null);     frame.setdefaultcloseoperation(jframe.exit_on_close);     frame.setvisible(true);   } } 

the result 'canvas' sticking @ 0,0, never moves 200,200 setviewpostition(). it's contents positioned well, regardless of null layout manager. wrote canvas jpanel simplicity, it's complex jlayeredpane.

there several problems in case:

  • you use null-layout/absolute positionning: stop doing that... forever. it's bad practice, bad , nasty habit leads same point: tons of problems.
  • don't call setpreferredsize(): either use appropriate layoutmanager or override getpreferredsize()
  • consider implementing scrollable canvas , getpreferredscrollableviewportsize() return new dimension(300, 300) (the targetted viewport extent size)
  • calling setsize()/setextentsize() pretty useless because overriden layoutmanager.

Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -