I want to make a JComboBox in which a particular item text should change and becomes editable on selection.For example if JComboBox has two items "ONE","TWO" in it's list then on Selection of "TWO".
I have wrote a sample program in which either i can make field editable or can change the Text but not both.So someone please suggest how to make selective item editable and changed text as well
Object[] items = new Object[]{"One","Two"};
DefaultComboBoxModel dcbm = new DefaultComboBoxModel(items);
final JComboBox comboBox = new JComboBox(dcbm);
comboBox.setPreferredSize(new Dimension(200, 20));
comboBox.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent e) {
Object selectedItem = comboBox.getSelectedItem();
boolean editable = selectedItem instanceof String && ((String)selectedItem).equals("Two");
comboBox.setEditable(editable);
//comboBox.setSelectedItem("text has changed");
}
});
Something like...
String[] data = {"One", "Two"};
JComboBox<String> cb = new JComboBox<>(data);
add(cb);
cb.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
cb.setEditable(cb.getSelectedIndex() != 0);
}
});
will basically do it, but what it won't do, is update the value of the model, just so you know ;)
If you want to make the editor "blank" when the combobox becomes editable, you could add...
if (cb.isEditable() && cb.getSelectedIndex() != -1) {
cb.setSelectedItem("");
}
to the ActionListener
So I'm not the best with jComboBox off the top of my head so this may not help but I would assume it uses an array to set the strings for the objects in the combo box along the lines of
(new String[] {"ONE","TWO"});
and with my understanding of arrays you could do something like
comboBox.addMouseListener(new MouseAdapter(){
public void ActionPerformed(MouseEvent click){
optionTwoClicked(click);
}
}
and then add the handler with something like
private void optionTwoClicked(MouseEvent click){
if (click.getSelectedItem()=String[2]){
String onTwo = JOptionPane.showInputDialog(null,"Enter your message","Messages",2);
textItem.setText()="onTwo";
}else{ //do something here?
}
}
Like I said before, not absolutely familiar with jComboBox, but,
Hope that helps!
Related
I am making a simple sudoku and when I want to start a new game, I reload the panel. I first remove it and then add it to the frame. The problem is that I can choose the difficulty for new game, but it always selects the first "Easy" dificulty, not selected. So if I change it in JComboBox to "medium", when page is reloaded it will load the game with "Easy", not "medium".
What should I do so my refreshed panel will accept changed difficulty?
Here are methods that are used for this in my program:
JComboBox difficulty = new JComboBox();
DefaultComboBoxModel difficultyModel = new DefaultComboBoxModel();
difficultyModel.addElement("Easy");
difficultyModel.addElement("Medium");
difficultyModel.addElement("Hard");
difficulty.setModel(tezavnostModel);
difficulty.setSelectedIndex(0);
difficulty.setPreferredSize(new Dimension(100, 25));
newGame.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mainFrame.reloadSudokuBoard();
sudokuBoard.pickDifficulty(getDifficulty()));
}
});
public String getDifficulty() {
return (String)difficulty.getSelectedItem();
}
public void board(int[][] numbers, int zeros) {
int numberZeros = setDifficulty(sudokuForm.getDifficulty());
int[][] boardNumbers = gameNumbers();
public void reloadSudokuBoard() {
String newDifficulty = (sudokuForm.getDifficulty());
remove(sudokuBoard);
sudokuBoard.board(sudokuBoard.gameNumbers(), sudokuBoard.setDifficulty(newDifficulty ));
add(sudokuBoard, BorderLayout.WEST);
SwingUtilities.updateComponentTreeUI(sudokuBoard);
}
Hope this helps.
public void reloadSudokuBoard() {
int index = difficulty.getSelectedIndex();
String newDifficulty = (sudokuForm.getDifficulty());
remove(sudokuBoard);
sudokuBoard.board(sudokuBoard.gameNumbers(), sudokuBoard.setDifficulty(newDifficulty ));
add(sudokuBoard, BorderLayout.WEST);
SwingUtilities.updateComponentTreeUI(sudokuBoard);
difficulty.setSelectedIndex(index);
}
Before removing components, you can use the getSelectedIndex to get the index that was selected. After the element have been added, the setSelectedIndex will fix it
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);
}
});
}
}
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 am new to Java and Swing and am following zetcode tutorial. I want to add multiple JComboBoxes and store the index selected for each one of those. index1 should hold selected index from 1st instance of JComboBox and index2 should hold selected index from 2nd instance of JComboBox. For one JComboBox it can be done like this:
public ComboBox() {
setLayout(new BoxLayout(getContentPane(),
BoxLayout.Y_AXIS));
add(Box.createRigidArea(new Dimension(0, 35)));
combobox = new JComboBox(authors);
combobox.addItemListener(this);
add(combobox);
}
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
JComboBox combo = (JComboBox) e.getSource();
int index = combo.getSelectedIndex();
display.setIcon(new ImageIcon(
ClassLoader.getSystemResource(images[index])));
}
}
So if I could write the name of itemlistener that should be called for each JComboBox and then instead of writing combobox.addItemListener(this), I could write combobox.addItemListener(itemListener1). How do I do this?
try doing like this
combobox1.addItemListener(this);
combobox2.addItemListener(this);
..
comboboxn.addItemListener(this);
public void actionPerformed(ActionEvent e) {
if(e.getSource().equals(comboBox1))
{
\\do something
}
else if(e.getSource().equals(comboBox2))
{
\\do something
}
..
else if(e.getSource().equals(comboBoxn))
{
\\do something
}
Use inner or anonymous classes, it helps to avoid 'if - else' statements.
Exemple! of anonymous class
I have a number of checkboxes in my Swing Project. For each checkbox select/deselect a particular query is to be executed. I know one way of getting the source of checkbox is
public void itemStateChanged(ItemEvent e) {
if(e.getSource=="checkbox object")
{
some code goes here;
}
}
If i have small number of checkboxes than this solution is best but if i have many checkboxes then i have to write lengthy code. Is there a way to find the object of checkbox that causes the event in a single command?
You can get selected checkbox by like this
JCheckBox checkBox1 = new JCheckBox("Check1");
JCheckBox checkBox2 = new JCheckBox("Check2");
checkBox1.setName("Check1");
checkBox2.setName("Check2");
ItemListener listener = new ItemListener() {
#Override
public void itemStateChanged(ItemEvent e) {
JCheckBox check = (JCheckBox)e.getSource();
String name = check.getName();
System.out.println(name);
}
};
checkBox1.addItemListener(listener);
checkBox2.addItemListener(listener);
If you handle checks in some verry uniform way, it may help to put JChekBoxes into HashMap, mapping them into some structure (maybe data source or some processing object) that helps to process the event easier. Amount of code can be further reduced by having a method that creates, adds and registers a checkbox. The general idea would be along the lines
HashMap<JCheckBox, String> urls = new HashMap<JCheckBox, String>();
// Here I use String but can be any complex data structure.
ActionListener listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
String url = urls.get(e.getSource());
// Work with the selected URL now
}
};
void buildCheckBoxes() {
register("http://wikipedia.org");
register("http://stackoverflow.com");
// and 101 others, or load the list from the file.
}
void register(String url) {
JCheckBox box = new JCheckBox("Use "+url);
urls.put(box, url);
box.addActionListener(listener);
// One listener for all, defined above
myPanel.add(box);
// Some panel probably with GridLayout
}
From the other side, if your actions are very different, it may also be better to have a separate listener (probably inner or anonymous class) for each different action:
JCheckBox boxA = new JCheckBox("A");
JCheckBox boxB = new JCheckBox("B");
boxA.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Only code for boxA
}
});
boxB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Only code for boxB
}
});
As soon as there is more code in the listener, you should move it into a method on you main class.
If you want to know which component (either CheckBox or any other Component) has generated an event in java, you can assign name to that component using "setName(name)" method.
// For CheckBox
JCheckBox checkBox1 = new JCheckBox();
checkBox1.setName("CheckBox1");
// Any other Component
JButton button1 = new JButton();
button1.setName("Button1");
Now in listener class you can obtain source object who has generated current event.
// CheckBox Listener
public void itemStateChanged(ItemEvent e)
{
JCheckBox source = (JCheckBox)e.getSource();
if(source.getName().equals("CheckBox1"))
{
//some code goes here;
}
}