Shortcut keys in Java (Mnemonic) - java

I need help with my homework. I can't seem to make this program work. I just need to put shortcut keys for the compute, reset, and exit buttons.
Compute - Ctrl C
Reset - Ctrl R
Exit - Ctrl E
If you guys need my professor's instructions, I can provide that as well.
here
Here's my code:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Calculator extends JFrame implements ActionListener{
JLabel fval,sval;
JTextField tf1,tf2;
JButton add,subtract,multiply,divide,compute,reset;
String s="";
JPanel jp = new JPanel();
Calculator(){
jp.setLayout(new GridLayout(5,2));
fval=new JLabel("First Value: ");
sval=new JLabel("Second Value: ");
tf1=new JTextField();
tf2=new JTextField();
add=new JButton("ADD");
subtract=new JButton("SUBTRACT");
multiply=new JButton("MULTIPLY");
divide=new JButton("DIVIDE");
compute=new JButton("COMPUTE");
reset=new JButton("RESET");
jp.add(fval);
jp.add(tf1);
jp.add(sval);
jp.add(tf2);
jp.add(add);
jp.add(subtract);
jp.add(multiply);
jp.add(divide);
jp.add(compute);
jp.add(reset);
add.addActionListener(this);
subtract.addActionListener(this);
multiply.addActionListener(this);
divide.addActionListener(this);
compute.addActionListener(this);
reset.addActionListener(this);
this.setTitle("Calculator");
this.setBounds(10,10,300,300);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(false);
add(jp);
//ADD
Action addAction = new AbstractAction("ADD") {
#Override
public void actionPerformed(ActionEvent evt) {
s="ADD";
}
};
String key1 = "ADD";
add.setAction(addAction);
addAction.putValue(Action.MNEMONIC_KEY, KeyEvent.VK_A);
add.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
KeyStroke.getKeyStroke(KeyEvent.VK_A, KeyEvent.CTRL_DOWN_MASK), key1);
add.getActionMap().put(key1, addAction);
//SUBTRACT
Action subAction = new AbstractAction("SUBTRACT") {
#Override
public void actionPerformed(ActionEvent evt) {
s="SUBTRACT";
}
};
String key2 = "SUBTRACT";
subtract.setAction(subAction);
subAction.putValue(Action.MNEMONIC_KEY, KeyEvent.VK_S);
subtract.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
KeyStroke.getKeyStroke(KeyEvent.VK_S, KeyEvent.CTRL_DOWN_MASK), key2);
subtract.getActionMap().put(key2, subAction);
//MULTIPLY
Action mulAction = new AbstractAction("MULTIPLY") {
#Override
public void actionPerformed(ActionEvent evt) {
s="MULTIPLY";
}
};
String key3 = "MULTIPLY";
multiply.setAction(mulAction);
mulAction.putValue(Action.MNEMONIC_KEY, KeyEvent.VK_M);
multiply.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
KeyStroke.getKeyStroke(KeyEvent.VK_M, KeyEvent.CTRL_DOWN_MASK), key3);
multiply.getActionMap().put(key3, mulAction);
//DIVIDE
Action divAction = new AbstractAction("DIVIDE") {
#Override
public void actionPerformed(ActionEvent evt) {
s="DIVIDE";
}
};
String key4 = "DIVIDE";
divide.setAction(divAction);
divAction.putValue(Action.MNEMONIC_KEY, KeyEvent.VK_D);
divide.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
KeyStroke.getKeyStroke(KeyEvent.VK_D, KeyEvent.CTRL_DOWN_MASK), key4);
divide.getActionMap().put(key4, divAction);
}
public void Add(double n1,double n2){
JOptionPane.showMessageDialog(this, +(n1+n2), "Answer", JOptionPane.INFORMATION_MESSAGE);
}
public void Subtract(double n1,double n2){
JOptionPane.showMessageDialog(this, +(n1-n2), "Answer", JOptionPane.INFORMATION_MESSAGE);
}
public void Multiply(double n1,double n2){
JOptionPane.showMessageDialog(this, +(n1*n2), "Answer", JOptionPane.INFORMATION_MESSAGE);
}
public void Divide(double n1,double n2){
JOptionPane.showMessageDialog(this, +(n1/n2), "Answer", JOptionPane.INFORMATION_MESSAGE);
}
#Override
public void actionPerformed(ActionEvent e) {
String in=e.getActionCommand();
if(in.equals("COMPUTE")){
try {
double n1=Double.parseDouble(tf1.getText());
double n2=Double.parseDouble(tf2.getText());
if(s.equals("ADD"))
Add(n1,n2);
else if(s.equals("SUBTRACT"))
Subtract(n1,n2);
else if(s.equals("MULTIPLY"))
Multiply(n1,n2);
else if(s.equals("DIVIDE"))
Divide(n1,n2);
else if(in.equals("RESET")){
tf1.setText("");
tf2.setText("");
s="";
}else
{
s=in;
}
}
catch (NumberFormatException e1) {
compute.setSelected(true);
JOptionPane.showMessageDialog(this, "Math Error.", "Warning", JOptionPane.INFORMATION_MESSAGE);
}
}
};
public static void main(String[] args) {
new Calculator();
}
}
Thank you in advance!

