How to make part of a JTextField uneditable - java

I wanted to develop a console-like interface, similar to IDLE. That involved determining how to prevent a certain part of the text in a JTextField from being edited. For example:
>>> help
Where the ">>> " is uneditable. The caret must never move behind a certain position, and the text behind that position cannot be edited in any way.

I looked at NavigationFilter, but it doesn't seem to prevent keyboard driven manipulation of the caret.
This shows how to do it with a NavigationFilter:
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;
public class NavigationFilterPrefixWithBackspace extends NavigationFilter
{
private int prefixLength;
private Action deletePrevious;
public NavigationFilterPrefixWithBackspace(int prefixLength, JTextComponent component)
{
this.prefixLength = prefixLength;
deletePrevious = component.getActionMap().get("delete-previous");
component.getActionMap().put("delete-previous", new BackspaceAction());
component.setCaretPosition(prefixLength);
}
#Override
public void setDot(NavigationFilter.FilterBypass fb, int dot, Position.Bias bias)
{
fb.setDot(Math.max(dot, prefixLength), bias);
}
#Override
public void moveDot(NavigationFilter.FilterBypass fb, int dot, Position.Bias bias)
{
fb.moveDot(Math.max(dot, prefixLength), bias);
}
class BackspaceAction extends AbstractAction
{
#Override
public void actionPerformed(ActionEvent e)
{
JTextComponent component = (JTextComponent)e.getSource();
if (component.getCaretPosition() > prefixLength)
{
deletePrevious.actionPerformed( null );
}
}
}
private static void createAndShowUI()
{
JTextField textField = new JTextField("Prefix_", 20);
textField.setNavigationFilter( new NavigationFilterPrefixWithBackspace(7, textField) );
JFrame frame = new JFrame("Navigation Filter Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(textField);
frame.pack();
frame.setLocationRelativeTo( null );
frame.setVisible(true);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}

Spent a little while figuring this out, so I thought I would share my solution for anyone else with the same dilemma. I don't know if it's optimal, but it does seem to work.
It prevents the user from using backspace behind the postion n. It also moves the caret back to n for any other events, such as (illegally) changing the caret position with the arrow keys or mouse. Finally, it resets the text and caret position after a entry is processed.
EDIT: While I'm leaving this answer here for posterity, see the accepted answer for the best way to solve this problem.
JTextField in = new JTextField();
final String protectMe = ">>> "; //protect this text
final int n = protectMe.length();
in.setText(protectMe);
in.setCaretPosition(n);
in.addCaretListener(new CaretListener()
{
#Override
public void caretUpdate(CaretEvent e)
{
if (e.getDot() < n)
{
if (!(in.getText().length() < n))
in.getCaret().setDot(n);
}
}
});
in.addKeyListener(new KeyListener()
{
#Override
public void keyPressed(KeyEvent arg0)
{
if (in.getCaret().getDot() <= n)
{
in.setText(protectMe + in.getText().substring(n));
arg0.consume();
}
}
#Override
public void keyReleased(KeyEvent arg0){}
#Override
public void keyTyped(KeyEvent arg0){}
});
in.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent evt)
{
String input = in.getText().substring(n).trim();
//do something
in.setText(protectMe);
in.setCaretPosition(n);
}
});
As usual, let me know if there's anything I missed!

Related

How to change the background color of a JSpinner dependent on the current edited content of the field?

