MainClass.java Source code

Java tutorial

Introduction

Here is the source code for MainClass.java

Source

import java.awt.Dimension;
import java.awt.Event;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.util.Vector;

import javax.swing.AbstractAction;
import javax.swing.ComboBoxEditor;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;

public class MainClass extends JFrame {
    JComboBox jcb;

    MainClass(String title) {
        super(title);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel jp = new JPanel();

        Vector v = new Vector();
        v.add("A");
        v.add("B");
        v.add("C");

        jcb = new JComboBox(v);
        jcb.setEditable(true);

        KeyStroke ks = KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, Event.CTRL_MASK);

        jcb.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(ks, "clearEditor");
        jcb.getActionMap().put("clearEditor", new ClearEditorAction());

        jp.setPreferredSize(new Dimension(200, 35));
        jp.add(jcb);
        getContentPane().add(jp);

        pack();
        setVisible(true);
    }

    public static void main(String[] args) {
        new MainClass("Binding Demo3");
    }
}

class ClearEditorAction extends AbstractAction {
    public void actionPerformed(ActionEvent e) {
        JComboBox jcb = (JComboBox) e.getSource();

        ComboBoxEditor cbe = jcb.getEditor();

        cbe.setItem("");
    }
}