I just need to put shortcut keys for the compute, reset, and exit buttons.
I think you are confusing a "mnemonic" with an "accelerator".
The "mnemonic" is invoked when the component is focused. You invoke the Action by using the "Alt" key plus the underlined character of the text on the button.
The "accelerator" can be invoked even when the component doesn't have focus by using the specified KeyStroke.
So instead of attempting use Key Bindings directly, you can set the "accelerator" of the Action. When you add the Action to the button the key bindings will be set automatically for you.
Read the section from the Swing tutorial on How to Use Actions for more information

Related

Java doubts about ActionEvent

this is my first question on this website.
I have this problem, in this class I have two buttons with two different functions, one to exit and another to put the first and last name in a text field.
I can't get the second ActionEvent to work, please help me, thanks.
import javax.swing.*;
import java.awt.event.*;
public class Prueba1 extends JFrame implements ActionListener{
private JLabel nombre, apellidos,respondo;
private JTextField textfield, textfield1;
private JButton boton,botonoff;
public Prueba1() {
setLayout(null);
nombre = new JLabel("Nombre:");
nombre.setBounds(10, 10, 300, 30);
add(nombre);
apellidos = new JLabel("Apellidos");
apellidos.setBounds(10, 40, 300, 30);
add(apellidos);
textfield = new JTextField();
textfield.setBounds(100,10,150,20);
add(textfield);
textfield1 = new JTextField();
textfield1.setBounds(100,40,150,20);
add(textfield1);
boton = new JButton("¿Que saldrá?");
boton.setBounds(10,80,120,30);
boton.addActionListener(this);
add(boton);
botonoff = new JButton("Salir");
botonoff.setBounds(10,120,120,30);
botonoff.addActionListener(this);
add(botonoff);
respondo = new JLabel("UwU");
respondo.setBounds(160,80,300,30);
add(respondo);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource() == boton) {
String nombreyapellidos, nombre1, apellidos1;
nombre1 = textfield.getText();
apellidos1 = textfield1.getText();
nombreyapellidos = nombre1 + apellidos1;
respondo.setText(nombreyapellidos);
}
}
public void actionPerformed1(ActionEvent e) {
if(e.getSource() == botonoff) {
System.exit(0);
}
}
public static void main(String args[]) {
Prueba1 clase = new Prueba1();
clase.setVisible(true);
clase.setBounds(0, 0, 500, 500);
clase.setResizable(true);
clase.setLocationRelativeTo(null);
}
}
Remove public void actionPerformed1(ActionEvent e) method and add the body of that method in the else branch in the body of public void actionPerformed(ActionEvent e).
public void actionPerformed(ActionEvent e) {
if (e.getSource() == boton) {
String nombreyapellidos, nombre1, apellidos1;
nombre1 = textfield.getText();
apellidos1 = textfield1.getText();
nombreyapellidos = nombre1 + apellidos1;
respondo.setText(nombreyapellidos);
} else if (e.getSource() == botonoff) {
System.exit(0);
}
}
When you provide an ActionListener object to a buttons button.addActionListener(listener)
You have several ways to accomplish this.
button.addActionListener(this);
Is only one way. This way says the the class implements ActionListener.
In effect it implements the
public void actionPerformed(ActionEvent e)
method.
Your
public void actionPerformed1(ActionEvent e)
can't be used by the button at all.
Fortunately there are many other ways to describe the code that should be executed when an action event is produced.
An inner class, static or not. Other class/object.
A lambda expression.
You can find how to express a lambda here.

Terminal class called from JFrame class don't have user inputs for a reason