I have a GUI with a JSpinner using a SpinnerNumberModel using double values.
As soon as I change the content of the Editor of the JSpinner, I want the background to change to yellow (to show that the currently displayed value is not the one "saved" in the JSpinner respectively its Model.
If that content is not valid (e.g. out of the allowed range specified by my SpinnerNumberModel or a text as "abc") the background should change to red.
I tried to achieve what I want with a FocusListener already but yet have not been successful, also I am not sure if It could work anyway, as I need to check the content somewhere between focussing and defocussing.
I checked Tutorials for all Listeners that exist for Swing components, but could not find a right one that suits the job. (here I informed myself)
I am new to the concept of Listeners and would really appreciate any help that gets me closer to solving the problem but also helps generally understanding Listeners and how to use them in this context better!
My really basic code example with the mentioned poor attempt using a focus listener:
public class test implements FocusListener{
JFrame frame;
SpinnerNumberModel model;
JSpinner spinner;
JComponent comp;
JFormattedTextField field;
public test() {
JFrame frame = new JFrame("frame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS));
model = new SpinnerNumberModel(0., 0., 100., 0.1);
spinner = new JSpinner(model);
comp = spinner.getEditor();
field = (JFormattedTextField) comp.getComponent(0);
field.addFocusListener(this);
frame.getContentPane().add(spinner);
frame.getContentPane().add(new JButton("defocus spinner")); //to have something to defocus when testing :)
frame.pack();
frame.setVisible(true);
}
#Override
public void focusGained(FocusEvent e) {
// TODO Auto-generated method stub
//when the values of the field and the spinner don't match, the field should get yellow
if(!field.getValue().equals(spinner.getModel().getValue())) {
field.setBackground(Color.YELLOW);
}
}
#Override
public void focusLost(FocusEvent e) {
// TODO Auto-generated method stub
//if they match again, reset to white
if(!field.getValue().equals(spinner.getModel().getValue())) {
field.setBackground(Color.RED);
}
}
}
A JSpinner uses a text field as the editor for the spinner
So, you can add a DocumentListener to the Document of the text field that is used as the editor.
Something like:
JTextField textField = ((JSpinner.DefaultEditor)spinner.getEditor()).getTextField());
textField.getDocument.addDocumentListener(...);
Then when text is added/removed a DocumentEvent will be generated and you can do your error checking. Read the section from the Swing tutorial on Listener For Changes on a Document for more information and working examples.
You can use CaretListener , here is a start:
import java.awt.Color;
import java.awt.Component;
import javax.swing.BoxLayout;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JSpinner;
import javax.swing.SpinnerNumberModel;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
public class SpinerTest{
JSpinner spinner;
public SpinerTest() {
JFrame frame = new JFrame("frame");
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);
frame.setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS));
SpinnerNumberModel model = new SpinnerNumberModel(0., 0., 100., 0.1);
spinner = new JSpinner(model);
setCaretListener();
frame.getContentPane().add(spinner);
frame.pack();
frame.setVisible(true);
}
private void setCaretListener() {
for(Component c : spinner.getEditor().getComponents()) {
JFormattedTextField field =(JFormattedTextField) c;
field.addCaretListener(new CaretListener(){
#Override
public void caretUpdate(CaretEvent ce) {
if (field.isEditValid()) {
//add aditional test as needed
System.out.println("valid Edit Entered " + field.getText());
field.setBackground(Color.WHITE);
}
else {
System.out.println("Invalid Edit Entered" + field.getText());
field.setBackground(Color.PINK);
}
}
});
}
}
public static void main(String[] args) {
new SpinerTest();
}
}
I was able to fulfill the task with a combination of a KeyListener, a DocumentListener and a FocusListener. The solution might not be the easiest, but finally I coded sth. that works. Comments in the file appended should explain how I dealt with the problem.
I expanded the original task with a CommaReplacingNumericDocumentFilter expands DocumentFilter class that was not written by me, I got the code from my professor and edited it to my needs only. Now only digits, minus and e, E are accepted as entries in the JSpinner.
Commas are replaced with dots also.
Code:
import java.awt.*;
import java.awt.event.*;
import java.util.Locale;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
public class test implements DocumentListener, ChangeListener, KeyListener{
boolean keyPressed;
JFrame frame;
SpinnerNumberModel model;
JSpinner spinner;
JComponent comp;
JFormattedTextField field;
public test() {
JFrame frame = new JFrame("frame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS));
model = new SpinnerNumberModel(0., 0., 100000., .1);
spinner = new JSpinner(model);
//disable grouping for spinner
JSpinner.NumberEditor editor = new JSpinner.NumberEditor(spinner);
editor.getFormat().setGroupingUsed(false);
spinner.setEditor(editor);
comp = spinner.getEditor();
field = (JFormattedTextField) comp.getComponent(0);
field.getDocument().addDocumentListener(this);
field.addKeyListener(this);
spinner.addChangeListener(this);
frame.getContentPane().add(spinner);
frame.pack();
frame.setVisible(true);
}
#Override
public void insertUpdate(DocumentEvent e) {
DocumentEventHandler(e);
}
#Override
public void removeUpdate(DocumentEvent e) {
DocumentEventHandler(e);
}
#Override
public void changedUpdate(DocumentEvent e) {
DocumentEventHandler(e);
}
public static boolean isNumeric(String str)
{
try
{
double d = Double.parseDouble(str);
}
catch(NumberFormatException nfe)
{
return false;
}
return true;
}
public static void main(String[] args) {
//to get the right format for double precision numbers
Locale.setDefault(Locale.US);
test test = new test();
}
#Override
public void stateChanged(ChangeEvent e) {
System.out.println("valuechanged: " + spinner.getValue().toString());
if(keyPressed) {
field.setBackground(Color.WHITE);
}
keyPressed = false;
}
public void DocumentEventHandler(DocumentEvent e) {
//as soon as update is inserted, set background to yellow
if (keyPressed) {
field.setBackground(Color.YELLOW);
//check if input is numeric and in bounds
String text = field.getText();
if (isNumeric(text)) {
double value = Double.parseDouble(text);
if (value < (Double)model.getMinimum() || value > (Double)model.getMaximum()) {
field.setBackground(Color.RED);
}
}
else { //set background to red
field.setBackground(Color.RED);
}
}
keyPressed = false;
//System.out.println(e.toString());
//System.out.println("Text: " + field.getText());
}
#Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
#Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
/** If not done yet, replaces the DocumentFilter with one replacing commas by decimal points.
* This can't be done at the very beginning because the DocumentFilter would be changed to a
* javax.swing.text.DefaultFormatter$DefaultDocumentFilter when setting up the JSpinner GUI. */
public void keyPressed(KeyEvent e) {
PlainDocument document = (PlainDocument)(field.getDocument());
if(!(document.getDocumentFilter() instanceof CommaReplacingNumericDocumentFilter))
document.setDocumentFilter(new CommaReplacingNumericDocumentFilter());
/*Tell the other handlers that a key has been pressed and the change in the document does
* not come from using the JSpinner buttons or the MouseWheel.
*/
keyPressed = true;
}
}
/** A javax.swing.text.DocumentFilter that replaces commas to decimal points
* and ignores non-numeric characters except 'e' and 'E'. This is called before
* modi */
class CommaReplacingNumericDocumentFilter extends DocumentFilter {
#Override
public void insertString(FilterBypass fb, int offset, String text, AttributeSet attr)
throws BadLocationException {
text = filter(text);
if (text.length() > 0)
super.insertString(fb, offset, text, attr);
}
#Override
public void replace(FilterBypass fb, int offset, int length, String text,
AttributeSet attrs) throws BadLocationException {
text = filter(text);
if (text.length() > 0)
super.replace(fb, offset, length, text, attrs);
}
String filter(String text) {
return text.replace(',', '.').replaceAll("[^0-9eE.-]","");
}
}

How to make a String not-deletable in JTextarea?

Basically, I have a dropdown menu containing templates. For example:
apple( )
banana( )
Once one of them is selected, it pastes onto a JTextArea. My problem is if "apple( )" is selected, I want "apple" and the two brackets non-deletable in the TextArea, and user can enter anything inside the brackets.
Can anyone give me any direction/ideas here? I have been searching on the internet and found very little about this.
Check out the Proctected Text Component. It allows you to mark individual pieces of text as protected so that it can't be changed or deleted.
It uses a DocumentFilter as well as a NavigationFilter.
For a simpler solution you might be able to just use a NavigationFilter. The example below shows how you can prevent the selection of text at the beginning of the Document. You should be able to customize it to also prevent selection of text at the end of the document as well.
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;
public class NavigationFilterPrefixWithBackspace extends NavigationFilter
{
private int prefixLength;
private Action deletePrevious;
public NavigationFilterPrefixWithBackspace(int prefixLength, JTextComponent component)
{
this.prefixLength = prefixLength;
deletePrevious = component.getActionMap().get("delete-previous");
component.getActionMap().put("delete-previous", new BackspaceAction());
component.setCaretPosition(prefixLength);
}
#Override
public void setDot(NavigationFilter.FilterBypass fb, int dot, Position.Bias bias)
{
fb.setDot(Math.max(dot, prefixLength), bias);
}
#Override
public void moveDot(NavigationFilter.FilterBypass fb, int dot, Position.Bias bias)
{
fb.moveDot(Math.max(dot, prefixLength), bias);
}
class BackspaceAction extends AbstractAction
{
#Override
public void actionPerformed(ActionEvent e)
{
JTextComponent component = (JTextComponent)e.getSource();
if (component.getCaretPosition() > prefixLength)
{
deletePrevious.actionPerformed( null );
}
}
}
private static void createAndShowUI()
{
JTextField textField = new JTextField("Prefix_", 20);
textField.setNavigationFilter( new NavigationFilterPrefixWithBackspace(7, textField) );
JFrame frame = new JFrame("Navigation Filter Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(textField);
frame.pack();
frame.setLocationRelativeTo( null );
frame.setVisible(true);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}
You'll have to do this yourself. I'd suggest you to make an event handler that fires every time the text changes (Click here to find out how). And inside that handler check if the JTextArea still starts with "apple(" and ends with ")".

setEnabled(true) when radioButton.isSelected()

as I said in other posts I'm new in Java and I'm having some dumb problems, here's the deal:
I have a radioButton (radioStock) and a textField (stockField). I want stockField to be setEnabled(false) by default, no problem with that, and whenever the radioStock is checked, set the stockField enabled on true. I wrote this code, but it doesn't work.
if (radioStock.isSelected()) {
stockField.setEnabled(true);
}else{
stockField.setEnabled(false);
}
That code needs to be in a listener that is attached to the JRadioButton such as an ActionListener or ItemListener. And you don't even need the if blocks since all you'd need is one line of code inside of the listener:
radioStock.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent itemEvent) {
stockField.setEnabled(itemEvent.getStateChange() == ItemEvent.SELECTED);
}
});
For more on use of JRadioButtons, please check out the tutorial: button tutorial.
Edit my SSCCE
import java.awt.event.*;
import javax.swing.*;
public class ItemListenereg {
private static void createAndShowGui() {
final JRadioButton radioStock = new JRadioButton("Stock", true);
final JTextField stockField = new JTextField(10);
JPanel panel = new JPanel();
panel.add(radioStock);
panel.add(stockField);
radioStock.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent itemEvent) {
stockField.setEnabled(itemEvent.getStateChange() == ItemEvent.SELECTED);
}
});
JOptionPane.showMessageDialog(null, panel);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
This should work
radioStock.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
if(radioStock == e.getSource())
{
stockField.setEnabled(radioStock.isSelected());
}
}
});

