我制作了一个组合框,但某些元素比我的框的宽度更宽。所以我尝试添加一个水平滚动窗格,而我唯一能看到的是一个内部带有组合框的滚动窗格!
当然我做错了什么。这是我没有 jscrolpane 的代码。
issuerdocumentJComboBox=new JComboBox<>(issuermodel);//the compo box
issuerdocumentJComboBox.setBounds(430, 120, 100, 30);
searchDocumentesJPanel.add(issuerdocumentJComboBox);
如何向组合框添加水平滚动窗格?
谢谢你!
有可能的!!这是我编写的一个小程序来展示我的解决方案:
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;
}
}
}
该方法是创建一个在滚动窗格中显示 JTextField 编辑器的自定义 ComboBoxEditor(更容易扩展 BasicComboBoxEditor)。
这getEditorComponent()
然后重写函数以返回滚动窗格而不是文本字段。
当您调用时,这两个重写函数会在内部调用combobox.setEditor(new MyEditor())
因此,如果您看不到它正在使用,请不要担心。
Here's a screenshot of the program showing an element wider than combobox:
![screenshot](https://i.stack.imgur.com/7XwTV.png)
祝你好运!! :-)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)