Show tooltip when JComboBox key is pressed

 Code that shows tooltip when key occurs by key listener in JComboBox


package test.swing;

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;

// key event tooltip
public class MainTest {
    public static void main(String[] args) {
        MainUI mainUI = new MainUI();
        mainUI.setVisible(true);
    }
}

class TestComboBox extends JComboBox {
    JTextField mTf = null;
    public TestComboBox() {
        super();
        mTf = (JTextField) editor.getEditorComponent();
        mTf.setToolTipText("TextField : ");
        mTf.addKeyListener(new KeyHandler());
    }

    class KeyHandler extends KeyAdapter {
        @Override
        public void keyReleased(KeyEvent e) {
            // set tooltip
            mTf.setToolTipText("TextField : " + mTf.getText());
            // show tooltip
            ToolTipManager.sharedInstance().mouseMoved(new MouseEvent(mTf, 0, 0, 0,0, 0, 0, false));
            super.keyReleased(e);
        }
    }
}

class MainUI extends JFrame {
    MainUI() {
        setPreferredSize(new Dimension(400, 300));
        setLayout(new FlowLayout());
        TestComboBox combo = new TestComboBox();
        combo.setToolTipText("ComboBox");
        combo.setEditable(true);
        add(combo);
        pack();
    }
}

No comments:

Lognote - My toy project

In a project, the code work is limited When I say, "I think it will work if I change it like this," I get, "If it doesn't...