java 从自定义渲染设置可编辑 JComboBox 中的文本字段
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10776416/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Setting the text field in editable JComboBox from custom render
提问by marcb
Both comboBox use the same code, the only exeption is that "combo 1" is set as editable and "Combo 2" is not. Both have "item 1" selected. As you can see, "Combo 1" is printing "[Ljava.lang.Object;@77905258" in the combo text feild and "Combo 2" print the selected name.
两个组合框使用相同的代码,唯一的例外是“组合 1”被设置为可编辑而“组合 2”不是。两者都选择了“项目 1”。如您所见,“Combo 1”在组合文本字段中打印“[Ljava.lang.Object;@77905258”,“Combo 2”打印所选名称。
How can "Combo 1" print the same text in the combo box text feild as "Combo 2"?
“Combo 1”如何在组合框文本字段中打印与“Combo 2”相同的文本?
To comply with E:(refer to attached image) If you click on "Combo 1" you will see the list of item 1, item 2... But the Text feild will show "[Ljava.lang.Object;@77905258" when item is selected (here it is item 1 that is selected).
遵守E:(请参阅附图)如果您单击“组合1”,您将看到项目1,项目2的列表......但文本字段将显示“[Ljava.lang.Object;@77905258”当项目被选中时(这里是项目 1 被选中)。
If you click on "Combo 2" you will see the list of item 1, item 2... And the non-editable Text feild will show "item 1" when "item 1" is selected.
如果单击“组合2”,则会看到第1项列表,第2项......和非可编辑文本,在选择“项目1”时将显示“项目1”。
Here is the code:
这是代码:
I'm using a custom renderer:
我正在使用自定义渲染器:
public class MyListRenderer extends JLabel
implements ListCellRenderer{
@Override
public Component getListCellRendererComponent(
JList list, Object value,
int index, boolean isSelected,
boolean cellHasFocus) {
Object[] itemData =(Object[])value;
setText((String)itemData[1]);
return this;
}
}
Here is the code to set the 2 combo boxes list:
这是设置 2 个组合框列表的代码:
private void iniCombobox() {
cmbMyCombo.addItem(new Object[] {"1", "Item 1"});
cmbMyCombo.addItem(new Object[] {"2", "Item 2"});
cmbMyCombo.addItem(new Object[] {"3", "Item 3"});
cmbMyCombo2.addItem(new Object[] {"1", "Item 1"});
cmbMyCombo2.addItem(new Object[] {"2", "Item 2"});
cmbMyCombo2.addItem(new Object[] {"3", "Item 3"});
cmbMyCombo.setRenderer(new MyListRenderer());
cmbMyCombo2.setRenderer(new MyListRenderer());
}
Here is the code of the events. This set the text feilds per selected item:
这是事件的代码。这将设置每个选定项目的文本字段:
private void cmbMyComboActionPerformed(
java.awt.event.ActionEvent evt) {
Object mySelectedItem = cmbMyCombo.getSelectedItem();
Object myObject[] = (Object[])mySelectedItem;
txtID.setText(myObject[0].toString());
txtName.setText(myObject[1].toString());
}
private void cmbMyCombo2ActionPerformed(
java.awt.event.ActionEvent evt) {
Object mySelectedItem = cmbMyCombo.getSelectedItem();
Object myObject[] = (Object[])mySelectedItem;
txtID1.setText(myObject[0].toString());
txtName1.setText(myObject[1].toString());
}
Here is the full code that can be cut and past to Comply with SC and C. Do not forget to add the custom renderer "MyListRenderer" class. (compiled with NetBean 7.1) :
这是可以剪切和粘贴到 Comply with SC 和 C 的完整代码。不要忘记添加自定义渲染器“MyListRenderer”类。(使用 NetBean 7.1 编译):
package combobox;
public class MyComboBox extends javax.swing.JFrame {
public MyComboBox() {
initComponents();
iniCombobox();
}
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
cmbMyCombo = new javax.swing.JComboBox();
lblId = new javax.swing.JLabel();
txtID = new javax.swing.JTextField();
lblName = new javax.swing.JLabel();
txtName = new javax.swing.JTextField();
jPanel2 = new javax.swing.JPanel();
cmbMyCombo2 = new javax.swing.JComboBox();
txtID1 = new javax.swing.JTextField();
lblId1 = new javax.swing.JLabel();
txtName1 = new javax.swing.JTextField();
lblName1 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants
.EXIT_ON_CLOSE);
jPanel1.setBorder(javax.swing.BorderFactory
.createTitledBorder("Combo 1"));
cmbMyCombo.setEditable(true);
cmbMyCombo.addActionListener(new java.awt.event
.ActionListener() {
public void actionPerformed(java.awt.event
.ActionEvent evt) {
cmbMyComboActionPerformed(evt);
}
});
lblId.setText("ID:");
lblName.setText("Name:");
javax.swing.GroupLayout jPanel1Layout = new javax
.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax
.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(
javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout
.Alignment.TRAILING,
jPanel1Layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(cmbMyCombo, javax
.swing.GroupLayout.PREFERRED_SIZE,
141,
javax.swing.GroupLayout
.PREFERRED_SIZE)
.addGap(40, 40, 40))
.addGroup(jPanel1Layout
.createSequentialGroup()
.addGroup(jPanel1Layout
.createParallelGroup(
javax.swing.GroupLayout
.Alignment.LEADING)
.addGroup(jPanel1Layout
.createSequentialGroup()
.addComponent(lblId)
.addGap(28, 28, 28)
.addComponent(txtID, javax
.swing.GroupLayout
.PREFERRED_SIZE, 66,
javax.swing.GroupLayout
.PREFERRED_SIZE)
.addPreferredGap(javax
.swing.LayoutStyle
.ComponentPlacement.RELATED,
81,
javax.swing.GroupLayout
.PREFERRED_SIZE))
.addGroup(jPanel1Layout
.createSequentialGroup()
.addComponent(lblName)
.addPreferredGap(javax
.swing.LayoutStyle
.ComponentPlacement.RELATED)
.addComponent(txtName,
javax.swing.GroupLayout
.PREFERRED_SIZE,
147, javax.swing
.GroupLayout
.PREFERRED_SIZE)))
.addContainerGap(
35, Short.MAX_VALUE))))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax
.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(cmbMyCombo, javax.swing
.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle
.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(
javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txtID,
javax.swing.GroupLayout
.PREFERRED_SIZE, javax.swing
.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lblId))
.addPreferredGap(javax.swing.LayoutStyle
.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(
javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lblName)
.addComponent(txtName,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout
.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel2.setBorder(javax.swing.BorderFactory
.createTitledBorder("Combo 2"));
cmbMyCombo2.setToolTipText("");
cmbMyCombo2.addActionListener(
new java.awt.event.ActionListener() {
public void actionPerformed(
java.awt.event.ActionEvent evt) {
cmbMyCombo2ActionPerformed(evt);
}
});
lblId1.setText("ID:");
lblName1.setText("Name:");
javax.swing.GroupLayout jPanel2Layout =
new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(
javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(
javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(
jPanel2Layout.createSequentialGroup()
.addGap(41, 41, 41)
.addComponent(
cmbMyCombo2,
javax.swing.GroupLayout
.PREFERRED_SIZE, 135,
javax.swing.GroupLayout
.PREFERRED_SIZE))
.addGroup(
jPanel2Layout.createSequentialGroup()
.addGap(18, 18, 18)
.addGroup(jPanel2Layout
.createParallelGroup(
javax.swing.GroupLayout
.Alignment.LEADING)
.addGroup(
jPanel2Layout
.createSequentialGroup()
.addComponent(lblId1)
.addGap(28, 28, 28)
.addComponent(txtID1,
javax.swing.GroupLayout
.PREFERRED_SIZE,
66,
javax.swing.GroupLayout
.PREFERRED_SIZE)
.addPreferredGap(
javax.swing.LayoutStyle
.ComponentPlacement.RELATED,
81, javax.swing.GroupLayout
.PREFERRED_SIZE))
.addGroup(jPanel2Layout
.createSequentialGroup()
.addComponent(lblName1)
.addPreferredGap(
javax.swing.LayoutStyle
.ComponentPlacement.RELATED)
.addComponent(txtName1,
javax.swing.GroupLayout
.PREFERRED_SIZE,
147,
javax.swing.GroupLayout
.PREFERRED_SIZE)))))
.addContainerGap(25, Short.MAX_VALUE))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(
javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(
cmbMyCombo2,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle
.ComponentPlacement.RELATED)
.addGroup(jPanel2Layout.createParallelGroup(
javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(
txtID1,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lblId1))
.addPreferredGap(
javax.swing.LayoutStyle.ComponentPlacement
.RELATED)
.addGroup(
jPanel2Layout.createParallelGroup(
javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lblName1)
.addComponent(txtName1,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(
javax.swing.GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE))
);
javax.swing.GroupLayout layout =
new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(
javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(
jPanel1,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(
jPanel2,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(
javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(
javax.swing.GroupLayout.Alignment.LEADING,
false)
.addComponent(
jPanel1,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE)
.addComponent(
jPanel2,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE))
.addContainerGap(
javax.swing.GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE))
);
pack();
}
private void cmbMyComboActionPerformed(
java.awt.event.ActionEvent evt) {
Object mySelectedItem = cmbMyCombo.getSelectedItem();
Object myObject[] = (Object[])mySelectedItem;
txtID.setText(myObject[0].toString());
txtName.setText(myObject[1].toString());
}
private void cmbMyCombo2ActionPerformed(
java.awt.event.ActionEvent evt) {
Object mySelectedItem = cmbMyCombo2.getSelectedItem();
Object myObject[] = (Object[])mySelectedItem;
txtID1.setText(myObject[0].toString());
txtName1.setText(myObject[1].toString());
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new MyComboBox().setVisible(true);
}
});
}
private javax.swing.JComboBox cmbMyCombo;
private javax.swing.JComboBox cmbMyCombo2;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JLabel lblId;
private javax.swing.JLabel lblId1;
private javax.swing.JLabel lblName;
private javax.swing.JLabel lblName1;
private javax.swing.JTextField txtID;
private javax.swing.JTextField txtID1;
private javax.swing.JTextField txtName;
private javax.swing.JTextField txtName1;
// End of variables declaration
private void iniCombobox() {
cmbMyCombo.addItem(new Object[] {"1", "Item 1"});
cmbMyCombo.addItem(new Object[] {"2", "Item 2"});
cmbMyCombo.addItem(new Object[] {"3", "Item 3"});
cmbMyCombo2.addItem(new Object[] {"1", "Item 1"});
cmbMyCombo2.addItem(new Object[] {"2", "Item 2"});
cmbMyCombo2.addItem(new Object[] {"3", "Item 3"});
cmbMyCombo.setRenderer(new MyListRenderer());
cmbMyCombo2.setRenderer(new MyListRenderer());
}
}
回答by marcb
Finally...To accomplish this, I had to add a basic custom ComboBox editor and set the custom editor to my combobox in my original code (included in my question):
最后......为了实现这一点,我必须添加一个基本的自定义 ComboBox 编辑器,并在我的原始代码中将自定义编辑器设置为我的组合框(包含在我的问题中):
cmbMyCombo.setEditor(new MyComboEditor());
The custom Combo Box Editor class need to implement ComboBoxEditor. i had 6 method to override. But here are the 3 main one. In getEditorComponent, i return a text feild, but i could return any type of component.
自定义组合框编辑器类需要实现 ComboBoxEditor。我有 6 种方法可以覆盖。但这里有 3 个主要的。在 getEditorComponent 中,我返回一个文本字段,但我可以返回任何类型的组件。
@Override
public Component getEditorComponent() {
return textFeild;
}
Then I set the text in the textFeild as per my selected object data[1] in setItem() (note that I'm keeping my original objet to be return later "myReturnObject"):
然后我根据我在 setItem() 中选择的对象数据 [1] 设置 textFeild 中的文本(请注意,我保留了我的原始对象以便稍后返回“myReturnObject”):
@Override
public void setItem(Object anObject) {
if(anObject != null){
myObject = (Object[])anObject;
myReturnObject = anObject;
//I can now set whatever i want in the text feild
textFeild.setText(myObject[1].toString());//<--
}
else{
myReturnObject = anObject;
}
}
I then return the original object if it selected from list or a custom object if the text feild has been edited.
然后,如果从列表中选择原始对象,则返回原始对象,如果文本字段已被编辑,则返回自定义对象。
@Override
public Object getItem() {
String objectTxt = myObject[1].toString();
String feildTxt = textFeild.getText();
if(objectTxt.equals(feildTxt)){
return myReturnObject;
}
else{
//Creating and returning custom object with the Feild text
//and setting the contnent of the text feild in the object
return new Object[]{"0",textFeild.getText()};
}
}
This is a lot of work for a combo box, but it worth it in my case. Hope this can help someone else.
对于组合框来说,这是很多工作,但在我的情况下是值得的。希望这可以帮助别人。
Here are referance for this work: http://www.java2s.com/Code/Java/Swing-JFC/AfancyexampleofJComboBoxwithacustomrendererandeditor.htmhttp://docs.oracle.com/javase/tutorial/uiswing/components/combobox.html Here is the full code for the custom combo editor "MyComboEditor()":
以下是这项工作的参考:http: //www.java2s.com/Code/Java/Swing-JFC/AfancyexampleofJComboBoxwithacustomrendererandeditor.htmhttp://docs.oracle.com/javase/tutorial/uiswing/components/combobox.html 这里是自定义组合编辑器“MyComboEditor()”的完整代码:
package combobox;
import java.awt.Component;
import java.awt.event.ActionListener;
import javax.swing.ComboBoxEditor;
import javax.swing.JTextField;
public class MyComboEditor implements ComboBoxEditor {
JTextField textFeild;
Object myObject[];
Object myReturnObject;
public MyComboEditor(){
textFeild = new JTextField();
}
@Override
public Component getEditorComponent() {
return textFeild;
}
@Override
public void setItem(Object anObject) {
if(anObject != null){
myObject = (Object[])anObject;
myReturnObject = anObject;
textFeild.setText(myObject[1].toString());
}
else{
myReturnObject = anObject;
}
}
@Override
public Object getItem() {
String objectTxt = myObject[1].toString();
String feildTxt = textFeild.getText();
if(objectTxt.equals(feildTxt)){
return myReturnObject;
}
else{
return new Object[]{"0",textFeild.getText()};
}
}
@Override
public void selectAll() {
throw new UnsupportedOperationException(
"Not supported yet. in select All");
}
@Override
public void addActionListener(ActionListener l) {
textFeild.addActionListener(l);
}
@Override
public void removeActionListener(ActionListener l) {
textFeild.removeActionListener(l);
}
}
回答by mKorbel
I do set myComboBox.setRenderer(new MyListRenderer()); What ever i chose in the list return the object in the combo Text field. Note: The id in my Object[]{id, nomClient} is my referance to the database.
我确实设置了 myComboBox.setRenderer(new MyListRenderer()); 我在列表中选择的内容返回组合文本字段中的对象。注意:我的 Object[]{id, nomClient} 中的 id 是我对数据库的引用。
Renderer(the same concept for JTable
, JList
and JComboBox
too) is for formatting value that already exist (Color
, Font
, Background
, Foreground
), don't add
, put
, change
or modify
whatever inside Renderer
渲染器(对于同一个概念JTable
,JList
而JComboBox
太)是一个用于格式化值已经存在(Color
,Font
,Background
,Foreground
),不add
,put
,change
或modify
任何内Renderer
How can i fix this?
我怎样才能解决这个问题?
put data as Items
to the JComboBox
directly, in your case to update the ComboBoxModel, notice add
, put
, change
or modify
must be done on Event Dispatch Thread
把数据Items
的JComboBox
直接,你的情况来更新的ComboBoxModel,通知add
,put
,change
或者modify
必须在完成事件分派线程