Simultaneously update text area while typing in text field

I want to update my text area along with typing in the text field but i get a delay of 1 keystroke while typing i.e when i press a key the previous key is displayed.Here is my snippet
private void jTextField1KeyTyped(java.awt.event.KeyEvent evt)
{
String a = jTextField1.getText();
jTextArea1.setText(a);
}
I would not recommend using KeyListeners
Simply add a DocumentListener to your JTextField via:
textField.getDocument().addDocumentListener(new DocumentListener() {
#Override
public void insertUpdate(DocumentEvent de) {
}
#Override
public void removeUpdate(DocumentEvent de) {
}
#Override
public void changedUpdate(DocumentEvent de) {
}
});
Inside each of the methods ( insertUpdate,removeUpdate and changedUpdate) simply put in a call to set the text of your JTextArea via setText():
textArea.setText(textField.getText());
Here is an example I made:
import java.awt.BorderLayout;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
public class Test {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Test().createAndShowUI();
}
});
}
private void createAndShowUI() {
final JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
initComponents(frame);
frame.setResizable(false);
frame.pack();
frame.setVisible(true);
}
private void initComponents(JFrame frame) {
final JTextField jtf = new JTextField(20);
final JTextArea ta = new JTextArea(20,20);
ta.setEditable(false);
jtf.getDocument().addDocumentListener(new DocumentListener() {
#Override
public void insertUpdate(DocumentEvent de) {
ta.setText(jtf.getText());
}
#Override
public void removeUpdate(DocumentEvent de) {
ta.setText(jtf.getText());
}
#Override
public void changedUpdate(DocumentEvent de) {
//Plain text components don't fire these events.
}
});
frame.getContentPane().add(jtf, BorderLayout.WEST);
frame.getContentPane().add(ta, BorderLayout.EAST);
}
}
You should do that under the keyReleased event instead of the keyTyped and it will work as you need.
You need to wait till the event on your TextField is processed before updating the TextArea. Your code update the TextArea before the TextField is done processing the new typed character. Hence the text set in the TextArea is one keystroke behind.
You could try using recursion by referencing the method inside the method (avoid loops though).

