I have a table and at each row i have a combox of operator from which we can choose any operator and value1 field value 2 field. COMBO BOX DEFAULT OPERATOR IS " EQUAL TO".so my question is when u click on combobox in any row i should get the value of the selected row and get the operator which i am selecting such that i can perform some operation based on selected operator....
Or else if i change the combobox operator from in between to equal to i should get clear the value 2 field....
Help me get out of this..
You should have an event to know item in the combo is clicked.
Like this:
combo.addActionListener (new ActionListener () {
public void actionPerformed(ActionEvent e) {
//doSomething();
}
});
You have three methods to get current item selected:
Will get the index of the item is order number.
int selectedIndex = myComboBox.getSelectedIndex();
-or-
Will get item selected with Object. You can do many method contains in this Object.
Object selectedObject = myComboBox.getSelectedValue();
-or-
Will get real values of item selected with string type.
String selectedValue = myComboBox.getSelectedValue().toString();
You can see full example code at here (from #secario member):
import java.awt.FlowLayout;
import java.awt.event.*;
import javax.swing.*;
public class MyWind extends JFrame{
public MyWind() {
initialize();
}
private void initialize() {
setSize(300, 300);
setLayout(new FlowLayout(FlowLayout.LEFT));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JTextField field = new JTextField();
field.setSize(200, 50);
field.setText(" ");
JComboBox comboBox = new JComboBox();
comboBox.setEditable(true);
comboBox.addItem("item1");
comboBox.addItem("item2");
//
// Create an ActionListener for the JComboBox component.
//
comboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
//
// Get the source of the component, which is our combo
// box.
//
JComboBox comboBox = (JComboBox) event.getSource();
Object selected = comboBox.getSelectedItem();
if(selected.toString().equals("item1"))
field.setText("30");
else if(selected.toString().equals("item2"))
field.setText("40");
}
});
getContentPane().add(comboBox);
getContentPane().add(field);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new MyWind().setVisible(true);
}
});
}
}
Related
I am trying to change JCombobox items list (towns) depending on the value of the other JCombobox (city). When I change the value in the city list, it changes the items in the towns list. But there are 2 issues.
The updated list (towns) shows double of the items but when click on it then it shows the correct number of items as shown in the first screenshot.
The updated list doesn't allow me to choose one of the item, it only select the first item
here is my code:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Testing extends JFrame implements ActionListener {
public static void main(String[] args )
{
new Testing();
}
JComboBox cb,cb1,cb2;
JFrame f;
JLabel label1,label2;
JButton b1;
JTextField name,ID,birth;
Testing(){
f=new JFrame("Information Example");
label1 = new JLabel("Please input your information below");
label1.setBounds(10, 20, 260, 30);
f.add(label1);
String question[]={"Calculate my Age","When do I drive","When do I vote"};
String city[]={"Asimah","Ahmadi","Hawalli"};
name= new JTextField("NAME");
name.setBounds(10,50,264,25);
f.add(name);
ID= new JTextField("CIVIL ID");
ID.setBounds(10,80,264,25);
f.add(ID);
birth= new JTextField("DATE OF BIRTH");
birth.setBounds(10,110,264,25);
f.add(birth);
cb=new JComboBox(question);
cb.setBounds(50, 150,180,20);
f.add(cb);
b1= new JButton("Get");
b1.setBounds(100,250,60,20);
f.add(b1);
cb1=new JComboBox(city);
cb1.setBounds(10, 200,120,20);
f.add(cb1);
cb2=new JComboBox();
cb2.setBounds(150, 200,120,20);
f.add(cb2);
f.setLayout(null);
f.setSize(300,400);
f.setVisible(true);
cb.addActionListener(this);
cb1.addActionListener(this);
cb2.addActionListener(this);
}
#Override
public void actionPerformed(ActionEvent event)
{
if(cb1.getSelectedIndex() == 0)
{
cb2.removeAllItems();
cb2.addItem("Rawdhah");
cb2.addItem("Abdahll");
}
else if(cb1.getSelectedIndex() == 1)
{
cb2.removeAllItems();
cb2.addItem("Siddiq");
cb2.addItem("Aljabryha");
}
else
{
cb2.removeAllItems();
cb2.addItem("Fintas");
cb2.addItem("Abdahll");
}
}
}
So, basically, the combination of removeAllItems and addItem is causing the JComboBox to generate a ActionEvent, but only for the first new item added.
You should isolate your functionality to only perform certain actions based on the source of the event, for example...
#Override
public void actionPerformed(ActionEvent event) {
if (event.getSource() == cb1) {
if (cb1.getSelectedIndex() == 0) {
cb2.removeAllItems();
System.out.println(cb2.getItemCount());
cb2.addItem("Rawdhah");
cb2.addItem("Abdahll");
} else if (cb1.getSelectedIndex() == 1) {
cb2.removeAllItems();
cb2.addItem("Siddiq");
cb2.addItem("Aljabryha");
} else {
cb2.removeAllItems();
cb2.addItem("Fintas");
cb2.addItem("Abdahll");
}
}
}
You could also make use of the actionCommand property, but the above is the simpler, immediate solution
I want a drop-down compobox where the selected element is one-line when its not selected, but when I choose from the drop-down each cell is taller and shows some extra information
This is achieved by the following code:
import java.awt.Component;
import javax.swing.DefaultComboBoxModel;
import javax.swing.DefaultListCellRenderer;
import javax.swing.JList;
public class ComboJFrame extends javax.swing.JFrame {
private boolean popup;
private javax.swing.JComboBox jComboBox1;
public ComboJFrame() {
initComponents();
}
private void initComponents() {
jComboBox1 = new javax.swing.JComboBox();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
getContentPane().setLayout(new java.awt.FlowLayout());
DefaultComboBoxModel model = new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3",
"Long Long Item 4" });
jComboBox1.setModel(model);
jComboBox1.setRenderer(new DefaultListCellRenderer() {
#Override
public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
System.out.println("rend = " + value);
// if popup is showing we need to make elements tall
if (popup) this.setText("<html>" + value.toString().replaceAll(" ", "<br/>\n"));
return this;
}
;
});
jComboBox1.addPopupMenuListener(new javax.swing.event.PopupMenuListener() {
public void popupMenuCanceled(javax.swing.event.PopupMenuEvent evt) {
popup = false;
System.out.println("popup = " + popup);
}
public void popupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent evt) {
popup = false;
System.out.println("popup = " + popup);
}
public void popupMenuWillBecomeVisible(javax.swing.event.PopupMenuEvent evt) {
popup = true;
jComboBox1.invalidate();
System.out.println("popup = " + popup);
}
});
getContentPane().add(jComboBox1);
pack();
model.setSelectedItem("Item 3"); // THIS GIVES THE PROBLEM
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new ComboJFrame().setVisible(true);
}
});
}
}
The problem is what if I programatically select an item, like
model.setSelectedItem("Item 3");
then the JCombobox gets the cell height wrong and displays
This is only happening on when selecting items programatically. If I select an item by manually clicking with the mouse and then opens the popup againd then it goes away.
Ive seen this on Ubuntu Linux 14.04 using Java 7 and Java 8.
I'd like to get it fixed, and to know whether Windows and Mac has the same problem.
Strange thing is, that if I add items to the model in a ways such that setSelectedItem is never called, like:
model.removeAllElements();
model.addElement("Item 3");
model.insertElementAt("Item 2",0);
model.insertElementAt("Item 1",0);
model.addElement("Long Item 4");
then the problem doesen't appear
Another workaround seems to be to select the item and then re-set the model:
model.setSelectedItem("Item 3");
jComboBox1.setModel(new DefaultComboBoxModel());
jComboBox1.setModel(model);
The above is test code, the real application is for Apertium machine translation, and the combobox looks like this:
I am tying to perform and action when an item in combo box are selected, but it performs an action no matter what item is selected.Can someone help me out please.
//number of players combo box
players = new JComboBox();
contentPane.add(players, BorderLayout.SOUTH);
players.addItem("1 Player");
players.addItem("2 Players");
players.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
makeFrame();
}
});
players.addItem("3 Players");
//end of combo box
In order to change behavior based on which item was selected, you will need to retrieve the selected value inside your ActionListener and change the behavior based on the selected value. You could use something like the following:
//number of players combo box
//notice that you have to declare players
//as final. If it is a member of the class,
//you can declare it final in the field
//declaration and initialize it in the
//constructor, or if local, just leave it
//as it is here. Unless using Java 8, then it
//doesn't need to be declared final
final JComboBox players = new JComboBox();
contentPane.add(players, BorderLayout.SOUTH);
players.addItem("1 Player");
//your combo box still needs to be final
final JComboBox players = new JComboBox();
contentPane.add(players, BorderLayout.SOUTH);
players.addItem("1 Player");
players.addItem("2 Players");
players.addItem("3 Players");
players.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String selectedValue = String.valueOf(players.getSelectedItem());
if (selectedValue != null && (selectedValue.equals("1 Player") || selectedValue.equals("2 Players"))) {
makeFrame();
}
else {
//do something else
}
}
});
//end of combo box
If you happen to know the index ahead of time (i.e., you statically initialize the list of options instead of dynamically generating the list), you could also just refer to .getSelectedIndex() to retrieve the index as follows:
//number of players combo box
//the combo box still needs to be final here
final JComboBox players = new JComboBox();
contentPane.add(players, BorderLayout.SOUTH);
players.addItem("1 Player");
//your combo box still needs to be final
final JComboBox players = new JComboBox();
contentPane.add(players, BorderLayout.SOUTH);
players.addItem("2 Players");
players.addItem("3 Players");
players.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
int myIndex = players.getSelectedIndex();
if (myIndex == 0 || myIndex == 1) {
makeFrame();
}
else {
//do something else
}
}
});
//end of combo box
I have a simple program , that asks for an ip address to connect to , a user id and a password. The IP address is selected through / entered into a combobox.
When the user has entered the address and moved onto another field for entering data , a validation routine is called and in case of an invalid address entered , the combobox background changes to red and a label containing an error message is shown.
The problem is that when the user returns back to the ip combo box , the background color remains red.
it does not change.
How do i code the combobox to overcome my problem ?
Try to use FocusListener on your JComboBox. With it you can manage background color when you enter to combobox and exit from it. Heres simple example:
import java.awt.BorderLayout;
public class Example extends JFrame {
private JComboBox<String> box;
public Example() {
init();
}
private void init() {
box = new JComboBox<String>(getObjects());
box.setBackground(Color.RED);
box.addFocusListener(getFocusListener());
JTextField f = new JTextField();
add(box,BorderLayout.SOUTH);
add(f,BorderLayout.NORTH);
pack();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
private FocusListener getFocusListener() {
return new FocusAdapter() {
#Override
public void focusGained(FocusEvent arg0) {
super.focusGained(arg0);
box.setBackground(Color.BLACK);
//validate();
}
#Override
public void focusLost(FocusEvent arg0) {
super.focusLost(arg0);
box.setBackground(Color.red);
//validate();
}
};
}
private String[] getObjects() {
return new String[]{"1","22","33"};
}
public static void main(String... s) {
Example p = new Example();
}
}
I need your suggestions and guidence on following task.
I have a frame which has two JComboBoxes supposed they are named combo1 and combo2, a JTable and other components.
At initial stage when frame is visible with above component. The combo1 combobox is filled with some values but no value is selected at initial stage, the combo2 combobox is disabled and the table is empty.
I have added an actionListener on combo1 as well as combo2. There are two types of values in combo1 suppose those values are type1 and type2.
Condition 1:
When we selects value type1 from Combo1 the actionListener method is called of combo1 which invokes a method which combo2 remains disabled and adds some rows to table related to selected value type1 from combo1.
Condition 2:
when we selects value type2 from combo1 the actionListener method is called of combo1 which invokes a method who makes combo2 filled with some values related to type2 and gets enabled but no value is selected from combo2 and table also should remain empty until we selects any value from combo2.
table at every addition of value to combo2 the action listener method of combo2 is gets fired. In actionListener method of combo2 which gets combo2 selected value but here there is no selected value of combo2 which leads to a NullPointerException.
So what should I do that the action listner method of combo2 will not be get executed after addition of an values to combo2.
You could remove the action listener before you add the new elements, and add it back once you're done . Swing is single threaded so there is no need to worry about other threads needing to fire the listener.
Your listener could probably also check if something is selected and take appropriate action if not. Better than getting a NPE.
What i do instead of adding and removing action listeners i have a boolean variable in my action listeners that is true if it has to allow the action through or false if it has to block it.
I then set it to false when i do some changes that will fire off the action listener
JComboBox test = new JComboBox();
test.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
if(testActionListenerActive)
{
//runn your stuff here
}
}
});
//then when i want to update something where i want to ignore all action evetns:
testActionListenerActive = false;
//do stuff here like add
SwingUtilities.invokeLater(() -> testActionListenerActive = false);
//and now it is back enabled again
//The reason behind the invoke later is so that if any event was popped onto the awt queue
//it will not be processed and only events that where inserted after the enable
//event will get processed.
try this:
indicatorComboBox = new JComboBox() {
/**
* Do not fire if set by program.
*/
protected void fireActionEvent() {
// if the mouse made the selection -> the comboBox has focus
if(this.hasFocus())
super.fireActionEvent();
}
};
although its late, a better alternative would be to disabled the combobox to be modified prior to being modified. by doing so, you prevent firing events of the modified combobox, when for example, you use methods likes removeAllItems() or addItem()
String orderByOptions[] = {"smallest","highest","longest"};
JComboBox<String> jcomboBox_orderByOption1 = new JComboBox<String(orderByOptions);
JComboBox<String> jcomboBox_orderByOption2 = new JComboBox<String(orderByOptions);
JComboBox<String> jcomboBox_orderByOption3 = new JComboBox<String(orderByOptions);
jcomboBox_orderByOption1.addItemListener(new ItemListener()
{
public void itemStateChanged(ItemEvent itemEvent)
{
int eventID = itemEvent.getStateChange();
if (eventID == ItemEvent.SELECTED)
{
Object selectedItem = jcomboBox_orderByOption1.getSelectedItem();
jcomboBox_orderByOption2.setEnabled(false);
jcomboBox_orderByOption2.removeAllItems();
for (String item: string_orderByOptions)
{
if (!item.equals(selectedItem))
{
jcomboBox_orderByOption2.addItem(item);
}
}
jcomboBox_orderByOption2.setEnabled(true);
}
}
});
jcomboBox_orderByOption2.addItemListener(new ItemListener()
{
public void itemStateChanged(ItemEvent itemEvent)
{
int eventID = itemEvent.getStateChange();
if (eventID == ItemEvent.SELECTED)
{
Object selectedItem1 = jcomboBox_orderByOption1.getSelectedItem();
Object selectedItem2 = jcomboBox_orderByOption2.getSelectedItem();
jcomboBox_orderByOption3.setEnabled(false);
jcomboBox_orderByOption3.removeAllItems();
for (String item: string_orderByOptions)
{
if (!item.equals(selectedItem1) && !item.equals(selectedItem2))
{
jcomboBox_orderByOption3.addItem(item);
}
}
jcomboBox_orderByOption3.setEnabled(true);
}
}
});
The cleaner way is to use lambda expressions like this:
do(comboBox, () -> comboBox.setSelectedItem("Item Name"));
For the above to work, you need the following method defined somewhere:
public static void do(final JComboBox<String> component, final Runnable f) {
final ActionListener[] actionListeners = component.getActionListeners();
for (final ActionListener listener : actionListeners)
component.removeActionListener(listener);
try {
f.run();
} finally {
for (final ActionListener listener : actionListeners)
component.addActionListener(listener);
}
}
This works:
/** Implements a Combo Box with special setters to set selected item or
* index without firing action listener. */
public class MyComboBox extends JComboBox {
/** Constructs a ComboBox for the given array of items. */
public MyComboBox(String[] items) {
super(items);
}
/** Flag indicating that item was set by program. */
private boolean isSetByProgram;
/** Do not fire if set by program. */
protected void fireActionEvent() {
if (isSetByProgram)
return;
super.fireActionEvent();
}
/** Sets selected Object item without firing Action Event. */
public void setSelection(Object item) {
isSetByProgram = true;
setSelectedItem(item);
isSetByProgram = false;
}
/** Sets selected index without firing Action Event. */
public void setSelection(int index) {
isSetByProgram = true;
setSelectedIndex(index);
isSetByProgram = false;
}
}
Note: You can't just override setSelectedItem(...) or setSelectedIndex(...) because these are also used internally when items are actually selected by user keyboard or mouse actions, when you do not want to inhibit firing the listeners.
To determine whether or not to perform various methods in actionListener interface methods (actionPerformed() blocks of code) use setActionCommand() on source components (combo1 or combo2).
For your example, before adding elements to combo2, call setActionCommand("doNothing") and guard your comboBoxActionPerformed() method.
Here's a compilable example that uses this principle to have one combo set another combo's selected index while also displaying a String in a JTextField. By using setActionCommand() and guarding the comboActionPerformed() block of code, the JTextField will cycle through each word in the wordBank. If the comboActionPerformed() method was not guarded or if the actionCommand String was not changed, 2 actionEvents will trigger and the textField will skip words.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
/** #author PianoKiddo */
public class CoolCombos extends JPanel {
JComboBox<String> candyCombo;
JComboBox<String> flavorCombo;
JTextField field;
String[] wordBank;
int i = 0;
CoolCombos() {
super();
initComponents();
addComponentsToPanel();
}
private void initComponents() {
initCombos();
initTextField();
}
private void initCombos() {
ActionListener comboListener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
comboActionPerformed(e);
}
};
String[] candyList = {"Sourpatch", "Skittles"};
String[] flavorList = {"Watermelon", "Original"};
candyCombo = new JComboBox<>(candyList);
candyCombo.addActionListener(comboListener);
flavorCombo = new JComboBox<>(flavorList);
flavorCombo.addActionListener(comboListener);
}
private void initTextField() {
wordBank = new String[]{"Which", "Do", "You", "Like", "Better?"};
field = new JTextField("xxxxx");
field.setEditable(false);
field.setText(wordBank[i]);
}
private void addComponentsToPanel() {
this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
this.add(candyCombo);
this.add(flavorCombo);
this.add(field);
}
public void comboActionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if (!command.equals("doNothing")) {
JComboBox combo = (JComboBox) e.getSource();
if (combo.equals(candyCombo)) {
setOtherComboIndex(candyCombo, flavorCombo); }
else {
setOtherComboIndex(flavorCombo, candyCombo); }
displayText(); //replace here for toDo() code
}
}
private void setOtherComboIndex(JComboBox combo, JComboBox otherCombo) {
String command = otherCombo.getActionCommand();
otherCombo.setActionCommand("doNothing"); //comment this line to skip words.
otherCombo.setSelectedIndex(combo.getSelectedIndex());
otherCombo.setActionCommand(command);
}
private void displayText() {
i++;
String word;
if (i > 4) { i = 0; }
word = wordBank[i];
field.setText(word);
this.repaint();
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("CoolCombos");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
JComponent newContentPane = new CoolCombos();
newContentPane.setOpaque(true); //content panes must be opaque
frame.setContentPane(newContentPane);
//Display the window.
frame.pack();
frame.setMinimumSize(frame.getSize());
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
I kind of went the stupid simple route with this issue for my program since I am new to programming.
I changed the action listeners to have a counter if statement:
if(stopActionlistenersFromFiringOnLoad != 0){//action performed ;}
Then at the end of the java program creation, I added 1 to the counter:
topActionlistenersFromFiringOnLoad += 1;
To avoid that addItem method fire events is better to use an DefaultComboBoxModel in the JComboBox to add data. Also, if you invoke a model.addElement(), an event is fired, so, you can add all the elements to the model and later use JComboBox.setModel(model). In this way, if you add elements to the model, events are not fired because you have not link the JComboBox with the model. Then, I show you an example.
private void rellenarArrendatarioComboBox(ArrayList<Arrendatario> arrendatarios) {
DefaultComboBoxModel model = new DefaultComboBoxModel();
model.addElement(new Arrendatario(" -- Seleccione un arrendatario --"));
for (Arrendatario arrendatario : arrendatarios) {
model.addElement(arrendatario);
}
ArrendatarioComboBox.setModel(model);
}
First, we create the model, add all elements to the model (events are not fired because you have not link the JComboBox with the model), we link the model with the JComboBox using ArrendatarioComboBox.setModel(model). After linking, events are fired.