I’m adding a panel into an already shown JFrame on click of button. Now when user resizes the frame, the panel remain constant at it’s location. What I want is panel location should also adjust as frame resizes. Any way to do that?
Code to regenerate my problem:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class ProblemPanelLocation {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
final JFrame frame = new JFrame("ProblemPanelLocation");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(250, 250);
final JPanel panel = new JPanel();
panel.setSize(100, 100);
panel.setBorder(BorderFactory.createBevelBorder(1));
final JButton button = new JButton("Add panel");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
panel.setLocation(button.getX() - button.getWidth() - 10, button.getY());
frame.getLayeredPane().add(panel, JLayeredPane.MODAL_LAYER);
}
});
GroupLayout layout = new GroupLayout(frame.getContentPane());
frame.getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addGroup(GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(317, Short.MAX_VALUE)
.addComponent(button)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(button)
.addContainerGap(266, Short.MAX_VALUE))
);
frame.setVisible(true);
}
});
}
}
The scenario:
- At first you see a frame with a button in it.
- When you click on it a panel is added into frame, in frame’s layered pane.
- Panel’s location is calculated based on button location.
- Now when you resize frame, button also moves to be at the right side of the frame, but panel don’t.
I want to add panel in such a way that it acts like button for location. Is it possible? and if yes then how can I do it?
Use a ComponentListener:
Override the setBounds() method of the frame and update the location there. This is not recommended since this code will execute in the same EventDispatcher-Event as the actual resize but it may help to avoid the sluggish repaint when using a component listener.