selected item in combobox not printing out when selected - java

I'm doing this project and it has I'm trying to print out the selected item in the combo box but it's not working. Just wanting to know why it is not printing out properly. trying to print "eric white"
public void subList() {
//sets up sub list based on selection in managerbox
cboManager.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent e) {
if(e.getStateChange() == ItemEvent.SELECTED) {
Object selected = cboManager.getSelectedItem();
if (selected.equals("Eric White") ) {
System.out.println("eric white");
}
}
}
});
}

Check whether the item listed in combo box is exactly "Eric White", because equals will look for exact string including space and case sensitive.

I usually use ActionListener. Prepare for null value and case sensitivity.
public void subList() {
//sets up sub list based on selection in managerbox
cboManager.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Object selected = cboManager.getSelectedItem();
if (selected != null && selected.equalsIgnoreCase("Eric White") ) {
System.out.println("eric white");
}
}
});
}

Related

Is it possible to extract Strings out of ListSelectionEvents in java swing?

I am using JList of Strings in java swing. I want to have a ListSelectionListener which returns the String of the Listentry, that was selected by the user. But I can't reach the String itself. The only thing that I could find
private void registerListeners()
{
gui.getListMeasurements().addListSelectionListener(new ListSelectionListener()
{
#Override
public void valueChanged(ListSelectionEvent event)
{
System.out.println(event.getSource());
}
});
}
Outputs the following 4 times: javax.swing.JList[,0,0,240x340,alignmentX=0.0,alignmentY=0.0,border=,flags=50331944,maximumSize=,minimumSize=,preferredSize=,fixedCellHeight=-1,fixedCellWidth=-1,horizontalScrollIncrement=-1,selectionBackground=javax.swing.plaf.ColorUIResource[r=184,g=207,b=229],selectionForeground=sun.swing.PrintColorUIResource[r=51,g=51,b=51],visibleRowCount=8,layoutOrientation=0]
Nothing in this output refers to the String selected in the list. Neither can I find any useful method for the event.
Is it possible to extract Strings the way I described?
gui.getListMeasurements().addListSelectionListener(new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent e) {
if (e.getValueIsAdjusting()) {
return;
}
if (e.getSource() instanceof JList) {
JList list = (JList) e.getSource();
int index = list.getSelectedIndex();
Object element = list.getModel().getElementAt(index);
if (element instanceof String) {
System.out.println("Selected value at " + index + " = " + element);
}
}
}
});
Helpful links:
How to Use Lists
JavaDocs for JList
How to Write a List Selection Listener
JavaDocs for ListSelectionListener and ListSelectionEvent

Getting the id of selected item returns 0

I have two JComboBoxes where the other one dynamically changing the value based on user choices. I properly get the id of those selected item. But getting the first element of my JComboBox gives me a zero value where I wanted to get the id without firing the ItemListener.
ActionListener listener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if ("Add".equals(e.getActionCommand())) {
System.out.println("Position id is " + getPositionId());
}
}
}
ItemListener itemListener = new ItemListener() {
#Override
public void itemStateChanged(ItemEvent e) {
if (e.getSource() == department) {
Department item = (Department) department.getSelectedItem();
int departmentId = item.getId();
model.setDeptId(departmentId);
List<Position> list = model.getAllPositionId();
DefaultComboBoxModel positionModel = new DefaultComboBoxModel(list.toArray());
position.setModel(positionModel);
}
else if (e.getSource() == position) {
Position item = (Position) cbPosition.getSelectedItem();
int positionId = item.getId();
model.setPositionId(positionId);
}
}
}
Every time the user changed the selected value. DefaultComboBoxModel changed also its value with corresponding id. But getting it returns me 0.
I already found a solution. I just created a void method outside the ItemListener where it gets the first element.

How to close the drop down list of JCombobox when we click on custom?

