i want to highlight an item inside popup list.
I say "highlight" becouse i don't want to select it (for example by calling setSelectedItem) but only make it selected inside the jcombobox popup.
How can i do?
The following sort of works in that an item other than the first is selected. However, if you use the keyboard to change selection, it always starts from the first because that is the one that is selected.
import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.plaf.basic.*;
public class ComboBoxSelect extends JFrame
{
public ComboBoxSelect()
{
String[] items = { "Item1", "Item2", "Item3", "Item4", "Item5" };
JComboBox comboBox = new JComboBox( items );
add( comboBox );
comboBox.addPopupMenuListener(new PopupMenuListener()
{
public void popupMenuWillBecomeVisible(PopupMenuEvent e)
{
JComboBox comboBox = (JComboBox)e.getSource();
BasicComboPopup popup = (BasicComboPopup)comboBox.getAccessibleContext().getAccessibleChild(0);
JList list = popup.getList();
list.setSelectedIndex(2);
}
public void popupMenuCanceled(PopupMenuEvent e) {}
public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {}
});
}
public static void main(String[] args)
{
ComboBoxSelect frame = new ComboBoxSelect();
frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
frame.pack();
frame.setLocationRelativeTo( null );
frame.setVisible( true );
}
}
This write-up provides guidance on how you could modify JComboBox:
http://www.orbital-computer.de/JComboBox/
Although it's written for auto-complete functionality, a custom mechanism to highlight without selecting would be very similar (and probably easier).
Related
I have a JList, where i am displaying some ID's. I want to capture the ID the user clicked and dis play it on a JLabel.
String selected = jlist.getSelectedItem().toString();
The above code gives me the selected JList value. But this code has to be placed inside a button event, where when i click the button it will get the JList value an assign it to the JLabel.
But, what i want to do is, as soon as the user clicks an item of the JList to update the JLabel in real time. (without having to click buttons to fire an action)
A simple example would be like below using listselectionlistener
import java.awt.Dimension;
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class JListDemo extends JFrame {
public JListDemo() {
setSize(new Dimension(300, 300));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
final JLabel label = new JLabel("Update");
String[] data = { "one", "two", "three", "four" };
final JList dataList = new JList(data);
dataList.addListSelectionListener(new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent arg0) {
if (!arg0.getValueIsAdjusting()) {
label.setText(dataList.getSelectedValue().toString());
}
}
});
add(dataList);
add(label);
setVisible(true);
}
public static void main(String args[]) {
new JListDemo();
}
}
Why don't you put a ListSelectionListener on your JList, and add your above code in to it.
I'm assuming you already know how to create listeners on JButtons, based on your question, so you just need to tweak it to create a ListSelectionListener instead, then assign the listener to your JList using jlist.addListSelectionListener(myListener);
There is a nice tutorial here that should get you started, or refer to the documentation
You should be aiming for something like this...
jlist.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent event) {
if (!event.getValueIsAdjusting()){
JList source = (JList)event.getSource();
String selected = source.getSelectedValue().toString();
}
}
});
Use a ListSelectionListener:
JList list = new JList(...);
list.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent evt) {
if (!evt.getValueIsAdjusting()) {
// code here
}
}
});
I have a JCombobox with the large list of items. Upon selecting an Item, I need something done.
I tried with actionListener and with itemListner
myComboBox.addItemListener(new ItemListener(){
#Override
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
String selection = (String)myComboBox.getSelectedItem();
System.out.println("Selected: "+selection ) ;
}
}
});
With Action listener, I tried the same thing
The problem, I am facing is this
When user rolls through the open drop down he inadvertently keep selecting each item he does not need. (or if uses the mouse wheel, etc...).
So, I want to be able to catch ONLY that selection that user makes.
How can it be done ?
The problem, I am facing is this When user rolls through the open drop down he inadvertently keep selecting each item he does not need.
You can prevent the listener from firing by using:
comboBox.putClientProperty("JComboBox.isTableCellEditor", Boolean.TRUE);
For example:
/*
This works on non editable combo boxes
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.plaf.basic.*;
import javax.swing.text.*;
public class ComboBoxAction extends JFrame implements ActionListener
{
public ComboBoxAction()
{
JComboBox<String> comboBox = new JComboBox<String>();
comboBox.addActionListener( this );
comboBox.addItem( "Item 1" );
comboBox.addItem( "Item 2" );
comboBox.addItem( "Item 3" );
comboBox.addItem( "Item 4" );
// This prevents action events from being fired when the
// up/down arrow keys are used on the dropdown menu
comboBox.putClientProperty("JComboBox.isTableCellEditor", Boolean.TRUE);
getContentPane().add( comboBox );
getContentPane().add( new JTextField(), BorderLayout.SOUTH );
}
public void actionPerformed(ActionEvent e)
{
System.out.println( e.getModifiers() );
JComboBox comboBox = (JComboBox)e.getSource();
System.out.println( comboBox.getSelectedItem() );
// make sure popup is closed when 'isTableCellEditor' is used
// comboBox.hidePopup();
}
public static void main(String[] args)
{
ComboBoxAction frame = new ComboBoxAction();
frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
frame.pack();
frame.setVisible( true );
}
}
The problem, I am facing is this When user rolls through the open drop
down he inadvertently keep selecting each item he does not need.
Reason for that is, when press arraw up and down it is also state change. So my solution is you can add keyTyped actionListener. Then you can get the code for arrow key and check for arraw press. Like below:
myComboBox.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
String x = String.valueOf(myComboBox.getSelectedItem());
if(evt.getKeyCode() == 40) {
System.out.println(x);
//System.out.println(evt.getKeyCode());
}
}
});
Please use ActionListeners, like this:
combo.addActionListener (new ActionListener () {
public void actionPerformed(ActionEvent e) {
// doSomething();
}
});
I have a JList and each item of the JList has a distinct display text and tooltip text. I would like to use 'DefaultListModel' for the JList. My question is that is it possible to somehow save the tooltip text when added an item to the DefaultListModel.
Thanks.
You can override the getToolTipText(...) method to provide your custom tool tip.
For example:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ListToolTip extends JFrame
{
public ListToolTip()
{
DefaultListModel model = new DefaultListModel();
model.addElement("one");
model.addElement("two");
model.addElement("three");
model.addElement("four");
model.addElement("five");
model.addElement("six");
model.addElement("seven");
model.addElement("eight");
model.addElement("nine");
model.addElement("ten");
JList list = new JList( model )
{
public String getToolTipText( MouseEvent e )
{
int row = locationToIndex( e.getPoint() );
Object o = getModel().getElementAt(row);
return o.toString();
}
public Point getToolTipLocation(MouseEvent e)
{
int row = locationToIndex( e.getPoint() );
Rectangle r = getCellBounds(row, row);
return new Point(r.width, r.y);
}
};
JScrollPane scrollPane = new JScrollPane( list );
getContentPane().add( scrollPane );
}
public static void main(String[] args)
{
ListToolTip frame = new ListToolTip();
frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
frame.setSize(400, 100);
frame.setVisible( true );
}
}
Overriding getToolTipLocation(...) is not necessary.
Edit:
I want to save the custom text in the model
Then you would need to save a custom object in the model that contains the value displayed in the list and the text for the tooltip.
Check out ComboBox With Hidden Data for an example of creating an object using this approach.
I'm trying to use a compound Swing component as part of a Menu.
Everything works just fine, apart from one detail: The component contains JComboBoxes and whenever the user clicks on one of them to open its dropdown, the dropdown opens but the menu disappears. Is it possible to make the menu stay open when a JComboBox is clicked?
I sub-classed JMenu. This is the corresponding code:
public class FilterMenu extends JMenu {
public FilterMenu(String name) {
super(name);
final JPopupMenu pm = this.getPopupMenu();
final FilterPanel filterPanel = new FilterPanel(pm) {
#Override
public void updateTree() {
super.updateTree();
pm.pack();
}
};
pm.add(filterPanel);
}
}
FilterPanel is the custom compound component. The pm.pack() is called to adapt the size of the JPopupMenu when the filterPanel changes in size.
Thanks for your help
are you meaning this bug
import javax.swing.*;
import java.awt.event.*;
public class Test {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(400, 400);
frame.setVisible(true);
String[] list = {"1", "2", "3", "4",};
JComboBox comb = new JComboBox(list);
final JPopupMenu pop = new JPopupMenu();
pop.add(comb);
frame.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
System.out.println("mousePressed");
pop.show(e.getComponent(), e.getX(), e.getY());
}
});
}
}
Look at Jide OSS' PopupWindow. This provides an easy-to-use solution for this problem. Works fine for me.
Javadoc is here.
I am making an address book GUI with Java and I have a JList that displays all the names of the people in my ArrayList (this is populated by the updateinfo method mentioned below). I want it so when I click an item on the JList, the TextFields are then updated with that persons details. Before I have only used buttons and therefore actionListeners. I think I understand that a JList must use ListSelectionListener but I cannot seem to implement this. I have added a snippet of my code below. Can somebody please help?? For continuity with my actionlisteners I would like to have it as an inner class but this is not vital
JList jl;
DefaultListModel list;
list = new DefaultListModel();
this.jl = new JList(this.list);
//add ListSelectionListener????
updateList();
this.add(this.jl, layout);
You can add the listener and then just query the currently selected index.
I did a sample for you, I hope you find it useful.
This is the relevant section:
private JComponent list() {
final JList list = new JList( data);
list.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
int i = list.getSelectedIndex();
nameTextField.setText( i >= 0 ? data.get( i ) : "" );
}
});
return new JScrollPane( list );
}
Bear in mind that's not the only way to go, this is just an starting point for you.
Here's the complete working sample:
import java.util.Vector;
import java.util.Arrays;
import java.awt.BorderLayout;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JLabel;
import javax.swing.JComponent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.ListSelectionEvent;
public class JListSample {
private Vector<String> data = new Vector<String>(
Arrays.asList( new String [] {
"one", "two", "three"
})
);
private JTextField nameTextField;
public static void main( String [] args) {
JListSample s = new JListSample();
s.run();
}
public void run() {
JFrame frame = new JFrame("Selection test");
frame.add( list(), BorderLayout.WEST );
frame.add( editPanel() );
frame.pack();
frame.setVisible( true );
}
private JComponent list() {
final JList list = new JList( data);
list.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
int i = list.getSelectedIndex();
nameTextField.setText( i >= 0 ? data.get( i ) : "" );
}
});
return new JScrollPane( list );
}
private JComponent editPanel() {
JPanel panel = new JPanel();
panel.add( new JLabel("Name:") );
nameTextField = new JTextField(10);
panel.add( nameTextField );
return panel;
}
}
This is what is displayed:
sample http://img177.imageshack.us/img177/6294/capturadepantalla200911k.png
You just add the selection listener to the list, like that:
jl.addSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
// evaluate e if necessary and call a method
// in your class to write the text in the textfield
int selectedRow = e.getFirstIndex(); // more complicate for multiselects
updateTextFieldWithName(selectedRow); // to be implemented
}
});
Using an anonymous class like here is the quickest way. It's a bit hard to read but a typical pattern.
(just read you preferred an inner class, but I can't code that here on the fly with no IDE at hand...)
Yes you will want to use a ListSelectionListener for this, you will also probably want to set the list to single selection(ListSelectionModel.SINGLE_SELECTION). This will allow the user to only select one item in the list. You can then add you listSelectionListener, and in the valueChanged of the event do something like the following(not exact syntax).
valueChanged(ListSelectionEvent e){
int idx = e.getFirstIndex();
int idx2 = e.getLastIndex(); //idx and idx2 should be the same if you set SingleSel
if(idx==idx2){
//here you can get the person detail however you have them stored. You can get them from the model like so,
Object personObj = MYLIST.getModel().getElementAt(int index);
}
}
I think I understand that a JList must
use ListSelectionListener but I cannot
seem to implement this
Well, then start by reading the JList API. You will find a link to the Swing tutorial on "How to Use Lists", which contains a working example.
Also in the tutorial you will find a section on "How to Write a List Selection Listener" which contains a second example.
Start with the tutorial for your basic questions.