调用方法后如何调整弹出组件的大小show()
?这个例子是行不通的:
package test;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.*;
public class MyFrame extends JFrame {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new MyFrame().setVisible(true);
}
});
}
public MyFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
setSize(400, 300);
setLocation(400, 300);
addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
showPopup();
}
});
}
void showPopup() {
JComponent popup = new JPanel();
popup.setPreferredSize(new Dimension(100, 40));
popup.setBorder(BorderFactory.createLineBorder(Color.GREEN));
Popup p = PopupFactory.getSharedInstance().getPopup(this, popup, this.getLocationOnScreen().x, this.getLocationOnScreen().y);
p.show();
popup.setPreferredSize(new Dimension(200, 80));
popup.setBorder(BorderFactory.createLineBorder(Color.RED));
}
}
组件的大小popup
不会改变。
我找到了解决方案,您必须显式更改弹出组件窗口的大小。
SwingUtilities.getWindowAncestor(popup).setSize(200, 80);
但是此解决方案仅在弹出组件位于另一个窗口中的情况下才有效。这不是我需要的。