Here is my code
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class Login
{
static BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in));
static String a, b, c;
static int d, z, f, g, h, i, k;
public static void Login()
{
JFrame frame = new JFrame("Login");
JButton button1 = new JButton("Login");
JLabel label1 = new JLabel("Username: ");
JLabel label2 = new JLabel("Pin: ");
JTextField txt1 = new JTextField(8);
JPasswordField pass1 = new JPasswordField(8);
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
JPanel FormPanel = new JPanel();
txt1.setBackground(Color.white);
pass1.setBackground(Color.white);
panel1.add(label1);
panel1.add(txt1);
panel2.add(label2);
panel2.add(pass1);
FormPanel.setLayout(new GridLayout(3,8));
FormPanel.add(panel1);
FormPanel.add(panel2);
FormPanel.add(button1);
pass1.getDocument().addDocumentListener(new DocumentListener()
{
public void changedUpdate(DocumentEvent e)
{
changed();
}
public void removeUpdate(DocumentEvent e)
{
changed();
}
public void insertUpdate(DocumentEvent e)
{
changed();
}
public void changed()
{
if (pass1.getText().equals(""))
{
button1.setEnabled(false);
}
else
{
button1.setEnabled(true);
}
}
});
txt1.getDocument().addDocumentListener(new DocumentListener()
{
public void changedUpdate(DocumentEvent e)
{
changed();
}
public void removeUpdate(DocumentEvent e)
{
changed();
}
public void insertUpdate(DocumentEvent e)
{
changed();
}
public void changed()
{
if (txt1.getText().equals(""))
{
button1.setEnabled(false);
}
else
{
button1.setEnabled(true);
}
}
});
button1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
frame.hide();
Body a = new Body();
a.Body();
}
});
button1.setActionCommand("Open");
frame.setContentPane(FormPanel);
frame.setSize(8,9);
frame.pack();
frame.show();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
}
}
and my Body.java is
try
{
do
{
System.out.print("Working time (hours): ");
a=dataIn.readLine();
e=Integer.parseInt(a);
k=e;
if(k<8)
{
System.out.print("\nYou have worked undertime");
g=e * 30;
h=g * 500;
i=h-200;
System.out.print("\nYour payment (per month) is: " +i);
}
if(k>8)
{
System.out.print("\nYou have worked overtime");
g=e*30;
h=g*500;
i=h+200;
System.out.print("\nYour payment (per month) is: " +i);
}
if(k==8)
{
System.out.print("\nYou have worked ontime");
g=e*30;
h=g*500;
System.out.print("\nYour payment (per month) is: " +h);
}
System.out.print("\n\nPress 0 to logout: ");
c=dataIn.readLine();
d=Integer.parseInt(c);
}while(d!=0);
}
catch(Exception j)
{
System.out.print("\nYou probably need to work for more than an hour to start earning");
}
of course I have import java.io.*; and BufferedReader dataIn = new BufferedReader(<arguments>); but when ever I call the body.java that opens in terminal it won't ask for user inputs, but when I try to execute the body.java it asks for user inputs...
I need help right now...
You ask:
okay.. then please tell me how can I do some simple calculations in full GUI?
Again you'll want to avoid trying to mix GUI with console programs since they interact with the user in two very dissimilar ways, and the console can lock up the GUI if you're not careful. Instead consider going all console or all GUI.
If you go all GUI, one possible solution is to create a GUI that is similar to what you're already doing with user name and PIN number:
Give your GUI JTextFields for the user to input his data.
Add a "Calculate" JButton
In the button's ActionListener, extract the data from the JTextFields, convert any Strings to numbers that need converting, calculate your value and display it in another JTextField or JLabel.
Other side recommendations:
Don't call deprecated methods since they're deprecated for a good reason. Instead the Java API will usually tell you what alternatives to use.
Avoid over-use of static variables and methods, since this leads to rigid code that is difficult to test or enhance.
Try to give your variables names that have meaning so that your code becomes "self-commenting".
Your log-in window should be a modal dialog of some type, such as a modal JDialog, not a JFrame, since
Closing it will not close the entire GUI
It will prevent interacting with the main GUI until it has been fully dealt with.

Event call doesn't work with key bind or click - what's the logical error?

