我通过单击按钮将面板添加到已显示的 JFrame 中。现在,当用户调整框架大小时,面板保持在其位置不变。我想要的是面板位置也应该随着框架大小的调整而调整。有办法做到吗?
重新生成我的问题的代码:
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);
}
});
}
}
场景:
- 首先您会看到一个框架,其中有一个按钮。
- 当您单击它时,一个面板会添加到框架中,位于框架的分层 Pane 中。
- 面板的位置是根据按钮位置计算的。
- 现在,当您调整框架大小时,按钮也会移动到框架的右侧,但面板不会。
我想添加面板,使其充当位置按钮。是否可以?如果是的话我该怎么做?
最佳答案
使用组件监听器:
frame.addComponentListener( new ComponentAdapter() { @Override public void componentResized( ComponentEvent e ) { panel.setLocation(button.getX() - button.getWidth() - 10, button.getY()); } } );
重写框架的 setBounds() 方法并更新那里的位置。不建议这样做,因为此代码将在与实际调整大小相同的 EventDispatcher-Event 中执行,但它可能有助于避免使用组件监听器时缓慢的重绘。
关于java - 调整 jpanel 在 jframe resize 上的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11578427/