need some help with ComboBoxes in Java. Looked through similar questions, found one slightly related, but not what im dealing with.
I need to load certain arrays into combo boxes depending on the items selected in the precious combo box:
think getting some procedure done at a medical center: Choose a procedure->get a list of doctors who do it, choose a doctor->get a list of available hours etc.
A single choice is working fine(whether it's "procedure->list of doctors", or "list of doctors->their working hours"), but doing more than a single one of those changes doesn't work.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Arrays;
public class GUIbandymas extends JFrame {
String[] start={"Choose","Choice1", "Choice2"};
String[] Option1={"Choose","A1"};
String[] Option2={"Choose","A2","A3"};
String[] Option3={"Choose","a","b","c","d"};
String[] Option4={"Choose","1","2","3","4"};
String[] Option5={"Choose","I","II","III","IV"};
String[] pradinis={"Pasirinkite Laika"};
String[] p1={"Pasirinkite Gydytoja"};
static double kainaR;
static double kainaK;
JComboBox<String> G=new JComboBox<String>(p1);
JComboBox<String> proc;
JComboBox<String> laikas=new JComboBox<String>(pradinis);
JComboBox<String> minutes;
JButton button = new JButton ("Registuotis");
JLabel label = new JLabel("Moketi uz vizita");
JLabel suma = new JLabel();
public GUIbandymas() throws Exception {
setValueProc(start);
frame();
}
public void frame()
{
JFrame frame = new JFrame();
frame.setVisible(true);
frame.setSize(500,300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.add(proc);
panel.add(G);
panel.add(laikas);
panel.add(button);
button.setEnabled(false);
//panel.add(minutes);
frame.add(panel);
panel.add(label);
panel.add(suma);
proc.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e) {
if(proc.getSelectedItem().toString().equals("Choice1"))
{
setGyd(Option1);
}
if(proc.getSelectedItem().toString().equals("Choice2"))
{
setGyd(Option2);
}
}
});
G.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent a) {
if(G.getSelectedItem().toString().equals("A1"))
{
setLaikas(Option3);
}
if(G.getSelectedItem().toString().equals("A2"))
{
setLaikas(Option4);
}
if(G.getSelectedItem().toString().equals("A3"))
{
setLaikas(Option5);
}
}
});//JComboBox
}
public void setGyd(String[] s)
{
G.removeAllItems();
for(int i=0; i<s.length; i++)
{
G.addItem(s[i]);
}
}
public void setValueProc(String[] sarasas)
{
proc=new JComboBox<String>(sarasas);
}
public void setLaikas(String[] sarasas)
{
laikas.removeAllItems();
for(int i=0; i<sarasas.length; i++)
{
laikas.addItem(sarasas[i]);
}
}
}
Im in a dire need of any suggestions and possible fixes, im inclined to think that it has something to do with action listeners, since methods do work, but im at a loss since i cant determine what is it.
EDITED: the actual code should work, seems like there is no unneeded things from other files left.
NOTE: this is work with GUI, just launch it in you main() :)
While I don't really like the if-else approach you're using, it should work just fine. I agree with rrirower's suggestion that you should look at using a data model instead. Especially if you get a lot of choices, since the code turns messy quite fast.
The problem with your code is that you run into NullPointerException when rebuilding the combobox items. The reason for this is that G.actionPerformed() is called when you remove/add items. After you have removed all items (before you start adding new ones), G.getSelectedItem() will return null.
If you code a little bit more defensively, then it works as expected:
proc.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Object selectedItem = proc.getSelectedItem();
if ("Choice1".equals(selectedItem)) {
setGyd(Option1);
}
if ("Choice2".equals(selectedItem)) {
setGyd(Option2);
}
}
});
G.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent a) {
Object selectedItem = G.getSelectedItem();
if ("A1".equals(selectedItem)) {
setLaikas(Option3);
}
if ("A2".equals(selectedItem)) {
setLaikas(Option4);
}
if ("A3".equals(selectedItem)) {
setLaikas(Option5);
}
}
});//JComboBox
Instead of checking for null's, I just flipped the equals and skipped the unnecessary toString() (they are already strings, that's what you put in there).
Another thing, a pet peeve of mine, please follow the normal java code convention for all your class, field and method names. You're almost there, but Option1 etc. should start with lowercase. G should probably have a more descriptive name, as well as start with lowercase.
Finally, I didn't understand why you both create a JFrame in the constructor and extend JFrame in your class. You should choose one or the other.
You don't appear to be using a data model for the combo box. The data model controls the internal list of items. Have a look at this for more info.
Related
Okay, so here's the deal. Currently, I am using this:
String[] choices = {"Rock", "Paper", "Scissors"};
String input = (String) JOptionPane.showInputDialog(null, "Please, make your choice", "Rock Paper Scissors!", JOptionPane.QUESTION_MESSAGE, null, choices, choices[0]);
Which is what I need. It creates a drop down menu that allows the user to select Rock, Paper, or Scissors and then outputs it into a String. The problem is, the window that it pops in is REALLY small, and is in the center of the screen. I want to re-size it to be 970 pixels by 300 pixels, and to appear at the location of 950 pixels and 0 pixels.
Now, before you say it, I HAVE tried to use JFrames for this, because I know how to get it the size and at the location I want it. However, I can't get the ActionListener to behave in the way that I want it to.
public static void main(String args[]) throws IOException
{
JFrame hi = new JFrame("Hi");
hi.setSize(970, 300);
hi.setLocation(950, 0);
System.out.println("Hi");
Picture Hi = new Picture("c:/The Game/Cool.png");
Hi.display();
JButton B = new JButton("Hey There!");
hi.add(B);
int c = Output(hi);
}
public int Output(JFrame b)
{
int j = 0;
j = //CODE NEEDED HERE
return j;
}
#Override
public void actionPerformed(ActionEvent arg0) {
}
So, the problem with this is that I need the JFrame to pop up in then "CODE NEEDED HERE" section, and then, upon clicking the button, to return a certain value, and then to close out of the JFrame. However, the JFrame doesn't wait for the Output() function, and it immediately returns j, which is equal to 0. Instead, it just does whatever is in the actionPerformed function.
So, I am asking for a solution to either one of these problems. How to either re-size the JOptionPane.showInputDialog() or to get the JFrame to return an int value upon clicking a button.
Sorry if this is really poorly explained, I'm really new to JOptionPane and JFrames.
JOptionPane is quite configurable, it's also nicely self contained, taking a lot of the repetitive, boil plate code and hiding it away in an easy to use package.
But that doesn't mean you have to use it that way, you can simply create an instance of JOptionPane, which is just an ancestor of JComponent and add it to what ever you want.
The difficulty is plumbing all the functionality back together, so you can respond to the buttons, for example.
Just beware, your example places the dialog under my task bar (yes, mine is at the top of the screen), so I can tell you, as a user, that will annoy me!
So, this example basically wraps up all the boiler plate code into a simple class/method, which makes it easy to repeatedly prompt the user the same question, over and over again...
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import static javax.swing.JOptionPane.OK_CANCEL_OPTION;
import static javax.swing.JOptionPane.UNINITIALIZED_VALUE;
import static javax.swing.JOptionPane.VALUE_PROPERTY;
import javax.swing.border.EmptyBorder;
public class Test {
public static void main(String[] args) {
String pick = Picker.pick();
System.out.println("You picked " + pick);
System.exit(0);
}
public static class Picker {
public static String pick() {
String[] choices = {"Rock", "Paper", "Scissors"};
JOptionPane pane = new JOptionPane("Please, make your choice", JOptionPane.QUESTION_MESSAGE,
OK_CANCEL_OPTION, null, null, null);
pane.setWantsInput(true);
pane.setSelectionValues(choices);
pane.setInitialSelectionValue(choices[0]);
JDialog dialog = new JDialog();
dialog.setModal(true);
PropertyChangeListener listener = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent event) {
// Let the defaultCloseOperation handle the closing
// if the user closed the window without selecting a button
// (newValue = null in that case). Otherwise, close the dialog.
if (dialog.isVisible()
&& (event.getPropertyName().equals(VALUE_PROPERTY))
&& event.getNewValue() != null
&& event.getNewValue() != JOptionPane.UNINITIALIZED_VALUE) {
dialog.setVisible(false);
}
}
};
WindowAdapter adapter = new WindowAdapter() {
private boolean gotFocus = false;
public void windowClosing(WindowEvent we) {
pane.setValue(null);
}
public void windowClosed(WindowEvent e) {
dialog.removePropertyChangeListener(listener);
dialog.getContentPane().removeAll();
}
public void windowGainedFocus(WindowEvent we) {
// Once window gets focus, set initial focus
if (!gotFocus) {
pane.selectInitialValue();
gotFocus = true;
}
}
};
dialog.addWindowListener(adapter);
dialog.addWindowFocusListener(adapter);
dialog.addComponentListener(new ComponentAdapter() {
public void componentShown(ComponentEvent ce) {
// reset value to ensure closing works properly
pane.setValue(JOptionPane.UNINITIALIZED_VALUE);
}
});
pane.addPropertyChangeListener(listener);
dialog.add(pane);
//dialog.pack();
//dialog.setLocationRelativeTo(null);
dialog.setSize(970, 300); // This is bad idea, use an EmptyBorder instead
dialog.setLocation(950, 0);
dialog.setVisible(true);
String pick = null;
Object value = pane.getInputValue();
if (value != UNINITIALIZED_VALUE) {
pick = value.toString();
}
return pick;
}
}
}
The reason you're having problems with JFrame is because it's not designed to block the code execution when displayed, a JDialog can, see How to Make Dialogs for more details
I don't know where to start I don't want to be spoon fed either. Help me with tons of problem.
My goal in this program is to get input from the user by letting them type in the input area and there area three button (ascending, array, bubble sort) must them to pick and then the output must show in outputarea.
my code only ends up in getting the input of the user in input area.
My problems are:
Can I tell the user to input like this (1, 2, 3, 5, 6) with comma and neglected the comma then convert it to array to sort it.
After they click the either three buttons how can i output it in the output area.
Is my code in the right track or not? :D
Sorry for my bad english.
i dont want to be spoonfeed just help me guys :D
more power stackoverflow
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class JavaGui205 extends JPanel
{
final JTextField inputarea,outputarea;
final JButton asc,desc,bubble;
int getsd;
JavaGui205()
{
//initialize textfield and buttons
inputarea=new JTextField("Inputarea",20);
outputarea=new JTextField("Outputarea",20);
asc=new JButton("Ascending");
desc=new JButton("Descending");
bubble=new JButton("BubbleSort");
//adding function on fields
inputarea.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==inputarea)
{
String sd=e.getActionCommand();
getsd=Integer.parseInt(sd);
}
}
});
//ascending function
asc.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
}
});
//adding to frame
add(inputarea);
add(asc);
add(desc);
add(bubble);
add(outputarea);
}
public static void main(String[]args)
{
JFrame frame = new JFrame("WTF");
frame.add(new JavaGui205());
frame.setVisible(true);
frame.setSize(300,150);
}
}
I try some fixixation.I add these code tnx to mr Wyatt Lowery.but i have some problems how can i convert those string array into integer array then contain its values to use to three buttons then the product of those will display in the output area.Im sorry guys im slowpoke T_T :D i try my best to research but nothing happens
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==inputarea)
{
String sd=inputarea.getText();
String[] inputArray=sd.split(",\\s*");
}
}
Your problems in order:
Get the string from the text field inputarea.getText() and store it into a variable(E.g. inputText = inputarea.getText()). You can use the method split() to separate the values and put it into an array(E.g. String[] inputArray = inputText.split(", "))
When the button is clicked, set the outputarea text equal to the array
(E.g. outputarea.setText(inputArray.toString()))
Try working on your coding conventions :-)
I am currently in a programming course in highschool and we are focusing on Java, one of the programs required to be built is a Rock Paper Scissors game. I have done this easily and it works but i decided to try and figure out how to make it work in a window of its own. this led me to research JFrames and how to use them. I have loked up many tutorials to introduce it and I have 5 different examples from the oracle site saved to use for reference, yet i have not be able to figure out why this program won't work.
package rps;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
/**
* Name: Steven Biro
* Course Code: ICS3U
* Teacher: Mr.Carron
* Date: 23-Apr-2014
* Program Description:
*/
public class RPS
implements ActionListener {
static JPanel text,buttons;
/**
* #param args the command line arguments
*/
public void RPS() {
JButton Rock,Paper,Scissors;
buttons = new JPanel();
Rock = new JButton("Rock");
Paper = new JButton("Paper");
Scissors = new JButton("Scissors");
Rock.setMnemonic(KeyEvent.VK_D);
Paper.setMnemonic(KeyEvent.VK_M);
Scissors.setMnemonic(KeyEvent.VK_E);
Rock.setActionCommand("Rock");
Paper.setActionCommand("Paper");
Scissors.setActionCommand("Scissors");
Rock.addActionListener(this);
Paper.addActionListener(this);
Scissors.addActionListener(this);
buttons.add(Rock);
buttons.add(Paper);
buttons.add(Scissors);
}
public void actionPerformed(ActionEvent e) {
String PC,Player;
int outcome;
PC="";
Player=(e.getActionCommand());
int computer = (int)(Math.random()*3+1);
if (computer==1) {
PC="Rock";
} else if (computer==2) {
PC="Paper";
} else {
PC="Scissors";
} if (Player.equals(PC)) {
outcome=0; //tied
} else {
if ("Rock".equals(PC)) {
if ("Paper".equals(Player)) {
outcome=1; //win
} else {
outcome=2; //lose
}
} else if ("Paper".equals(PC)) {
if ("Scissors".equals(Player)) {
outcome=1; //win
} else {
outcome=2; //lose
}
} else {
if ("Rock".equals(Player)) {
outcome=1; //win
} else {
outcome=2; //lose
}
}
}
JLabel r;
if (outcome==0) {
r = new JLabel ("You Tied.");
} else if (outcome==1) {
r = new JLabel ("You Win.");
} else if (outcome==2) {
r = new JLabel ("You Lose.");
} else {
System.exit(2);
r = new JLabel ("wont ever execute");
}
text = new JPanel();
text.add(r);
}
public static void GUI() {
//Create and set up the window.
JFrame frame = new JFrame("RockPaperScissors");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
frame.add(buttons);
frame.add(text);
//Display the window.
frame.pack();
frame.setVisible(true);
frame.setSize(250,150);
}
public static void main(String[] args) {
GUI();
}
}
If you can help me figure out why the JPanels called "buttons" and "text" wont add I would be very grateful.
If I remove
//Create and set up the content pane.
frame.add(buttons);
frame.add(text);
from my program, then it runs without a problem and is just a blank window as would be expected, so i am at a loss of what to do.
EDIT:
The error i get after i make the correction of removing void from public void RPS() {
Exception in thread "main" java.lang.NullPointerException
at java.awt.Container.addImpl(Container.java:1091)
at java.awt.Container.add(Container.java:1003)
at javax.swing.JFrame.addImpl(JFrame.java:564)
at java.awt.Container.add(Container.java:415)
at rps.RPS.GUI(RPS.java:102)
at rps.RPS.main(RPS.java:114)
Picked up _JAVA_OPTIONS: -Djava.net.preferIPv4Stack=true
Java Result: 1
If i remove static from static JPanel text,buttons; then netbeans "corrects" each method so it never says static for any of them including Main so it says it cant find main.
sorry if im coming across as stupid, but if anyone could please help me figure this out i would be very appreciative.
You never create a RPS instance anywhere via new RPS().
You have a "pseudo-constructor" in your RPS class. i.e., this, public void RPS() { is not a constructor. Get rid of the void return type as constructors should have no return type: public RPS() {
Your Swing component fields should most definitely not be static.
You're adding components to a JFrame without respect for its layout manager, the BorderLayout. Your current code is adding null components, but if they weren't null, they'd both be added BorderLayout.CENTER, the last one covering up the previous one.
Create a master JPanel in the RPS class, and then add that to the JFrame in the main method, via non-static methods.
For example, RPS could potentially extend JPanel, and if that's the case, then you'd add it to the JFrame like so:
JFrame frame = new JFrame("RPS");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.add(new RPS());
Other suggestions:
Check out enums as Rock Paper Scissors lends itself well to this, including giving the enum methods to test for win
By using an enum, it would be easier to modify the code later to allow for additional states, such as Lizard and Spock.
Try to separate the logic portion of your program from the view -- the GUI portion.
Avoid having your GUI classes implement your listener interfaces as this leads to creation of "switch-board" listeners, kind of like you're writing -- a bear to debug or enhance. Instead experiment with anonymous inner classes, or private inner classes here.
This is probably because
public void RPS() {
is not the constructor, but a method (because it has a return type), and so is never called.
Remove the void and you should be good.
My problem is a bit tricky. I am using an Editable JComboBox. It may contain case sensitive items. For example, it may have Item1 and item1. So, these two items should be treated as different in my case.
But the problem is, these two items is treated as same. No matter which Items I have selected, it always select the first one (Item1). I've searched in Google, but didn't find any solution. That's why, I am here.
Code:
//loading of Items
jdcbmItemType = new javax.swing.DefaultComboBoxModel(ItemTypeHandler.getItemTypeComboData(MainFrame.companyId));
private void jcbItemTypeMouseReleased(MouseEvent evt)
{
if (jcbItemType.getSelectedIndex() != -1)
{
loadItemTypeDetails(((ItemObject) jcbItemType.getSelectedItem()).getId());
}
else
{
resetFields();
}
}
public static Vector<ItemObject> getItemTypeComboDataV(BigInteger companyId, BigInteger categoryId, boolean addFirstElement, TriState deleted) throws ExceptionWrapper, EJBException
{
try
{
return (Vector<ItemObject>)lookupItemTypeFacade().getItemTypeComboData(companyId, categoryId, addFirstElement, deleted);
} catch (ExceptionWrapper exceptionWrapper)
{
throw exceptionWrapper;
} catch (EJBException ejbEx)
{
throw ejbEx;
} catch (Exception ex)
{
throw new ExceptionWrapper(ex.getMessage());
}
}
ItemObject is a customClass where one field is BigInteger and another is String.
getItemTypeComboData is functioning properly. So, you can assume to get a list of ItemObject from here and it will nicely convert it to Vector<ItemObject>
jcbItemType.getSelectedIndex() always return the same index for Item1 and item1. But it returns different index for item2.
I know, it would be better if I can use itemStateChanged event. But in my case, I can't use it. But my question is, MouseReleased and FocusLost works fine for different name string but not same string with different case. I am really stumbled.
Another way to ask the question:
Does MouseReleased or FocusLost event check for case-sensitive items?
How to resolve this problem?
Thanks.
Here is my SSCCE and this works fine , If this is not what youre looking for, then post your SSCCE for better sooner help!
import javax.swing.*;
import java.awt.event.*;
public class ComboBoxTest {
JComboBox combo;
JTextField txt;
public static void main(String[] args) {
new ComboBoxTest();
}
public ComboBoxTest() {
String items[] = {"Item1", "item1"};
JFrame frame = new JFrame("JComboBox Case-sensitivity Test");
JPanel panel = new JPanel();
combo = new JComboBox(items);
combo.setEditable(true);
txt = new JTextField(10);
panel.add(combo);
panel.add(txt);
frame.add(panel);
combo.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent ie) {
String str = (String) combo.getSelectedItem();
txt.setText(str);
}
});
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 100);
frame.setVisible(true);
}
}
I think you are doing like this :-
String[] items = {"item1", "item2"};
JComboBox cb = new JComboBox(items);
cb.setEditable(true);
Now you have to access the JCombobox elements which you have insert into this as in array form like this:-
MyItemListener actionListener = new MyItemListener();
cb.addItemListener(actionListener);
class MyItemListener implements ItemListener {
// This method is called only if a new item has been selected.
public void itemStateChanged(ItemEvent evt) {
JComboBox cb = (JComboBox)evt.getSource();
// Get the affected item
Object item = evt.getItem();
if (evt.getStateChange() == ItemEvent.SELECTED) {
// Item was just selected
} else if (evt.getStateChange() == ItemEvent.DESELECTED) {
// Item is no longer selected
}
}
}
After adding the itemListener you can do your different tasks with individual JCombobox Item
Try this, it works fine...
use ActionListener() to capture the click... then use getSelectedItem() to capture the item clicked on the JComboBox
try this,
check in your console for the output
myComboBox.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent ie) {
String str = (String) myComboBox.getSelectedItem();
System.out.println(str);
}
i'm having problems with this listener, the gui in general constructs and works fine, also the jlist is there but when i select some items in the list i dont see the results and also not the printl() i wrote for test purpose, pls note this code is contained within the getJContentPane in order to add the event handler at init-time
private JList myList=new JList(dlm);//a defaultlistmodel
myList.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent evt) {
if (evt.getValueIsAdjusting()){
System.out.println("Eventhandler called");
return;
}
System.out.println("Eventhandler called");
doMyMethod(evt);
}
});
The doMyMethod():
private void doMyMethod(ListSelectionEvent e){
if(e.getValueIsAdjusting()){
return;
}else{
String item=(String)e.getSource();
accounter.add(item);
}
}
It is a very simple method which takes as parameter an instance of ListSelectionEvent
The main problem in my opinion is not the doMyMethod() which performs very basic actions but the fact that the eventHandler is not fired at all, it seems lik the gui does not "listen" to this list at all
Any idea?
here the initialisation code:
private JScrollPane getScrollBox() {
if (scrollboxBox == null) {
scrollboxBox = new JScrollPane();
scrollBox.setBounds(new Rectangle(280, 56, 245, 204));
scrollBox.getViewport().add(myList,null);
myList.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent evt) {
System.out.println("addListSelectionListener");
if (evt.getValueIsAdjusting()){
System.out.println("Eventhandler called");
return;
}
System.out.println("Eventhandler called");
doMyMethod(evt);
}
});
}
return scrollboxBox;
}
After trying to understand what is going on in your question I understood that you are failing to get selected item in the list, when the selection is changed.
To present you how this could be achieved I have built the below example. You can observe there when each part of the if else is called. The if(e.getValueIsAdjusting()) is execute always when you drag the moue over items. The else part is called when you release the mouse while previously clicked on an item.
There are some serious issues in the code that you have provided, therefore I tried to remove all that is unnecessary, e.g.
1.The doMyMethod() method and the if(e.getValueIsAdjusting()) piece of code that is in it would never be called since you already are checking that condition before it is called. Plus there is no need to code a method working on listener's events, this code should stay inside the listener which is private. Then if you want to call programmatically its code you would call the listener.valueChanged(evt).
2.The evt.getSource() returns the object which is author of the event in this case the myList not the selected item which I think you were after, for this use the getSelectedValue() on the source or myList directly since this listener serves only this list.
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class ListTest extends JPanel
{
private JScrollPane myScrollPane;
private JList myList;
private ListSelectionListener lSL = new ListSelectionListener()
{
#Override
public void valueChanged(ListSelectionEvent evt)
{
if(evt.getValueIsAdjusting())
{
System.out.println("Eventhandler called evt.getValueIsAdjusting() true");
return;
}
else
{
// String item = (String) evt.getSource();//!!!Exception casting JList to String
//maybe what you need is getSelectedValue()
System.out.println("else called myList.getSelectedValue() ="+myList.getSelectedValue());
}
}
};
private ListTest()
{
int noRows = 25;
Object[] listData = new String[noRows];
for(int i =0; i < noRows; i++)
listData[i]= "Oi "+i;
this.myList = new JList(listData);
this.myScrollPane = new JScrollPane(myList);
myList.addListSelectionListener(lSL);
add(myScrollPane);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
ListTest p = new ListTest();
JPanel contentPane = new JPanel();
contentPane.add(p);
JFrame f = new JFrame();
f.setContentPane(contentPane);
f.setSize(800, 600);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
});
}
}
Hope that even if it doesn't solve your problem it at least will be helpful in building an SSCCE for us.