我制作了一个组合框,但有些元素比我的框宽。所以我尝试添加一个水平滚动 Pane ,但我唯一能看到的是一个带有组合框的滚动 Pane ! 当然是我做错了什么。所以这是我没有 jscrolpane 的代码。
issuerdocumentJComboBox=new JComboBox<>(issuermodel);//the compo box
issuerdocumentJComboBox.setBounds(430, 120, 100, 30);
searchDocumentesJPanel.add(issuerdocumentJComboBox);
如何向组合框添加水平滚动 Pane ? 谢谢!
最佳答案
有可能!!这是我写的一个小程序来展示我的解决方案:
import java.awt.Component;
import java.awt.Dimension;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.ScrollPaneConstants;
import javax.swing.plaf.basic.BasicComboBoxEditor;
public class TestComboScroll {
public static void main(String[] args) {
JFrame frame = new JFrame("Scroll inside Combo");
JComboBox combobox = new JComboBox();
combobox.addItem("");
combobox.addItem("Item1");
combobox.addItem("Item2 Item2 Item2 Item2 Item2 Item2 Item2 Item2 Item2 Item2 Item2 Item2 Item2 Item2");
combobox.addItem("Item3");
combobox.setEditor(new MyEditor());
combobox.setEditable(true);
combobox.setPreferredSize(new Dimension(200, 50));
frame.add(combobox);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
static class MyEditor extends BasicComboBoxEditor{
JScrollPane scroller = new JScrollPane();
//NOTE: editor is a JTextField defined in BasicComboBoxEditor
public MyEditor(){
super();
scroller.setViewportView(editor);
scroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
}
/** Return a JScrollPane containing the JTextField instead of the JTextField **/
@Override
public Component getEditorComponent() {
return scroller;
}
/** Override to create your own JTextField. **/
@Override
protected JTextField createEditorComponent() {
JTextField editor = new JTextField();
editor.setBorder(null);
/*editor.setEditable(false); //If you want it not to be editable */
return editor;
}
}
}
方法是创建一个在滚动 Pane 中显示 JTextField 编辑器的自定义 ComboBoxEditor(仅扩展 BasicComboBoxEditor 更容易)。
然后覆盖 getEditorComponent()
函数以返回滚动 Pane 而不是文本字段。
当您调用 combobox.setEditor(new MyEditor())
时,会在内部调用这两个重写函数,所以如果您看不到它正在使用,请不要担心。
这是程序的屏幕截图,显示了一个比组合框宽的元素:
祝你好运!! :-)
关于java - JComboBox 上的 JScrollPane,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10267032/