简体   繁体   English

为什么 JComboBox 在鼠标 hover 上触发 toString()?

[英]Why JComboBox firing toString() on mouse hover?

I have created a simple GUI, one JComboBox and JButton.我创建了一个简单的 GUI,一个 JComboBox 和一个 JButton。 JButton populate the JComboBox with objects of class testString. JButton 使用 class testString 的对象填充 JComboBox。 When mouse hover the JComboBox it fired toString() of testString class almost 25 time.当鼠标 hover JComboBox 触发 testString class 的 toString() 几乎 25 次时。 Why this happening?为什么会这样? How we can stop it?我们怎样才能阻止它?

here is code:这是代码:

import javax.swing.DefaultComboBoxModel;

public class _NewJFrame extends javax.swing.JFrame {

public _NewJFrame() {
    initComponents();
}

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    
    Object[] args = {new testString("ABC") , new testString("EDF") , "GIH", "IJK"}; 
    jComboBox1.setModel(new DefaultComboBoxModel(args ));
}                                        
public static void main(String args[]) {
        

            new _NewJFrame().setVisible(true);
            
             
}

private javax.swing.JButton jButton1;
private javax.swing.JComboBox<String> jComboBox1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextArea jTextArea1;
}



class testString {
String text; 
static int i; 
testString(String text){ this.text = text; }; 


public String toString(){
    System.out.println("ToSting() Called on Text " + text + " "+ ++i);

    return text; 
}


}

GUI output图形用户界面output

You can't stop the JComboBox from calling the toString() method of your items.您无法阻止JComboBox调用项目的toString()方法。

This is because the JComboBox needs to know what text it has to show to the user.这是因为JComboBox需要知道它必须向用户显示什么文本。

For this it calls the toString() method of the items (of the currently shown item on mouse-over, of all items when the drop down list).为此,它调用项目(鼠标悬停时当前显示的项目,下拉列表时的所有项目)的toString()方法。

@Thomas @托马斯

I have tried the following but results are same.我尝试了以下方法,但结果相同。

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    
    
    Object[] args = {new testString("ABC") , new testString("EDF") }; 
    jComboBox1.setModel(new DefaultComboBoxModel(args ));
    
    
    
    
    jComboBox1.setRenderer(new DefaultListCellRenderer() {
@Override
public Component getListCellRendererComponent(JList list,
                                           Object value,
                                           int index,
                                           boolean isSelected,
                                           boolean cellHasFocus) {
    testString employee = (testString)value;
    value = employee.mytoString();
    return super.getListCellRendererComponent(list, value,
            index, isSelected, cellHasFocus);
}
});
 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM