How to display graphics larger than canvas size?
How do I display graphics larger than canvas size in Java AWT?
I tried setting the canvas size() to a value larger than my monitor size, and then adding scroll bars to the canvas, but the scroll bars and the canvas won't go beyond the monitor size in pixels, which is only 800, so the large graphic I try to display gets cut off at the bottom.
How can I overcome this problem? Has anybody encounter a similar dilemma before?
[444 byte] By [
cabrera148] at [2007-9-30 17:57:08]

import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
public class AWTSizing
{
public static void main(String[] args)
{
LargeCanvas canvas = new LargeCanvas();
ScrollPane scrollPane = new ScrollPane();
scrollPane.add(canvas);
Frame f = new Frame();
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
f.add(scrollPane);
f.setSize(400,400);
f.setLocation(200,200);
f.setVisible(true);
}
}
class LargeCanvas extends Canvas
{
int w, h;
final int PAD = 10;
Rectangle r1, r2, r3;
Rectangle[] rects;
boolean firstTime;
public LargeCanvas()
{
w = 360;
h = 360;
firstTime = true;
}
public void paint(Graphics g)
{
super.paint(g);
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
if(firstTime)
initShapes();
g2.setPaint(Color.red);
g2.draw(r1);
g2.draw(r2);
g2.draw(r3);
}
private void initShapes()
{
r1 = new Rectangle(w/4, h/4, w/2, h*3/4);
r2 = new Rectangle(w/2, h/2, w/2, h/2);
r3 = new Rectangle(w*5/8, h/6, w*3/5, h*2/3);
rects = new Rectangle[] { r1, r2, r3 };
firstTime = false;
invalidate();
getScrollPane().validate();
}
private ScrollPane getScrollPane()
{
ScrollPane scrollPane = null;
Component c = this;
while((c = c.getParent()) != null)
if(c instanceof ScrollPane)
{
scrollPane = (ScrollPane)c;
break;
}
return scrollPane;
}
public Dimension getPreferredSize()
{
Dimension d = new Dimension(w, h);
if(rects == null)// before calling initShapes
return d;
Rectangle r;
for(int j = 0; j < rects.length; j++)
{
r = rects[j];
if(r.x + r.width + PAD > w)
d.width += r.x + r.width + PAD - w;
if(r.y + r.height + PAD > h)
d.height += r.y + r.height + PAD - h;
}
return d;
}
}