Programatically Select an Item in a JList
Hi,
I need to do this: Programmatically select an item in a JList.
JList.selectItem(0) will select the item 0 in the model but it will NOT visually highlight the selected item in the list.
Neither will ensureIndexIsVisible(0),
I need to automatically select and item in a list (highlight that item as well)
As if someone has clicked on that item with the mouse.. however they haven't you see, my program has done it, programatically.
Please don't refer me to the beginners guide to java, or the API documentation, the answer is not there.
Thanks
Swing related questions should be posted in the Swing forum.
Please don't refer me to the beginners guide to java, or the API documentation, the answer is not there.Yes it is.
If you need further help then you need to create a [url http://homepage1.nifty.com/algafield/sscce.html]Short, Self Contained, Compilable and Executable, Example Program (SSCCE) that demonstrates the incorrect behaviour, because I can't guess exactly what you are doing based on the information provided.
And don't forget to use the [url http://forum.java.sun.com/help.jspa?sec=formatting]Code Formatting Tags so the code retains its original formatting.
Similar Messages
-
HorizontalList - How to programatically select an item
Hi All,
I am new to flex and new to this forum. I am building an
application that uses a HorizontalList and a button.
When the button is clicked, I need to add a new item (image +
label) on the HorizontalList, and I need to make the newly added
item the default selection.
I tried to set the selectedIndex property, but that does not
work.
Any idea how to make this work ? ie how to programatically
select an item in the HorizontalList
Regards
RoniThis code seems to do what you want:
-
Selecting an item twice in JList
Hy,
I have create a JList with some animal's name in it. When I click on one of the animal's
name for the FIRST time, it appears in a JTextArea.
What I want is that when I click on that same name consecutively, it appears again in that
JTextArea. Can anyone please send me the code for doing that. Its very urgent.
Here are my code:
import javax.swing.*;
import javax.swing.text.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class PropertyWindow extends JFrame implements ListSelectionListener, ActionListener {
private JList list;
private JScrollPane scrollTextArea;
private JTextArea textArea;
private String text;
private Vector imageNames;
private JLabel picture;
private DefaultListModel listModel;
public PropertyWindow () {
super("Property Window");
//create a text area
textArea = new JTextArea();
textArea.setFont(new Font("Arial", Font.PLAIN, 16));
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
//create a scrollpane and add it to the text area
scrollTextArea = new JScrollPane(textArea);
scrollTextArea.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
scrollTextArea.setPreferredSize(new Dimension(200,35));
//create a list of button and add it to the JPanel
JButton addButton = new JButton("+");
JButton subtractButton = new JButton("-");
JButton multiplyButton = new JButton("x");
JButton divideButton = new JButton("/");
JButton assignButton = new JButton("=");
JButton equalButton = new JButton("= =");
JButton greaterButton = new JButton(">");
JButton G_EqualButton = new JButton("> =");
JButton lessButton = new JButton("<");
JButton L_EqualButton = new JButton("< =");
JButton notEqualButton = new JButton("! =");
JButton oneButton = new JButton("1");
JButton twoButton = new JButton("2");
JButton threeButton = new JButton("3");
JButton fourButton = new JButton("4");
JButton fiveButton = new JButton("5");
JButton sixButton = new JButton("6");
JButton sevenButton = new JButton("7");
JButton eightButton = new JButton("8");
JButton nineButton = new JButton("9");
JButton zeroButton = new JButton("0");
addButton.setActionCommand ("+");
subtractButton.setActionCommand("-");
multiplyButton.setActionCommand("x");
divideButton.setActionCommand ("/");
assignButton.setActionCommand ("=");
equalButton.setActionCommand ("= =");
greaterButton.setActionCommand (">");
G_EqualButton.setActionCommand ("> =");
lessButton.setActionCommand ("<");
L_EqualButton.setActionCommand ("< =");
notEqualButton.setActionCommand("! =");
oneButton.setActionCommand ("1");
twoButton.setActionCommand ("2");
threeButton.setActionCommand ("3");
fourButton.setActionCommand ("4");
fiveButton.setActionCommand ("5");
sixButton.setActionCommand ("6");
sevenButton.setActionCommand ("7");
eightButton.setActionCommand ("8");
nineButton.setActionCommand ("9");
zeroButton.setActionCommand ("0");
JPanel buttonPane = new JPanel();
buttonPane.setBorder(
BorderFactory.createCompoundBorder(
BorderFactory.createCompoundBorder(
BorderFactory.createTitledBorder("Arithmetic/Logical Operations"),
BorderFactory.createEmptyBorder(5,5,5,5)),
buttonPane.getBorder()));
buttonPane.setLayout(new GridLayout (3,7));
buttonPane.add(addButton);
buttonPane.add(subtractButton);
buttonPane.add(multiplyButton);
buttonPane.add(divideButton);
buttonPane.add(assignButton);
buttonPane.add(equalButton);
buttonPane.add(greaterButton);
buttonPane.add(G_EqualButton);
buttonPane.add(lessButton);
buttonPane.add(L_EqualButton);
buttonPane.add(notEqualButton);
buttonPane.add(oneButton);
buttonPane.add(twoButton);
buttonPane.add(threeButton);
buttonPane.add(fourButton);
buttonPane.add(fiveButton);
buttonPane.add(sixButton);
buttonPane.add(sevenButton);
buttonPane.add(eightButton);
buttonPane.add(nineButton);
buttonPane.add(zeroButton);
addButton.addActionListener(this);
subtractButton.addActionListener(this);
multiplyButton.addActionListener(this);
divideButton.addActionListener(this);
assignButton.addActionListener(this);
equalButton.addActionListener(this);
greaterButton.addActionListener(this);
G_EqualButton.addActionListener(this);
lessButton.addActionListener(this);
L_EqualButton.addActionListener(this);
notEqualButton.addActionListener(this);
oneButton.addActionListener(this);
twoButton.addActionListener(this);
threeButton.addActionListener(this);
fourButton.addActionListener(this);
fiveButton.addActionListener(this);
sixButton.addActionListener(this);
sevenButton.addActionListener(this);
eightButton.addActionListener(this);
nineButton.addActionListener(this);
zeroButton.addActionListener(this);
//create the 'ok' and 'cancel' button
JButton okButton = new JButton("Ok");
JButton cancelButton = new JButton("Cancel");
okButton.setActionCommand("Ok");
okButton.addActionListener(this);
cancelButton.setActionCommand("Cancel");
cancelButton.addActionListener(this);
JPanel controlPane = new JPanel();
controlPane.setLayout(new FlowLayout());
controlPane.add(okButton);
controlPane.add(cancelButton);
//create a Jlist where to insert variables
listModel = new DefaultListModel();
listModel.addElement("dog");
listModel.addElement("cat");
listModel.addElement("rat");
listModel.addElement("rabbit");
listModel.addElement("cow");
list = new JList(listModel);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
//list.setSelectedIndex(0);
list.addListSelectionListener(this);
JScrollPane scrollList = new JScrollPane(list);
scrollList.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
scrollList.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollList.setPreferredSize(new Dimension(200,300));
scrollList.setBorder(
BorderFactory.createCompoundBorder(
BorderFactory.createCompoundBorder(
BorderFactory.createTitledBorder("Variables"),
BorderFactory.createEmptyBorder(5,5,5,5)),
scrollList.getBorder()));
//create a pane and put the scroll list and ok/cancel button in it
JPanel rightPane = new JPanel();
BoxLayout rightBox = new BoxLayout(rightPane, BoxLayout.Y_AXIS);
rightPane.setLayout(rightBox);
rightPane.add(scrollList);
rightPane.add(controlPane);
//create a pane and put the scroll text area and arithmetic button in it
JPanel leftPane = new JPanel();
BoxLayout leftBox = new BoxLayout(leftPane, BoxLayout.Y_AXIS);
leftPane.setLayout(leftBox);
leftPane.add(scrollTextArea);
leftPane.add(buttonPane);
//add both pane to the container
JPanel contentPane = new JPanel();
BoxLayout box = new BoxLayout(contentPane, BoxLayout.X_AXIS);
contentPane.setLayout(box);
contentPane.add(leftPane);
contentPane.add(rightPane);
setContentPane(contentPane);
public void valueChanged(ListSelectionEvent e) {
if (e.getValueIsAdjusting() == false) {
if (list.getSelectedIndex() == -1) {
//No selection, disable fire button.
else {
//Selection, update text field.
String name = list.getSelectedValue().toString();
textArea.append(" " + name + " ");
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
if (cmd.equals("Ok")) {
// save current textarea
text = textArea.getText();
System.out.println(text);
dispose();
setVisible(false);
if (cmd.equals("Cancel")) {
dispose();
setVisible(false);
if (cmd.equals("+")) {
textArea.append(" + ");
if (cmd.equals("-")) {
textArea.append(" - ");
if (cmd.equals("x")) {
textArea.append(" x ");
if (cmd.equals("/")) {
textArea.append(" / ");
if (cmd.equals("=")) {
textArea.append(" = ");
if (cmd.equals("= =")) {
textArea.append(" == ");
if (cmd.equals(">")) {
textArea.append(" > ");
if (cmd.equals("> =")) {
textArea.append(" >= ");
if (cmd.equals("<")) {
textArea.append(" < ");
if (cmd.equals("< =")) {
textArea.append(" <= ");
if (cmd.equals("! =")) {
textArea.append(" != ");
if (cmd.equals("1")) {
textArea.append("1");
if (cmd.equals("2")) {
textArea.append("2");
if (cmd.equals("3")) {
textArea.append("3");
if (cmd.equals("4")) {
textArea.append("4");
if (cmd.equals("5")) {
textArea.append("5");
if (cmd.equals("6")) {
textArea.append("6");
if (cmd.equals("7")) {
textArea.append("7");
if (cmd.equals("8")) {
textArea.append("8");
if (cmd.equals("9")) {
textArea.append("9");
if (cmd.equals("0")) {
textArea.append("0");
public static void main(String args []) {
JFrame frame = new PropertyWindow();
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
frame.pack();
frame.setVisible(true);
frame.setResizable(false);
}If the whole point of the JList is to display the information in the JTextArea and you don't mind losing the selection in the JList I have a solution for you (just had something similar come up).
Add the following lines in the public void valueChanged(ListSelectionEvent e) method:
listModel = list.getModel();
list.setModel(listModel);
This causes the particular animal in the JList to be un-selected and with each subsequent clicks on that JList selection a new ListSelectionEvent will fire and the text will keep appending.
This gives the effect of a JList just being a bunch of buttons that can be clicked on all you want. -
Selecting a Item in horizontal list programatically
Hi,
I have multiple horizontal lists in a canvas and am trying to manage the focus between them.
Am facing problems while I try to programatically select a item by setting the SelectedItem property to [0],
can someone help me please!!
kcbthe following steps solved the problem:
1) Setting the focus to the horizontalList using horizontallist.setfocus() method.
2)Setting the selectedIndex property
3) firing explicitly a key event for the horizontallist.
I did not directly use the horizontal list , I extended the horizontal list class and added a public method which I can call to explicitly call the key event handler. -
Problems with the selected item in a JList
Hi,
I am using a JList with a JTextPane as renderer, when I select an item in the list the foreground color is black instead of being white and when I go up in the list the foreground color of the items under the selected one is white (they are not visible anymore).
Does anyone know why this list behaves like that and what I should do to prevent this?
Thanks in advance
Here's the code of the renderer (I suppose this is the place where the problems are):
public class TextPaneListRenderer extends JTextPane implements ListCellRenderer
public TextPaneListRenderer()
setOpaque(true);
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus)
this.setText(value.toString());
if (cellHasFocus)
setBackground(list.getSelectionBackground());
setForeground(list.getSelectionForeground());
else
setBackground(list.getBackground());
setForeground(list.getForeground());
return this;
getListCellRendererComponent() not yet implemented.");
}Hi,
i would use isSelected:
if (isSelected)
setBackground(list.getSelectionBackground());
setForeground(list.getSelectionForeground());
else
setBackground(list.getBackground());
setForeground(list.getForeground());
It might help, just give it a try. -
By default a item in a JList should selected
Hi
I need a item in the JList should be selected(not the first item) by default while I am creating a new instances for the JList.
Note: I am rendering a button in the JList.
with regrads
senthil kumarYou should be able to use either of the following methods of JList: setSelectedIndex(defaultIndex); or setSelectedValue(defaultObject, shouldScroll);Is one of these what you are looking for?
-
Key pressed in Jlist and selecting the item of key list accordingly
Hi,
I have a JList with the items in sorted order.Now I want that if a person presses any key (say K) then the first item starting with K should be selected.Hmmm I can do it by addding a key listener to the list and cheking all the items in the list ,by traversing through the whole lenght of JList and selecting the item if it starts with the character of the key pressed.
But i was thinking if there is any better way to do that?
Regards Aminsee bugid: 4654916 - it does say that the the
scrolling for the JList should now work with keyboard
selection.I have the same problem. Thanx for the hint with the bugid. Saw a good workaround there with a simple subclass of JList. Works for me although it is annoying to subclass JList all the time. The bug seems not to be fixed in the 1.4.1 JDK.
Andreas -
Selected item in a JList - Clear selection after mouse click
Hello:
I'm developing a Java GUI application which uses some JLists. I've seen that, when an item of the JList is selected and you click the mouse another time in the same selected item, the selection does not "disappear". Now, the only way I know to do this is tho press Control + click in the selected item.
I would like that, when I click to the selected item of a list, the selection disappears.
How can I solve that?
Lots of thanks for your help.add a MouseListener to the list
in mouseReleased (note: Released), get the selected index
compare to previous selection - if the same, list.clearSelection()
if you clear the selection, you'll need to reset the 'previous selection' variable -
Getting multiple items from a Jlist
hi i am trying to get selected items from a Jlist to print out
but can only seem to get one item at a time using getSelectedValue()
when i try and use getSelectedValues().toString(); i get
the following print out [Ljava.lang.Object;@ed783f68 can anyone show me
where i am going wrong and tell me why i get that print out
cheers
submitdetails.addActionListener(
new ActionListener() {
public void actionPerformed( ActionEvent e )
String data = privilegesList.getSelectedValue().toString();
Object data2 = privilegesList.getSelectedValues().toString();
System.out.println(data);
System.out.println(data2);
The getSelectedValues(...) method returns and ARRAY of OBJECTS. You have to loop through the array to get each object separately:
Object[] values = privilegesList.getSelectedValues();
for (int j = 0; j < values.length; j++)
System.out.println ( values[j].toString() ); -
How to programatically select text for editing in an af:inputText control?
Hello, I am new to jdeveloper 11.1.1.3.0 and have searched and searched for info. I must be using the wrong terms as I cannot find any info or example on how to programatically select text for editing in an inputText field.
My request is to change an existing app so when the user presses a button, control should go to the inputText control (this part works, see existing backing bean code from another developer below) but automatically select the text within for editing by the user (saving the user from having to select the text first before editing).
Backing bean code to set the focus to an inputText field:
* sets the cursor to the given component id
* @param componentId of item on page
public void setFocusOnUIComponent(String componentId) {
FacesContext facesContext = FacesContext.getCurrentInstance();
ExtendedRenderKitService service =
Service.getRenderKitService(facesContext, ExtendedRenderKitService.class);
UIComponent uiComponent = facesContext.getViewRoot().findComponent(componentId);
service.addScript(facesContext,
"Component = AdfPage.PAGE.findComponentByAbsoluteId('" + componentId + "'); Component.focus();");
} I hope this isn't a dumb question and would appreciate it if someone can steer me in the right direction.
Thank you for any info,
GaryHi,
not a dumb question at all. Before answering it, here some comments on the code you pasted in your question
1. UIComponent uiComponent = facesContext.getViewRoot().findComponent(componentId);
This code line is not used at all in your method. So it seems you can get rid of it
2. "Component = AdfPage.PAGE.findComponentByAbsoluteId('" + componentId + "'); Component.focus();");
I suggest to change it to
"var component = AdfPage.PAGE.findComponentByAbsoluteId('" + componentId + "'); component.focus();");
as it is better coding practice to have variable names starting with a lower case letter and being flagged with the "var" identifier
For pre-selecting text in an an input component, there is no API available in ADF Faces, which means you need to reach out to the rendered HTML ouput. To access the markup for the rendered component, you can try
var markup = AdfRichUIPeer.getDomContentElementForComponent(component)
If this markup returns the HTML input component then you can use JavaScript you find on the Internet to select the area of it. If it does not return the input component then you may have to use
document.getElementById(componentId+'::content')
Note however that working directly with generated HTML output bears the risk that your code breaks when - for whatever reason - the ADF Faces component rendering changes in the future
Frank
Frank -
How to select an item in sap.ui.table.Table without using index?
Hi there,
I want to select an item of a sap.ui.table.Table by finding the right item and selecting it.
Take the example at this SDK page:
SAPUI5 SDK - Demo Kit
You have first name and last name. I want to select "Mo Lester". While there is a function called setSelectedIndex, there is no function for setSelectedItem.
I have to search the items of the table for a required entry and select it (like clicking on it).
Is there a way to do this (programatically)?
I'm using aggregation binding with a JSON model.
Regards
TobiasHi Tobias,
What you could do is first find the JSON object (i.e., the table row) in your table model, and use its index in the model to set the selected index:
var matches = $.grep(array, function() {
return(this.firstName === "John" && this.lastName === "Doe");
if (matches.length) {
var index = yourTable.getModel().getData().indexOf(matches[0]); //first match
yourTable.setSelectedIndex(index); -
Set Default Value of Multi-select list item
I have a multi-select list item I want to default the value of to '%' (which is really '%null%') and have it selected. I tried setting default value of item, but it doesn't take '%null%'. I also tried a computation with a static of
:P507_ITEM := '%null%'; How do you get the default value set and selected?Hi
Shijesh is right, you need to change your null return value and use that return value as your default. Try and use something of the same datatype as your real return values if you plan to use '%' to display all as it will make your queries simpler. eg.
Company A returns 1
Company B return 2
% returns 0
Then your query would be...
SELECT ...
FROM ...
WHERE company_id = DECODE(:P_COMPANY,1,1,2,2,0,company_id)
Hope this makes sense.
Cheers
Ben -
Selecting open items in F-03 using additional selections
I need to select open items in a GL account using more than one additional selection eg. document type, posting date, assignment
I select Additional Selections then document type then add a document type, then I select Other Selection - posting date and then Process Open Items. Only the first selection for document type is recognised.
Is this a bug?
Edited by: Richard Somerset on Jan 7, 2009 5:14 PMHowever SAP help suggest that this can be done
Searching for Open Items
Use
After you have entered an account with open items, you can search for specific open items to be cleared.
On the screen for selecting open items, you can search for specific open items to be cleared using the following additional selection fields:
Gross amount
Document number
Posting date
Other fields depending on the system configuration
Procedure
To search for open items using the additional selection criteria, proceed as follows:
Choose one of these fields, such as Posting date, then choose Execute.
The screen for entering selection criteria appears.
Enter one or more single values or ranges within the selection, such as 01/01/1993 through 01/31/1993 for a range of posting dates.
To search for specific open items by other criteria (optional), choose Edit ® Select more.
Repeat steps 1 and 2 for the other selection criteria.
After you enter your selection criteria, you have the following options:
Display the list of open items by choosing Goto ® Open items.
Display the clearing document header and the items entered so far by choosing Goto ® Doc. Overview.
Post the clearing document by choosing Document ® Post
Edited by: Richard Somerset on Jan 8, 2009 9:05 AM -
Report for a selection of items+batch numbers that I would have had on hand
I would like to run a report for a selection of items and batch numbers that I would have had on hand (only) for September 30th. I have run the batch numbers report but this gives me all transactions from August 1/09 to September 30/09.
Hi
If you need to know quantity onhand ,probably you need to run query against OINM tables but If you are lloking for information then I guess this batch and serial number would be handy ....
Hope this helps
Bishal -
Display all valid items and select multiple items
Let us say I have valid items in table. For each purchase user can select few items from the list. I have to display all valid items from table and user should able to check items to buy. What is the best way we can implement this in forms.
Thanks, lalithaFor all the valid items you can create LOV as i understood then user can choose what he wants. But this sentence ti still confusing to me. Or what is the tricky things in you scanerio if only you have to show the valid item then use LOV.
Lalitk wrote:
and user should able to check items to buy.-Ammad
Maybe you are looking for
-
I have 2 iPods one I don't use anymore. I would like to make a new account for one but not the other. Is that possible? If I wipe the memory in one will the other wipe out too? How can I do all of this?
-
How can i execute a SAP function from destop in froeground mode?
Hi Experts, I faced a problme during my work. i need a programme log on a SAP system and then execute a function from my windows desktop. however i need this function to be executed in front end because there are someting need to be poped up. i am us
-
Receiver SOAP : Parsing SOAP Exception
Hello We have a simple scenario SOAP scenario and we are calling backend service in our Receiver SOAP It seems that issue is with the SOAP Action. Our backend service has multiple SOAP Actions : Endpoint is as follows http://serverID/ABCSoftware/ABC
-
Error in :--INTEGRATION_DIRECTORY_HMI :--Solved
hello frnds, after a fresh installation in configured a soap 2 rfc syn scenario ..and i encountered a XIAdapter Exception. after struggling a lot with all the connections.. i got into the Http connection for INTEGRATION_DIRECTORY_HMI:-- in
-
Using Customize grouping and filtering for EPPM 8.2.1 family
Are there any know issues or BUGS when using customize grouping and filtering returing more than the filtered projects? We are customizing grouping on Project Status and Region and filtering on Region and Let by Code Thanks