I'm trying to call this event below; I create the frame with TabBuilder (since is part of my application) then it calls the Search screen which is popping up; but the event of the search with key bind or simple click on the button is not working and of course I'm doing something wrong but I don't know what since I'm a little bit new in Java. Please could anyone help me?
SearchScreen:
public class SearchScreen extends EventSearch{
public static void main (String[] args){
SearchScreen s= new SearchScreen();
}
public void SearchScreen(){
TabBuilder tb = new TabBuilder();
tb.searchTab();
}
}
EventSearch:
public class EventSearch extends TabBuilder{
String userQuery;
String key = "ENTER";
KeyStroke keyStroke = KeyStroke.getKeyStroke(key);
public EventSearch(){
btSearch.addActionListener(this);
txtSearch.getInputMap().put(keyStroke, key);
txtSearch.getActionMap().put(key, enterAction);
}
Action enterAction = new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
try{
System.out.println("worked");
} catch (IOException e1) {
e1.printStackTrace(); //print failure
JOptionPane.showMessageDialog(null, "HTTP request failure.");
}
}
};
}
TabBuilder:
public class TabBuilder implements ActionListener {
protected JButton btSearch;
JMenuItem close, search;
protected JTextField txtSearch;
protected JFrame searchFrame = new JFrame();
public void TabBuilder(){
}
public void searchTab(){
JLabel lbSearch;
JPanel searchPane;
btSearch= new JButton("Search");
lbSearch= new JLabel("Type Keywords in english to be searched below:");
lbSearch.setHorizontalAlignment(SwingConstants.CENTER);
txtSearch= new JTextField();
searchPane=new JPanel();
searchPane.setBackground(Color.gray);
searchPane.add(lbSearch);
searchPane.add(txtSearch);
searchPane.add(btSearch);
searchPane.setLayout(new GridLayout(3,3));
btSearch.setEnabled(true);
searchFrame.add(searchPane);
searchFrame.setTitle("SHST");
searchFrame.setSize(400, 400);
searchFrame.setVisible(true);
searchFrame.setDefaultCloseOperation(1);
}
public void actionPerformed(ActionEvent e){
if(e.getSource()==close){
System.exit(0);
}
if(e.getSource()==search){
SearchScreen s = new SearchSreen();
}
}
}
You write this actionListener
public void actionPerformed(ActionEvent e){
if(e.getSource()==close){
System.exit(0);
}
if(e.getSource()==search){
TabBuilder tb = new TabBuilder();
tb.searchTab();
}
}
and you added to btnSearch.addActionListener(this) , your actionListener never would do anything.
And for your KeyBinding happens something similar , you add the action to the txtSearch and then you are asking if the source is the e.getSource()==btSearch
And for KeyBindings you can use Constants to specify when they have to be binded.
JComponent.WHEN_FOCUSED, JComponent.WHEN_IN_FOCUSED_WINDOW , JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT
For example :
txtSearch.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(keyStroke, key);
How to use KeyBindings

Java 1.7 issue, Enter key pressed work differently

I have following code
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class TesttxtF {
/**
* #param args
*/
public static void main(String[] args) {
TextField txt1 = new TextField();
TextField txt2 = new TextField();
DefaultFocusManager manager = new DefaultFocusManager() {
#Override
public void processKeyEvent(Component focusedComponent, KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_ENTER:
if (e.getID() == KeyEvent.KEY_PRESSED)
super.focusNextComponent(focusedComponent);
else
super.processKeyEvent(focusedComponent, e);
break;
default:
super.processKeyEvent(focusedComponent, e);
break;
}
}
};
FocusManager.setCurrentManager(manager);
JPanel panel = new JPanel();
panel.add(txt1);
panel.add(txt2);
txt1.addKeyListener(new KeyListener() {
#Override
public void keyTyped(KeyEvent e) {
System.out.println("Key keyTyped");
}
#Override
public void keyReleased(KeyEvent e) {
System.out.println("Key keyReleased");
}
#Override
public void keyPressed(KeyEvent e) {
System.out.println("Key Pressed");
}
});
txt1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Action performed");
}
});
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel, null);
frame.setSize(100, 100);
frame.setVisible(true);
}
}
When run with
jdk1.6.0_18 -> output as following when pressing enter key
Key Pressed
Key keyTyped
Action performed
jdk1.7.0_12 -> output as following when pressing enter key
Key Pressed
What is wrong with java 7 then ?
when i typed any number and clear the console. Then press the Enter key focus changed to next component but actionperformed never fired in java 7. How i can fix it ? i had checked with java 7 update 25 also. i got same result. Can anybody help ?

