我在点击按钮时将一个面板添加到已经显示的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);
}
});
}
}
情景:
我希望以这样的方式添加面板,使其像按钮一样用于定位。可能吗?如果是,那我该怎么办?
答案 0 :(得分:1)
使用ComponentListener:
frame.addComponentListener( new ComponentAdapter() {
@Override
public void componentResized( ComponentEvent e ) {
panel.setLocation(button.getX() - button.getWidth() - 10, button.getY());
}
} );
覆盖框架的setBounds()方法并更新其中的位置。建议不要这样做,因为此代码将在与实际调整大小相同的EventDispatcher-Event中执行,但在使用组件侦听器时可能有助于避免缓慢重绘。