ADS

Create Relatively Moving Jframes In Swing

Let us create jframes that moves relatively. That is of one frame moves, the other frame's position does not change. This is seen in ImgBurn, the log window and the main window moves relatively. This is a simple Swing hack. Here we go.




 import javax.swing.*;
import java.awt.event.*;
class StickedFrames
{
public static void main(String args[])
{
final JFrame f=new JFrame("Frame 1");
f.setVisible(true);
f.setSize(400,400);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

final JFrame f1=new JFrame("Frame 2");
f1.setVisible(true);
f1.setSize(400,150);
f1.setLocation(f.getX()+f.getHeight(),f.getY()+f.getWidth());
f1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

f.addComponentListener(new ComponentAdapter()
{
public void componentMoved(ComponentEvent ce)
{
//f1.setLocation(f.getX()+f.getWidth(),f.getY());
f1.setLocation(f.getX(),f.getY()+f.getWidth());
}
});


}
}

Output

 Let us create jframes that moves relatively Create Relatively moving JFrames in Swing
Sticked JFrames

For this, i am adding a ComponentListener to the JFrame. Here if f moves then f1 moves but vice versa simultaneously is not possible. I've tried repeating the same code for moving jframes relatively and some more different code must be written. Let me explain the first commented lines.

f1.setLocation(f.getX()+f.getWidth(),f.getY()): The location of the down frame. Here the frame appears side by side. Here the top-left corner of the down frame (in the image) is set side of the top-right corner of the first frame. And y-axis of both the frames are same.

f1.setLocation(f.getX(),f.getY()+f.getHeight()): The location of the down frame. For the second frame to locate down, this statement is used. Here, the x-axis of both the frames are same, the y-axis is what that differs. The top-left corner of the second frame is set along the y-axis of the first frame, but down to the first frame. So for this, the getHeight() method in the first frame is called which gets height of the first frame.

In this way, you can relatively move JFrames in swing. Drop a comment.

Subscribe to receive free email updates:

ADS