Java Swing Combobox removeAllItems calling ItemStateChanged also?

My code is quite simple actually. I saw a simple and similar code was from this article.
At first, I have 1 combobox. I have a listener on it called itemStateChanged(). My purpose to add into this listener is that; "to execute some code when user click (select) an item from its dropbox".
Cmb_ItemCategory = new javax.swing.JComboBox();
Cmb_ItemCategory.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Loading..." }));
Cmb_ItemCategory.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
Cmb_ItemCategoryItemStateChanged(evt);
}
});
private void Cmb_ItemCategoryItemStateChanged(java.awt.event.ItemEvent evt) {
if(evt.getStateChange() == java.awt.event.ItemEvent.SELECTED){
System.err.println("Sombody click or change my model content");
}
}
Behind the code, I grab some data, and then calling a method of removeAllItems() .
And then I set a new Model (from new data) into it.
-- at another line of code ---
Cmb_ItemCategory.removeAllItems();
Cmb_ItemCategory.setModel(newModel);
I juz realized that my itemStateChanged() is called when i do the removeAllItem() method. called once.
So, How to make it only called once user Click (select) only AND not when removeAllItems() called?
it similar to this article. But it's not removingItems case. CMIIW.
Here check this code out, this works flawlessly, might be you doing something wrong where you calling removeAllItems() :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ComboState
{
private void createAndDisplayGUI()
{
JFrame frame = new JFrame("Combo State Testing : ");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
final JComboBox cbox = new JComboBox();
cbox.addItem("One");
cbox.addItem("Two");
cbox.addItem("Three");
cbox.addItem("Four");
cbox.addItemListener(new ItemListener()
{
public void itemStateChanged(ItemEvent ie)
{
if (ie.getStateChange() == ItemEvent.SELECTED)
{
System.out.println("Item Selected is : " + ie.getItem());
}
/*else
{
System.out.println("I am called for other reasons.");
}*/
}
});
/*
* Click me to remove JComboBox's items.
*/
JButton removeButton = new JButton("REMOVE");
removeButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
cbox.removeAllItems();
}
});
frame.add(cbox, BorderLayout.CENTER);
frame.add(removeButton, BorderLayout.PAGE_END);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new ComboState().createAndDisplayGUI();
}
});
}
}
As nIcE cOw already illustrated in his example, it should certainly work when you use a DefaultComboBoxModel (which is the case in his sample code, although it happens behind the screens).
I could explain the behavior you encounter for the non-DefaultComboBoxModel case, although your code snippet suggests you use one. Looking at the source code for JComboBox#removeAllItems there is a different code path since the removeAllElements method is not part of the MutableComboBoxModel interface
public void removeAllItems() {
checkMutableComboBoxModel();
MutableComboBoxModel<E> model = (MutableComboBoxModel<E>)dataModel;
int size = model.getSize();
if ( model instanceof DefaultComboBoxModel ) {
((DefaultComboBoxModel)model).removeAllElements();
}
else {
for ( int i = 0; i < size; ++i ) {
E element = model.getElementAt( 0 );
model.removeElement( element );
}
}
selectedItemReminder = null;
if (isEditable()) {
editor.setItem(null);
}
}
So with a non-DefaultComboBoxModel you are going to remove the items one by one. This means that at a certain point in time, you will remove the selected element. A possible implementation of your model might change the selected element at that point. If you look for example at the implementation in DefaultComboBoxModel (although this code will not be triggered) you can clearly see it changes the selection.
public void removeElementAt(int index) {
if ( getElementAt( index ) == selectedObject ) {
if ( index == 0 ) {
setSelectedItem( getSize() == 1 ? null : getElementAt( index + 1 ) );
}
else {
setSelectedItem( getElementAt( index - 1 ) );
}
}
objects.removeElementAt(index);
fireIntervalRemoved(this, index, index);
}
Perhaps your model does something similar, which explains the event. Just for making this post complete, the code behind the DefaultComboBoxModel#removeAllElements where you can clearly see it sets the selection to null and does not select another object. Only weird thing in that code is that it does not fire a DESELECTED event first, although you know the selection has changed if you listen for the intervalRemoved event ... but that is not really relevant to your problem
public void removeAllElements() {
if ( objects.size() > 0 ) {
int firstIndex = 0;
int lastIndex = objects.size() - 1;
objects.removeAllElements();
selectedObject = null;
fireIntervalRemoved(this, firstIndex, lastIndex);
} else {
selectedObject = null;
}
}
So to conclude: I say the solution for your problem is located in your model, and not in the code you posted
One quick way to do is to have a bool set to true before you call removeAllItem() and back false after. Execute the code in your itemStateChanged() only if the bool variable is false.
Ideally you could override the removeAllItem() function.
not clear from whole discusion,
you have to remove all Listener(s) from JComboBox before removing all Items, after Items are removed you can add Listener(s) back,
still not sure if you want to add & remove Items dynamically, or you can set whatever value for another JComponent(s),
(against complicating simple things) did you see there remove,
.
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
public class ComboBoxTwo extends JFrame implements ActionListener, ItemListener {
private static final long serialVersionUID = 1L;
private JComboBox mainComboBox;
private JComboBox subComboBox;
private Hashtable<Object, Object> subItems = new Hashtable<Object, Object>();
public ComboBoxTwo() {
String[] items = {"Select Item", "Color", "Shape", "Fruit"};
mainComboBox = new JComboBox(items);
mainComboBox.addActionListener(this);
mainComboBox.addItemListener(this);
//prevent action events from being fired when the up/down arrow keys are used
//mainComboBox.putClientProperty("JComboBox.isTableCellEditor", Boolean.TRUE);
getContentPane().add(mainComboBox, BorderLayout.WEST);
subComboBox = new JComboBox();// Create sub combo box with multiple models
subComboBox.setPrototypeDisplayValue("XXXXXXXXXX"); // JDK1.4
subComboBox.addItemListener(this);
getContentPane().add(subComboBox, BorderLayout.EAST);
String[] subItems1 = {"Select Color", "Red", "Blue", "Green"};
subItems.put(items[1], subItems1);
String[] subItems2 = {"Select Shape", "Circle", "Square", "Triangle"};
subItems.put(items[2], subItems2);
String[] subItems3 = {"Select Fruit", "Apple", "Orange", "Banana"};
subItems.put(items[3], subItems3);
// mainComboBox.setSelectedIndex(1);
}
#Override
public void actionPerformed(ActionEvent e) {
String item = (String) mainComboBox.getSelectedItem();
Object o = subItems.get(item);
if (o == null) {
subComboBox.setModel(new DefaultComboBoxModel());
} else {
subComboBox.setModel(new DefaultComboBoxModel((String[]) o));
}
}
#Override
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
if (e.getSource() == mainComboBox) {
if (mainComboBox.getSelectedIndex() != 0) {
FirstDialog firstDialog = new FirstDialog(ComboBoxTwo.this,
mainComboBox.getSelectedItem().toString(), "Please wait, Searching for ..... ");
}
}
}
}
private class FirstDialog extends JDialog {
private static final long serialVersionUID = 1L;
FirstDialog(final Frame parent, String winTitle, String msgString) {
super(parent, winTitle);
setModalityType(Dialog.ModalityType.APPLICATION_MODAL);
JLabel myLabel = new JLabel(msgString);
JButton bNext = new JButton("Stop Processes");
add(myLabel, BorderLayout.CENTER);
add(bNext, BorderLayout.SOUTH);
bNext.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
setVisible(false);
}
});
javax.swing.Timer t = new javax.swing.Timer(1000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
setVisible(false);
}
});
t.setRepeats(false);
t.start();
setLocationRelativeTo(parent);
setSize(new Dimension(400, 100));
setVisible(true);
}
}
public static void main(String[] args) {
JFrame frame = new ComboBoxTwo();
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
The method removeAllItems does not call ItemStateChanged, but it call actionPerformed, you can check it by running this simple code:
public class Tuto {
public static void main(String[] args) {
//create the main frame
JFrame frame = new JFrame();
frame.setResizable(false);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setLayout(null);
frame.setLocation(new Point(10, 10));
frame.setPreferredSize(new Dimension(400, 300));
JComboBox<String> combo = new JComboBox();
combo.addItem("item 1");
combo.addItem("item 2");
combo.addItem("item 3");
combo.setBounds(50, 30, 300, 20);
combo.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
System.out.println(" action Performed ");
}
});
frame.add(combo);
JButton button = new JButton("Remove");
button.setBounds(50, 100, 100, 30);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
combo.removeAllItems();
}
});
frame.add(button);
frame.pack();
frame.setVisible(true);
}
}

Categories