开发者

How to Change JFrame Size dynamically

I have a simple drawing program, I set开发者_如何学JAVA my Jframe's size with the following code:

    frame.setSize(900, 700);

However, when user change the size of the window, white area to draw, still remain same size therefore, user is not able to draw eventhough he enlarge the window.

http://forum.codecall.net/java-tutorials/31180-java-mini-paint-program.html this is where I start from. I extended class "PadDraw" and wrote most of my code to there, in my other java file, I only create a frame, then I create "PadDraw" object, I crated a container and then added object to the frame's container: content.add(drawPad, BorderLayout.CENTER);

I changed my code:

public class PadDraw extends JComponent implements ActionListener, ItemListener, ComponentListener{
    public synchronized void addComponentListener(ComponentListener l) {};

. . . .

And I added unimplemented methods, and the "componentResized" is:

public void componentResized(ComponentEvent arg0) {
    System.out.println("Changed ????");

}

But when I changed the window's size, nothing happens.

One thougt: When I added componentlistener to my other file instead of drawPad, componentResized method flags, but because I have created drawPad object before this event occured, I can't change the size =/

Thanks


Hopefully you're not drawing directly on the JFrame but rather in a JPanel or JComponent that's been added to the JFrame's contentPane. If it has been added BorderLayout.CENTER, then it should expand and contract as the JFrame expands and contracts. Things get a little trickier if you're drawing on a BufferedImage as you'll have to use a ComponentListener to see when the component that holds the BufferedImage changes size, and when it does, change the size of the BufferedImage without losing the drawing that's already there.

If this answer is not helpful enough, consider giving us more specific information about your current problem and your current program.

In the program that you link to, you're drawing on an Image object whose size is set the first time paint is called. What you'll want to do is to add a ComponentListener to the PadDraw object in its own constructer, and in the ComponentListener's componentResized method, resize your image using the PadDraw's new height and width. I would only do this however if the new size is larger than the old size. You would also then want to redraw the old image on the new before setting the image variable = to the new image. Then call repaint.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