How to set selected index JComboBox by value

I want to set the selected index in a JComboBox by the value not the index. How to do that? Example
public class ComboItem {
private String value;
private String label;
public ComboItem(String value, String label) {
this.value = value;
this.label = label;
}
public String getValue() {
return this.value;
}
public String getLabel() {
return this.label;
}
#Override
public String toString() {
return label;
}
}
JComboBox test = new JComboBox();
test.addItem(new ComboItem(0, "orange"));
test.addItem(new ComboItem(1, "pear"));
test.addItem(new ComboItem(2, "apple"));
test.addItem(new ComboItem(3, "banana"));
test.setSelectedItem("banana");
Ok, I have modified my question a bit. I forgot that i have a custom item inside my JComboBox that makes it a bit more difficult. i cant do setSelectedItem as i have a ComboItem inside each item. So still, how do i get this done?
setSelectedItem("banana"). You could have found it yourself by just reading the javadoc.
Edit: since you changed the question, I'll change my answer.
If you want to select the item having the "banana" label, then you have two solutions:
Iterate through the items to find the one (or the index of the one) which has the given label, and then call setSelectedItem(theFoundItem) (or setSelectedIndex(theFoundIndex))
Override equals and hashCode in ComboItem so that two ComboItem instances having the same name are equal, and simply use setSelectedItem(new ComboItem(anyNumber, "banana"));
You should use model
comboBox.getModel().setSelectedItem(object);
public static void setSelectedValue(JComboBox comboBox, int value)
{
ComboItem item;
for (int i = 0; i < comboBox.getItemCount(); i++)
{
item = (ComboItem)comboBox.getItemAt(i);
if (item.getValue().equalsIgnoreCase(value))
{
comboBox.setSelectedIndex(i);
break;
}
}
}
Hope this help :)
Why not take a collection, likely a Map such as a HashMap, and use it as the nucleus of your own combo box model class that implements the ComboBoxModel interface? Then you could access your combo box's items easily via their key Strings rather than ints.
For instance...
import java.util.HashMap;
import java.util.Map;
import javax.swing.ComboBoxModel;
import javax.swing.event.ListDataListener;
public class MyComboModel<K, V> implements ComboBoxModel {
private Map<K, V> nucleus = new HashMap<K, V>();
// ... any constructors that you want would go here
public void put(K key, V value) {
nucleus.put(key, value);
}
public V get(K key) {
return nucleus.get(key);
}
#Override
public void addListDataListener(ListDataListener arg0) {
// TODO Auto-generated method stub
}
// ... plus all the other methods required by the interface
}
for example
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
public class ComboboxExample {
private JFrame frame = new JFrame("Test");
private JComboBox comboBox = new JComboBox();
public ComboboxExample() {
createGui();
}
private void createGui() {
comboBox.addItem("One");
comboBox.addItem("Two");
comboBox.addItem("Three");
JButton button = new JButton("Show Selected");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(frame, "Selected item: " + comboBox.getSelectedItem());
javax.swing.SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
comboBox.requestFocus();
comboBox.requestFocusInWindow();
}
});
}
});
JButton button1 = new JButton("Append Items");
button1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
appendCbItem();
}
});
JButton button2 = new JButton("Reduce Items");
button2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
reduceCbItem();
}
});
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridLayout(4, 1));
frame.add(comboBox);
frame.add(button);
frame.add(button1);
frame.add(button2);
frame.setLocation(200, 200);
frame.pack();
frame.setVisible(true);
selectFirstItem();
}
public void appendCbItem() {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
comboBox.addItem("Four");
comboBox.addItem("Five");
comboBox.addItem("Six");
comboBox.setSelectedItem("Six");
requestCbFocus();
}
});
}
public void reduceCbItem() {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
comboBox.removeItem("Four");
comboBox.removeItem("Five");
comboBox.removeItem("Six");
selectFirstItem();
}
});
}
public void selectFirstItem() {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
comboBox.setSelectedIndex(0);
requestCbFocus();
}
});
}
public void requestCbFocus() {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
comboBox.requestFocus();
comboBox.requestFocusInWindow();
}
});
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
ComboboxExample comboboxExample = new ComboboxExample();
}
});
}
}
http://docs.oracle.com/javase/6/docs/api/javax/swing/JComboBox.html#setSelectedItem(java.lang.Object)
test.setSelectedItem("banana");
There are some caveats or potentially unexpected behavior as explained in the javadoc. Make sure to read that.
The right way to set an item selected when the combobox is populated by some class' constructor (as #milosz posted):
combobox.getModel().setSelectedItem(new ClassName(parameter1, parameter2));
In your case the code would be:
test.getModel().setSelectedItem(new ComboItem(3, "banana"));
Just call comboBox.updateUI() after doing comboBox.setSelectedItem or comboBox.setSelectedIndex or comboModel.setSelectedItem
public boolean preencherjTextCombox (){
int x = Integer.parseInt(TableModelo.getModel().getValueAt(TableModelo.getSelectedRow(),0).toString());
modeloobj = modelosDAO.pesquisar(x);
Combmarcass.getModel().setSelectedItem(modeloobj.getMarca());
txtCodigo.setText(String.valueOf(modeloobj.getCodigo()));
txtDescricao.setText(String.valueOf(modeloobj.getDescricao()));
txtPotencia.setText(String.valueOf(modeloobj.getPotencia()));
return true;
}
In my case build class Item(key, value) as item of combobox
SanPhamDTO currentProd = prodDao.getDetailById(id);
Item item = new Item(currentProd.getCategory().getId(),
currentProd.getCategory().getName());
cbdanhmuc.getModel().setSelectedItem(item)

Categories