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
Related
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!
I've created a JPanel[][] Array.
private JPanel[][] pnlFeld;
And filled it with panels
for (int i = 0; i < world.getSize(); i++) {
for (int j = 0; j < world.getSize(); j++) {
pnlFeld[i][j] = new JPanel();
pnlFeld[i][j].setBorder(new EtchedBorder());
pnlFeld[i][j].addMouseListener(ml);
pnlFeld[i][j].setBackground(off);
add(pnlFeld[i][j]);
}
}
Now I want to get the array coordinates ([][]) by clicking on them and I have no clue how to do that.
I've only added methods to change the color of the panel I clicked on, nothing related to my problem.
MouseListener ml = new MouseListener() {
#Override
public void mouseEntered(MouseEvent e) {
if (world.getMode().equals("Malen")) {
if (e.getSource() instanceof JPanel)
e.getComponent().setBackground(on);
// check();
}
else if (world.getMode().equals("Radieren")) {
if (e.getSource() instanceof JPanel)
e.getComponent().setBackground(off);
// check();
}
}
#Override
public void mousePressed(MouseEvent e) {
if (SwingUtilities.isLeftMouseButton(e)) {
if (world.getMode().equals("Setzen")) {
if (e.getSource() instanceof JPanel) {
if (e.getComponent().getBackground() == off) {
e.getComponent().setBackground(on);
} else
e.getComponent().setBackground(off);
}
// check();
}
}
}
#Override
public void mouseClicked(MouseEvent e) {}
#Override
public void mouseExited(MouseEvent e) {}
#Override
public void mouseReleased(MouseEvent e) {}
};
Actually you can use getBounds() to get component location and size. If you mean the array indexes there could be multiple solutions.
Define a Map and place all your panels in the Map with String value e.g. i+":"+j (or define simple pojo class with 2 fields i and j.
Create unique listener for each JPanel to keep the i and j.
Place the panels in a containr with GridBagLayout then you can use gridBagLayoutInstance.getConstraints(theClickedPanel) and check row column of the constraint
Getting JPanel[][] coordinates by clicking on a JPanel
Use a JButton[][] with ActionListener for easier coding and a better user experience. The ActionEvent has a getSource() method that will identify the button that was activated.
This chess GUI uses buttons for the 64 places on the chessboard.
If you create your MouseListener in your loop, you can use i en j within the code of your listener. The drawback is that you'll have a bit more instances of your listener.
I could suggest that you set the name of each JPanel as i and j in the loop where you declare and initialise the panels. As illustrated
pnlFeld[i][j].setName(i + "" + j);
And in your mouseClicked event check if the event source is an instance of JPanel and parse the name to get the x and y coordinates like this:
Integer.parseInt(p.getName().subString(0,1))
Integer.parseInt(p.getName().subString(1));
Currently I'm using a for-loop to populate the JPanel with numbers from 1-31
So basically, What I want to do is if let say i click on number 1, it will do show
System.out.println(1);
Here's the code:
public class MonthPanel extends JPanel implements MouseListener {
public MonthPanel() {
setLayout(new GridLayout(6,7));
// Add headers
// Use for-each loop.
for (String header : headers) {
add(new JLabel(header));
}
for (int i = 1; i < 31; i++) {
add(new JLabel(String.valueOf(i)));
}
addMouseListener(this);
}
public void mouseClicked(MouseEvent e) {
// What should i do in here to get a specific JLabel?
}
}
}
Here's the picture
Here's the solution
First you have to add mouselistener in label which should have mouse adapter in brackets its because you only want to use mouse click method.
Than add mouseClicked method in it .
and than add you code in mouseClicked method.
Example:
JLabel l = new JLabel("label");
l.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
// Your Code Here
}
});
add(l);
Instead of adding like that you can do something like
for (String header : headers) {
JLabel lbl = new JLabel(header);
lbl.addMouseListener(add ur listner);
add(lbl);
}
In the mouseClicked event you can get the JLabel and print its text as follows
public void mouseClicked(MouseEvent e) {
System.out.println(((JLabel) e.getSource()).getText());
}
In your code if you implement the MouseListener interface you must override all the abstract method in that. Otherwise it will not compile
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'm having some trouble using two comboboxes to affect the state of one item. Each combo box has a value between 1 and 99, I'm trying to change the values in each, combine them, then display this value on a jlabel. So far I can only the first combobox seems to impact the formula. I have simplified it to the following and thanks for any help :)
private int value1int, value2int;
value1.addItemListener(new ItemListener()
{
public void itemStateChanged(ItemEvent ex)
{
if (ex.getStateChange() == ItemEvent.SELECTED)
{
// assume single selection
int value1int = (Integer)ex.getItemSelectable().getSelectedObjects()[0];
}
}
});
value2.addItemListener(new ItemListener()
{
public void itemStateChanged(ItemEvent exs)
{
if (exs.getStateChange() == ItemEvent.SELECTED)
{
// assume single selection
int value2int = (Integer)exs.getItemSelectable().getSelectedObjects()[0];
}
}
});
overallValue2.setText((Integer.toString(value1int + value2int)));
overallValue2.revalidate();
you have to do something like that:
public class GUI extends JFrame ...
private int labelVal;
...
// combobox events - The same code to both comboboxes must works
public void itemStateChanged(ItemEvent exs)
{
if (exs.getStateChange() == ItemEvent.SELECTED)
{
// assume single selection
int aux = (Integer)combobox1.getSelectedItem()+(Integer)combobox2.getSelectedItem();
int labelVal= aux;
}
}
Them refresh the screen