I have a JCombobox in which when I select any one from drop down list of JCombobox ,the selected item is opening but when I click on "Custom" among one of the drop down list I have to open a daiolg ,here daiolg is opening but drop down list is not closing I want to hide the drop down when I click on Custom. here is my sample code....
private PropertyChangeSupport pcs;///here Iam using ActionListener and PopupMenuListener
public void actionPerformed(ActionEvent ae){
if(ae.getSource() instanceof ComboBox )
{
ComboBox comboBox = (ComboBox)ae.getSource();
Object selectedItem = comboBox.getSelectedItem();
if(selectedItem != null && (!selectedItem.equals("(Custom..)")))
{
pcs.firePropertyChange("ITEM_SELECTED",getCaption(),null);
}}}
public void popupMenuWillBecomeInvisible(PopupMenuEvent e)
{
ComboBox comboBox = (ComboBox)e.getSource();
Object repeatedSelectedItem = comboBox.getSelectedItem();
if(repeatedSelectedItem != null && repeatedSelectedItem.equals("(Custom..)"))
{
invokeCustomFilterDialog(repeatedSelectedItem, comboBox);
}}
private void invokeCustomFilterDialog(Object repeatedSelectedItem, ComboBox comboBox)
{
customFilterDialog.showDialog(); //here Iam opening dailog...
if(customFilterDialog.isCustomFilterAppliedFlag() == true)
{
pcs.firePropertyChange("ITEM_SELECTED",getCaption(),null);
}
else
{comboBox.setSelectedItem(lastSelectedItem);}}
public void popupMenuCanceled(PopupMenuEvent e)
{ }
public void popupMenuWillBecomeVisible(PopupMenuEvent e)
{
ComboBox comboBox = (ComboBox)e.getSource();
this.lastSelectedItem = comboBox.getSelectedItem();
}
combobox.getUI().setPopupVisible(combobox, false);
You can use SwingUtilities.invokeLater.
For example
public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
final JComboBox comboBox = (JComboBox) e.getSource();
final Object repeatedSelectedItem = comboBox.getSelectedItem();
if (repeatedSelectedItem != null
&& repeatedSelectedItem.equals("(Custom..)")) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
invokeCustomFilterDialog(repeatedSelectedItem, comboBox);
}
});
}
}

JFormattedTextfield.selectAll() does not work when formatting the text

I have a lot of different JFormattedTextFields with action and keylisteners. Every Field has a keylistener, so when I press enter I will focus the next JFormattedTextField. The Problem is, for some JFormattedTextFields my code is formatting the input and then sets the text new and for those selectAll() does not work.
JFormattedTextField a = new JFormattedTextField(someDouble);
JFormattedTextField b = new JFormattedTextField(someDouble2);
a.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
leasingfaktor1Field.selectAll();
if(...) {
//do something
a.setText(tausenderPunkt(someValue));
}
}
});
a.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == 10) {
b.requestFocusInWindow();
}
}
});
b.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
leasingfaktor1Field.selectAll();
if(...) {
//do something
b.setText(tausenderPunkt(someValue));
}
}
});
b.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == 10) {
c.requestFocusInWindow();
}
}
});
The function tausenderPunkt():
public String tausenderPunkt(double value) {
String s = String.format("%1$,.2f", value);
return s;
}
So when my cursor is in field a and i press enter the cursor goes to field b but does not select the text or values. When i do not use setText() i do not have the problem. Somebody has a solution?
Edit: For some JFormattedTextFields the solution was to add selectAll() to the keyAdapter, but not for all.
For example:
b.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == 10) {
c.requestFocusInWindow();
c.selectAll();
}
}
});
Edit2:
The problem seems to be when i create the JFormattedTextFields.
When i do not create them with a value in the constructor it works.
But i have to do.
Before moving to your next text field you should consider handling all the required conditions for the text field you are currently focused on and this would of course include the formatting of values or text supplied to that field. Once all the desired conditions are met then move on to the next text field.
In reality this can all be accomplished through the keyPressed event for your particular situation. There is no need for the actionPerformed event on any of your text fields, for example:
a.addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
checkConditions(a, b);
}
}
});
b.addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
checkConditions(b, c);
}
}
});
//---------- and so on -------------
Here is a simple method so as to eliminate the need for repetitious code:
private void checkConditions(JFormattedTextField fieldA, JFormattedTextField fieldB) {
// Make sure something is contained within fieldA and
// that it's actually numerical text.
if(!fieldA.getText().isEmpty() &&
fieldA.getText().matches("([-]?)\\d+([,]\\d+)?(([.]\\d+)?)")) {
// Convert the supplied text to Double and
// ensure the desired numerical formating.
String res = (String)tausenderPunkt(Double.parseDouble(fieldA.getText().replace(",","")));
fieldA.setText(res);
// Set Focus to our next text fieldB.
fieldB.requestFocusInWindow();
// Highlight the contents (if any) within the
// next text fieldB.
fieldB.selectAll();
}
// If fieldA is empty or fieldA does not contain
// numerical text then inform User and re-highlight
// the entry in fieldA.
else {
JOptionPane.showMessageDialog (null, "Please Enter Numerical Values Only!",
"Incorrect Entry", JOptionPane.WARNING_MESSAGE);
fieldA.selectAll();
}
}
If you want the contents of your first text field to be highlighted as soon as focus has been established upon it (tabbed to or clicked on) then consider using a FocusGained event for that component or any other component where you desire the same effect.
I Hope this has helped in some way.
EDITED!
So as to handle OP's particular situation.
String str=this.getText();
this.setText(str);
this.selectAll();
You can get the focus owner and remove the focusable feature:
Component focusOwner = FocusManager.getCurrentManager().getFocusOwner();
When you get the component, put this sentence after load it:
component.setFocusable(false);

