我有一个 JComboBox
包含了很长的 String
s,使得我的GUI占用了太多空间。我只需要在选择时看到完整的长度。所以,我希望 JComboBox
只在全尺寸时显示其完整长度,在其他情况下缩短。
以下代码似乎可行。但由于我是一个Java新手,我想知道是否有更好或更标准的方法来实现这个功能。
谢谢。
import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
public class DynamicJComboBox{
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new FlowLayout());
frame.setSize(250, 100);
JComboBox box = new JComboBox();
box.addItem("Really Long Line Number One");
box.addItem("Really Long Line Number Two");
box.addItem("Really Long Line Number Three");
box.addItem("Really Long Line Number Four");
box.setPreferredSize(new Dimension(100, 30));
box.addPopupMenuListener (new PopupMenuListener() {
@Override
public void popupMenuCanceled(PopupMenuEvent e) {}
@Override
public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
box.setSize(100,30);
}
@Override
public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
box.setSize(200,30);
}
});
frame.add(box);
frame.setVisible(true);
}
public static void main(String[] args) {
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
} catch (Exception exc) {}
SwingUtilities.invokeLater(() -> {
createAndShowGUI();
});
}
}
popupMenuWillBecomeVisible
会重新安排customizePopup
方法在Swing事件线程上运行?我本以为popupMenuWillBecomeVisible
已经在该线程上运行了。 - Greg Valvo