Add keybindings to a JList ?
Hi!
Is possible to add key bindings to a JList ? I want to
be able to delete selected list items with the DEL key. Similarly,
can I add a key binding to a JFrame to change its state ? I
want to change the fullscreen state of a frame with the
F11 key. Are KeyListeners suitable for these tasks ?
Thanks in advance
I ended up doing this for a JTable instead of a JList but it should work along the same lines.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
public class Keys
static JTable table;
static JScrollPane scrollPane;
static JFrame f;
public static void main(String[] args)
String[] headers = { "column 1", "column 2", "column 3", "column 4" };
String[][] data = new String[8][4];
for(int j = 0; j < data.length; j++)
for(int k = 0; k < data[0].length; k++)
data[j][k] = "item " + (j * data[0].length + k + 1);
DefaultTableModel model = new DefaultTableModel(data, headers);
table = new JTable(model);
table.setFocusable(true);
table.getInputMap().put(KeyStroke.getKeyStroke("DELETE"), "DELETE");
table.getActionMap().put("DELETE", deleteRow);
scrollPane = new JScrollPane(table);
scrollPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
KeyStroke.getKeyStroke("F11"), "F11");
scrollPane.getActionMap().put("F11", fullScreen);
GraphicsDevice gd = getScreenDevice();
f = new JFrame(gd.getDefaultConfiguration());
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(scrollPane);
f.setSize(400,400);
f.setLocation(200,200);
f.setVisible(true);
private static GraphicsDevice getScreenDevice()
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gd = ge.getDefaultScreenDevice();
return gd;
private static Action deleteRow = new AbstractAction()
public void actionPerformed(ActionEvent e)
DefaultTableModel model = (DefaultTableModel)table.getModel();
if(table.getSelectedRow() != -1)
model.removeRow(table.getSelectedRow());
private static Action fullScreen = new AbstractAction()
public void actionPerformed(ActionEvent e)
GraphicsDevice gd = getScreenDevice();
if(gd.getFullScreenWindow() == null)
JWindow w = new JWindow(f);
w.getContentPane().add(scrollPane);
gd.setFullScreenWindow(w);
w.validate();
else
gd.setFullScreenWindow(null);
f.getContentPane().add(scrollPane);
f.validate();
}
Similar Messages
-
How can I add the string to JList
I have one string " teletoppy" and I have Jlist which have 5 items in it.
After I press submit I want teletoppy added to the list.
How can I write the command?
because I try by using command_list.add("teletoppy", comp);
I don't know what component is?how can I add it in?.Read the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/components/list.html]How to Use Lists for a working example of how to do this. The "Hire" button adds the text from the text field to the JList.
-
How can I add several JButton into JList?
I want to add several button into a Jlist. I tried this method, list.add(button,1),nothing shows up.I am not sure whether jList has the function.If it is,please show me how to achieve that.Thanks in advance!
A JList is used to display text Strings. You should be able to add a JButton to the JList but all you will see is the toString() representation of the JButton. You will not see a button or be able to click on it.
Try creating a panel using a GridLayout with a single column and add all you JButtons to the panel. -
How to add rs.getString() into JList
for add inf rs.getString data into my JList , i m using ---
list.add(rs.getString(1));
but its throws an exception: java.lang.IllegalArgumentException: adding container's parent to itselfUse the DefaultListModel and setting this model of the JList.
here's a code snippet:
DefaultListModel model = new DefaultListModel()
model.addElement(elementToBeAdded);
jList.setModel(model); -
Add an entry to a JList ?
What is the simplest way to add another item, in my case a string, to a jlist? Thanks!
It was a pain in the rump trying to figure this one out, so I sympathize with your quest to figure out how to add things to JLists.
Try this:
( (DefaultListModel) myList.getModel() ).add(new String("hello, this is a new entry!"));This assums that your JList uses DefaultListModel as its ListModel, and automatically class-casts it to that, because the original JList getModel() method does not return a DefaultListModel - even though it IS the default list model. Just a quick tip!
Also, be sure to remember that you can add ANY Object to your JList. How it is "shown" in the JList depends on your Object's toString() method.
So if I have an Object called Entry...
public class Entry {
private String textualRepresentation = "AnEntry";
public Entry() { }
public String toString() {
return textualRepresentation;
}And add it to my JList via...
Entry entry = new Entry();
( (DefaultListModel) myList.getModel() ).add(entry);The JList will now have an item listed as "AnEntry", which is actually our Entry object.
Note that the JList will not update its display when you add the new Object.
To do this, you can either manually click on the list to change its selection, forcing a repaint, or resizing the window (accomplishing the same goal), or doing this:
SwingUtilities.updateComponentTreeUI(myList);Best of luck! -
hi
im a bit confused as to how to add items to a jlist during runtime
could someone please show an exampleHi,
Maybe this will help:
http://www.exampledepot.com/egs/javax.swing/list_ListAddRem.html?l=rel -
How i can add each item to JList. Using loop not use array?
I have not used a JList before, but looking at the API, one of the JLists constructors will take a Vector as one of it's argument
JList API http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/JList.html
constructor
JList(Vector listData) so you would be able to add elements to the vector in a loop using the add() method of the vector class
then construct the JList after the elements have been added to the vector, this will mean that you do not have to specify the size of the vector (all thought you can) as it will dynamically grow as you add items to it.
So if you don't know the amount of items that you will be adding to your JList to start with, it is a better bet than using an array
again have a look at the vector API http://java.sun.com/j2se/1.4.2/docs/api/java/util/Vector.html
hope that points you in the right direction
JaVAmUG3380 -
How to move items from one JList to other
Can u pls help me out to implement this(I m using Netbeans 5.5):
I want to move items from one JList to other thru a ADD button placed between JLists, I am able to add element on Right side JList but as soon as compiler encounter removeElementAt() it throws Array Index Out of Bound Exception
and if I use
removeElement() it removes all items from left side JList and returns value false.
Pls have a look at this code:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
Object selItem = jList1.getSelectedValue();
int selIndex = jList1.getSelectedIndex();
DefaultListModel model = new DefaultListModel();
jList2.setModel(model);
model.addElement(selItem);
DefaultListModel modelr = new DefaultListModel();
jList1.setModel(modelr);
flag = modelr.removeElement(selItem);
//modelr.removeElementAt(selIndex);
System.out.println(flag);
}hi Rodney_McKay,
Thanks for valuable time but my problem is as it is, pls have a look what I have done and what more can b done in this direction.
Here is the code:
import javax.swing.DefaultListModel;
import javax.swing.JList;
public class twoList extends javax.swing.JFrame {
/** Creates new form twoList */
public twoList() {
initComponents();
//The code shown below is automatically generated and we can�t edit this code
// <editor-fold defaultstate="collapsed" desc=" Generated Code ">
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
jList1 = new javax.swing.JList();
jButton1 = new javax.swing.JButton();
jScrollPane2 = new javax.swing.JScrollPane();
jList2 = new javax.swing.JList();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jList1.setModel(new javax.swing.AbstractListModel() {
String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
public int getSize() { return strings.length; }
public Object getElementAt(int i) { return strings[i]; }
jList1.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
jList1ValueChanged(evt);
jScrollPane1.setViewportView(jList1);
jButton1.setText("ADD>>");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
jScrollPane2.setViewportView(jList2);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(31, 31, 31)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(78, Short.MAX_VALUE))
layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jScrollPane1, jScrollPane2});
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(62, 62, 62)
.addComponent(jButton1))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addContainerGap(159, Short.MAX_VALUE))
layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {jScrollPane1, jScrollPane2});
pack();
}// </editor-fold>
//automatic code ends here
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
jList1 = new JList(new DefaultListModel());
jList2 = new JList(new DefaultListModel());
Object selItem = jList1.getSelectedValue();
System.out.println(selItem);
((DefaultListModel) jList1.getModel()).removeElement(selItem);
((DefaultListModel) jList2.getModel()).addElement(selItem);
//Now trying with this code it is neither adding or removing and the value �null� is coming in �selItem� .It may be bcoz JList and Jlist are already instantiated in automatic code. So, I tried this:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
Object selItem = jList1.getSelectedValue();
System.out.println(selItem);
((DefaultListModel) jList1.getModel()).removeElement(selItem);
((DefaultListModel) jList2.getModel()).addElement(selItem);
//Now with this as soon as I click on �jButton1�, it is throwing this error:
Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: twoList$1 cannot be cast to javax.swing.DefaultListModel
at twoList.jButton1ActionPerformed(twoList.java:105)
at twoList.access$100(twoList.java:13)
at twoList$3.actionPerformed(twoList.java:50)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
at java.awt.Component.processMouseEvent(Component.java:6038)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3260)
at java.awt.Component.processEvent(Component.java:5803)
at java.awt.Container.processEvent(Container.java:2058)
at java.awt.Component.dispatchEventImpl(Component.java:4410)
at java.awt.Container.dispatchEventImpl(Container.java:2116)
at java.awt.Component.dispatchEvent(Component.java:4240)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4322)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3986)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3916)
at java.awt.Container.dispatchEventImpl(Container.java:2102)
at java.awt.Window.dispatchEventImpl(Window.java:2429)
at java.awt.Component.dispatchEvent(Component.java:4240)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:173)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:121) -
Adding files from JFileChooser to Jlists
i have created a JList i am wondering how i can add files to this Jlist using a JFile chooser.
i need to add the actual file with the path and everything i also need to add the contents of a directory into the jList if selected in the Filechooser.
i have no problem creating a JFilechooser dialog.
please help me out.Hi,
I gave an example how to use the filechosser and filefilter [url http://forum.java.sun.com/thread.jsp?forum=57&thread=435432]here.
I think its also where you got the source code above.
Compactly and performable:import java.awt.*;
import java.awt.event.*;
import java.io.File;
import javax.swing.*;
import javax.swing.filechooser.FileFilter;
class Player2 extends JFrame
public static final int DELAY = 10;
JButton playButton;
private JButton Shuffle;
private JButton stopButton;
Timer playTimer;
private JLabel aMessage;
private JButton openButton;
JList playList = null;
JPanel aPanel;
JFileChooser theFileChooser = new JFileChooser();
AudioFileFilter filter = new AudioFileFilter();
JFrame win = new JFrame("AudioPlayer");
class playTimerListener extends AbstractAction
public void actionPerformed(ActionEvent e)
//myPlayer.play();
class OpenFileChooserAction extends AbstractAction
public void actionPerformed(ActionEvent e)
int retVal = theFileChooser.showOpenDialog(aPanel);
if (retVal == JFileChooser.APPROVE_OPTION)
File[] files = theFileChooser.getSelectedFiles();
DefaultListModel model = (DefaultListModel) playList.getModel();
model.clear();
for (int i = 0; i < files.length; i++)
if (files.isDirectory())
String[] filesInDirectory = files[i].list();
for (int ii = 0; ii < filesInDirectory.length; ii++)
File f = new File(files[i].getPath() + "/" + filesInDirectory[ii]);
//to prevent subdirectories to be added to the list
if (f.isFile() && filter.accept(f))
model.addElement(filesInDirectory[ii]);
else
if (filter.accept(files[i]))
model.addElement(files[i]);
class playButtonActionListener extends AbstractAction
public void actionPerformed(ActionEvent e)
System.out.println("Playing...");
playTimer.start();
class stopButtonActionListener extends AbstractAction
public void actionPerformed(ActionEvent e)
System.out.println("Stopped!");
playTimer.stop();
public Player2(String s)
super(s);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
playTimer = new Timer(DELAY, new playTimerListener());
theFileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
theFileChooser.setMultiSelectionEnabled(true);
theFileChooser.setFileFilter(filter);
theFileChooser.setFileHidingEnabled(false);
makeMyGUI();
pack();
show();
private void makeMyGUI()
aMessage = new JLabel("Nothing selected yet", JLabel.CENTER);
JScrollPane listScroll = new JScrollPane(playList = new JList(new DefaultListModel()));
listScroll.setPreferredSize(new Dimension(200, 200));
playList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
playButton = new JButton(new playButtonActionListener());
playButton.setText("play...");
stopButton = new JButton(new stopButtonActionListener());
stopButton.setText("stop...");
openButton = new JButton(new OpenFileChooserAction());
openButton.setText("Open...");
openButton.setBackground(Color.yellow);
Shuffle = new JButton("Shuffle");
aPanel = new JPanel();
aPanel.setBackground(Color.blue);
aPanel.add(openButton);
aPanel.add(playButton);
aPanel.add(stopButton);
getContentPane().add(listScroll, "Center");
getContentPane().add(aPanel, "North");
getContentPane().add(aMessage, "South");
class AudioFileFilter extends FileFilter
public boolean accept(File f)
if (f.isDirectory())
return true;
String extension = Utils.getExtension(f);
if (extension != null)
if (extension.equals(Utils.wav)
|| extension.equals(Utils.aif)
|| extension.equals(Utils.rmf)
|| extension.equals(Utils.au)
|| extension.equals(Utils.mid))
return true;
else
return false;
return false;
public String getDescription()
return "wav, aif, rmf, au and mid";
public static void main(String[] args)
try
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
catch (Exception e)
e.printStackTrace();
new Player2("MP3 PLAYER");
class Utils
public final static String wav = "wav";
public final static String aif = "aif";
public final static String rmf = "rmf";
public final static String au = "au";
public final static String mid = "mid";
* Get the extension of a file.
public static String getExtension(File f)
String ext = null;
String s = f.getName();
int i = s.lastIndexOf('.');
if (i > 0 && i < s.length() - 1)
ext = s.substring(i + 1).toLowerCase();
return ext;
//without formatting
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import javax.swing.*;
import javax.swing.filechooser.FileFilter;
class Player2 extends JFrame
public static final int DELAY = 10;
JButton playButton;
private JButton Shuffle;
private JButton stopButton;
Timer playTimer;
private JLabel aMessage;
private JButton openButton;
JList playList = null;
JPanel aPanel;
JFileChooser theFileChooser = new JFileChooser();
AudioFileFilter filter = new AudioFileFilter();
JFrame win = new JFrame("AudioPlayer");
class playTimerListener extends AbstractAction
public void actionPerformed(ActionEvent e)
//myPlayer.play();
class OpenFileChooserAction extends AbstractAction
public void actionPerformed(ActionEvent e)
int retVal = theFileChooser.showOpenDialog(aPanel);
if (retVal == JFileChooser.APPROVE_OPTION)
File[] files = theFileChooser.getSelectedFiles();
DefaultListModel model = (DefaultListModel) playList.getModel();
model.clear();
for (int i = 0; i < files.length; i++)
if (files[i].isDirectory())
String[] filesInDirectory = files[i].list();
for (int ii = 0; ii < filesInDirectory.length; ii++)
File f = new File(files[i].getPath() + "/" + filesInDirectory[ii]);
//to prevent subdirectories to be added to the list
if (f.isFile() && filter.accept(f))
model.addElement(filesInDirectory[ii]);
else
if (filter.accept(files[i]))
model.addElement(files[i]);
class playButtonActionListener extends AbstractAction
public void actionPerformed(ActionEvent e)
System.out.println("Playing...");
playTimer.start();
class stopButtonActionListener extends AbstractAction
public void actionPerformed(ActionEvent e)
System.out.println("Stopped!");
playTimer.stop();
public Player2(String s)
super(s);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
playTimer = new Timer(DELAY, new playTimerListener());
theFileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
theFileChooser.setMultiSelectionEnabled(true);
theFileChooser.setFileFilter(filter);
theFileChooser.setFileHidingEnabled(false);
makeMyGUI();
pack();
show();
private void makeMyGUI()
aMessage = new JLabel("Nothing selected yet", JLabel.CENTER);
JScrollPane listScroll = new JScrollPane(playList = new JList(new DefaultListModel()));
listScroll.setPreferredSize(new Dimension(200, 200));
playList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
playButton = new JButton(new playButtonActionListener());
playButton.setText("play...");
stopButton = new JButton(new stopButtonActionListener());
stopButton.setText("stop...");
openButton = new JButton(new OpenFileChooserAction());
openButton.setText("Open...");
openButton.setBackground(Color.yellow);
Shuffle = new JButton("Shuffle");
aPanel = new JPanel();
aPanel.setBackground(Color.blue);
aPanel.add(openButton);
aPanel.add(playButton);
aPanel.add(stopButton);
getContentPane().add(listScroll, "Center");
getContentPane().add(aPanel, "North");
getContentPane().add(aMessage, "South");
class AudioFileFilter extends FileFilter
public boolean accept(File f)
if (f.isDirectory())
return true;
String extension = Utils.getExtension(f);
if (extension != null)
if (extension.equals(Utils.wav)
|| extension.equals(Utils.aif)
|| extension.equals(Utils.rmf)
|| extension.equals(Utils.au)
|| extension.equals(Utils.mid))
return true;
else
return false;
return false;
public String getDescription()
return "wav, aif, rmf, au and mid";
public static void main(String[] args)
try
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
catch (Exception e)
e.printStackTrace();
new Player2("MP3 PLAYER");
class Utils
public final static String wav = "wav";
public final static String aif = "aif";
public final static String rmf = "rmf";
public final static String au = "au";
public final static String mid = "mid";
* Get the extension of a file.
public static String getExtension(File f)
String ext = null;
String s = f.getName();
int i = s.lastIndexOf('.');
if (i > 0 && i < s.length() - 1)
ext = s.substring(i + 1).toLowerCase();
return ext;
//Tim -
Click an item twice or more 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);
}Morten,
I have since found that the problem is related to the .DS_store files. If you delete it from the parent folder, the ghost disapears. I found a little application that does this and is easy to use, it's called "DS_Store cleaner" and it's free. It doesn't solve the problem for the future though, but it might illimenate any corrupted .DS_Store files on the server.
Another thing I read, but didn't implement because of the side effects is to set the clients to NOT write the DS_Store on the server. This of corse means that they won't have their settings kept when reopening the folder, that's why I didn't implement it yet, still need to see if it's worth it.
Here is the URL from Apple tech note
http://docs.info.apple.com/article.html?artnum=301711
Keep me posted
Jeff -
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. -
Stop "Ctrl-Page Down" in a JList but propergate the event
Hi all. I have a JList inside a tabbed pane.
On my tabbed pane I have hot keys such that Ctrl-Page Up and Ctrl-Page Down change the tab. This works fine except when a JList has focus in the tab.
When I press Ctrl-Page Up or Page Down on the JList I don't want it do anything and I would like the tab to change as expected.
If I add this to my JList:
list.getInputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_DOWN, InputEvent.CTRL_DOWN_MASK), "none")it stops my JList from reacting to the Ctrl-Page Down but it doesn't propergate it up to the tabbed pane.
Does anyone know how I can do this?
Thanks, Nick.Hi guys. Thanks for the responses but it still isn't working.
I changed my component to this:
list.getInputMap(JComponent.WHEN_FOCUSED).getParent().remove(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_DOWN, InputEvent.CTRL_DOWN_MASK));and it does remove the ctrl-page down from the JList. However, it still isn't being propergated to the JTabbedPane.
In case it helps, this is how I'm adding the action in the tabbed pane:
tabbed.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_DOWN, InputEvent.CTRL_DOWN_MASK), "nextTabAction");Am I doing something wrong?
Thanks, Nick. -
Hi
I wonder if it is possible to add JButton in a JList? Or how can I produce a list of JButtons? Each button represents a person (an object), is there anyway to add listener to the buttons so i can get the person thats represnted by the button? I can decide in advance how many button ther will be...that depends on the number of person in the db.Use a panel with a GridLayout. The Panel can be added to a JScrollPane. Read this section on "Layout Managers":
http://java.sun.com/docs/books/tutorial/uiswing/layout/using.html -
Addition in JList???
Can anyboty post a snippet on how to add numbers inside a JList?
(the list accepts only numbers)
In a textfield, the sum will be displayed.
thanksYou could use Integer objects I guess.
JList yourList = new JList(new DefaultListModel());
DefaultListModel mod = (DefaultListModel)yourList.getModel();
// Just add some numbers
for(int i = 1; i <= 10; i++)
mod.addElement(new Integer(i)); -
I'm just messing around trying to get a JList to show work, but it won't show up. I've been going off the JList tutorial at http://java.sun.com/docs/books/tutorial/uiswing/components/list.html
but I don't know what I'm doing wrong.
private class FileListPanel extends JPanel{
public FileListPanel(){
String[] arr = {";laskdfj","asdf"};
JList fileList = new JList(arr);
add(fileList);
fileList.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
fileList.setLayoutOrientation(JList.HORIZONTAL_WRAP);
fileList.setVisible(true);
fileList.setVisibleRowCount(-1);
fileList.setSelectedIndex(1);
JScrollPane listScroller = new JScrollPane(fileList);
listScroller.setPreferredSize(new Dimension(100,100));
listScroller.setAlignmentX(LEFT_ALIGNMENT);
}and I'm calling that from the constructor for the class using
Container gcp = getContentPane();
gcp.setLayout(new BorderLayout());
gcp.add(new FileListPanel(), BorderLayout.CENTER);
...In situations like this, you're shooting yourself in the foot if you don't post a SSCCE. Demo:
import java.awt.*;
import javax.swing.*;
public class JListExample {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable(){
public void run() {
launch();
static void launch() {
String[] data = {"aaa","bbb","ccc","ddd","eee",
"fff","ggg","hhh","iii","jjj"};
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new JScrollPane(new JList(data)));
f.setSize(100,100);
f.setLocationRelativeTo(null);
f.setVisible(true);
}And in the future, please post Swing questions to the Swing forum.
Maybe you are looking for
-
EVDRE Expansion depending on Property of members
Hi All, I am developing a report which will give me data for specific property of the members and at different levels. Let me explain it more... We have a dimension PROJ which has one property Bill_to. This property is set to child projects only. So
-
Harri
-
Installed new SSD boot drive, Time Machine won't backup
I installed a new 240 GB SSD boot drive (cloned using Super Duper) in my Mac Pro and want to use it as my startup disk. When I boot up using the new 240 SSD drive and try to start Time Machine to back it up onto a 500GB external drive it tells me it
-
How to create a button to load an external exe file
hi i have an flash cs5 project so the user when clicking the button the exe file open ? the exe in folder name "puzz" the exe file name play.exe i tried this button_1.addEventListener(MouseEvent.CLICK, fl_MouseClickHandler); function fl_Mo
-
Does the account holder have to go with you to get a 4g LTE sim card?
The sim card in my son's thunderbolt messed up a few days ago and he has his license but he's only 16. Would it be possible for him to go to the Verizon store and get another sim card? Or does the person going have to be 18 and up? Thanks in advance