Strange blinking of cell on selection with custom Cell Editor

I am new to working with JTables and having trouble with getting my custom JTable editor to work properly.
I have a number of custom panels with lists and buttons. To renderder them in a cell I am using a custom PanelCellRenderer that has various constructors for each type of the panel.
To make the buttons clickable I have created this simple PanelCellEditor that extends DefaultCellEditor. To access the data stored within cells at the time of editting I pass the reference to the PanelCellRenderer.
The problem I am having is that when I select the cell (by clicking at it), from displaying the list with the button, the cell selected becomes completely blank. When the cell gets deselected the list with data and the button reappear again. Any advice on this will be helpful. Thanks.
public class PanelCellEditor extends DefaultCellEditor {
private PanelCellRenderer pcr;
private Object value;
public PanelCellEditor(final PanelCellRenderer pcr) {
super(new JCheckBox());
this.pcr = pcr;
this.pcr.setOpaque(true);
if (pcr.firstPanel != null) {
pcr.firstPanel.Button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//do something
fireEditingStopped();
}
});
pcr.firstPanel.List.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
String value = (String) ((javax.swing.JList) e.getSource()).getSelectedValue();
//do something
fireEditingStopped();
}
});
}
else if (pcr.secondPanel != null) {
pcr.secondPanel.Button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//do something
fireEditingStopped();
}
});
pcr.secondPanel.List.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
String value = (String) ((javax.swing.JList) e.getSource()).getSelectedValue();
//do something
fireEditingStopped();
}
});
}
}
public Component getTableCellEditorComponent(JTable table, Object value,
boolean isSelected, int row, int column) {
//// if I comment this whole bit ////
if (isSelected) {
pcr.setForeground(table.getSelectionForeground());
pcr.setBackground(table.getSelectionBackground());
} else {
pcr.setForeground(table.getForeground());
pcr.setBackground(table.getBackground());
}
if (pcr.firstPanel != null)
pcr.firstPanel.list.setListData((String[])value);
else if (pcr.secondPanel != null) {
pcr.secondPanel.list.setListData((String[])value);
}
//////// nothing changes /////////
this.value = value;
return pcr;
}
public Object getCellEditorValue() {
return value;
}
public boolean stopCellEditing() {
return super.stopCellEditing();
}
protected void fireEditingStopped() {
super.fireEditingStopped();
}
}
you could trace the JTable.getTableCellEditor into your objects.
Have you actually registered your editor with the value it should edit with the Jtable?

Categories