How can I keep the selectedIndex of two JLists the same?

I have two independant JLists. I have one button to add items from two textfields to the lists. I also have one button to remove the selected items from the lists. However because the items in both JLists are related I want to make sure the selected index of one is always equal to the selected index of the other. HOW!

OK, so here is the current code, there must be an easy way to do it, Swing gurus please help.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
public class ListDemo extends JFrame
                      implements ListSelectionListener {
    private JList list;
    private JList list2;
    private DefaultListModel listModel;
    private DefaultListModel listModel2;
    private static final String hireString = "Add";
    private static final String fireString = "Remove";
    private JButton fireButton;
    private JTextField employeeName;
    private JTextField percent;
    private JSlider per;
    public ListDemo() {
        super("ListDemo");
        listModel = new DefaultListModel();
        listModel.addElement("Alison Huml");
        listModel.addElement("Kathy Walrath");
        listModel.addElement("Lisa Friendly");
        listModel.addElement("Mary Campione");
        listModel2 = new DefaultListModel();
        listModel2.addElement("100");
        listModel2.addElement("80");
        listModel2.addElement("50");
        listModel2.addElement("10");
        //Create the list and put it in a scroll pane
        list = new JList(listModel);
        list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        list.setSelectedIndex(0);
        list.addListSelectionListener(this);
        JScrollPane listScrollPane = new JScrollPane(list);
        //Create the percentlist and put it in a scroll pane
        list2 = new JList(listModel2);
        list2.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        list2.setSelectedIndex(0);
        list2.addListSelectionListener(this);
        JScrollPane listScrollPane2 = new JScrollPane(list2);
        JButton hireButton = new JButton(hireString);
        hireButton.setActionCommand(hireString);
        hireButton.addActionListener(new HireListener());
        fireButton = new JButton(fireString);
        fireButton.setActionCommand(fireString);
        fireButton.addActionListener(new FireListener());
        employeeName = new JTextField(10);
        employeeName.addActionListener(new HireListener());
        String name = listModel.getElementAt(
                              list.getSelectedIndex()).toString();
        employeeName.setText(name);
        per = new JSlider(JSlider.HORIZONTAL, 0, 100, 50);
        per.setMajorTickSpacing(10);
        per.setPaintTicks(true);
        per.setPaintLabels(true);
        percent = new TextField(10);
        percent.setValue(new Integer(1));
        percent.addActionListener(new HireListener());
        String name2 = listModel2.getElementAt(
                              list2.getSelectedIndex()).toString();
        percent.setText(name2);
        //Create a panel that uses FlowLayout (the default).
        JPanel buttonPane = new JPanel();
        buttonPane.add(employeeName);
        buttonPane.add(per);
        buttonPane.add(hireButton);
        buttonPane.add(fireButton);
        Container contentPane = getContentPane();
        contentPane.add(listScrollPane, BorderLayout.CENTER);
        contentPane.add(listScrollPane2, BorderLayout.EAST);
        contentPane.add(buttonPane, BorderLayout.SOUTH);
    class FireListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            //This method can be called only if
            //there's a valid selection
            //so go ahead and remove whatever's selected.
            int index = list.getSelectedIndex();
            int index2 = list2.getSelectedIndex();
            listModel.remove(index);
            listModel2.remove(index2);
            int size = listModel.getSize();
            int size2 = listModel2.getSize();
            if (size == 0) {
            //Nobody's left, disable firing.
                fireButton.setEnabled(false);
            } else {
            //Adjust the selection.
                if (index == listModel.getSize())//removed item in last position
                    index--;
                list.setSelectedIndex(index);   //otherwise select same index
            if (size2 == 0) {
            //Nobody's left, disable firing.
                fireButton.setEnabled(false);
            } else {
            //Adjust the selection.
                if (index2 == listModel2.getSize())//removed item in last position
                    index2--;
                list2.setSelectedIndex(index2);   //otherwise select same index
    //This listener is shared by the text field and the hire button
    class HireListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            //User didn't type in a name...
            if (employeeName.getText().equals("")) {
                Toolkit.getDefaultToolkit().beep();
                return;
            //User didn't type in a percent...
            if (percent.getText().equals("")) {
                Toolkit.getDefaultToolkit().beep();
                return;
            int index = list.getSelectedIndex();
            int index2 = list2.getSelectedIndex();
            int size = listModel.getSize();
            int size2 = listModel2.getSize();
            //If no selection or if item in last position is selected,
            //add the new hire to end of list, and select new hire.
            if (index == -1 || (index+1 == size)) {
                listModel.addElement(employeeName.getText());
                list.setSelectedIndex(size);
            //Otherwise insert the new hire after the current selection,
            //and select new hire.
            } else {
                listModel.insertElementAt(employeeName.getText(), index+1);
                list.setSelectedIndex(index+1);
            //If no selection or if item in last position is selected,
            //add the new hire to end of list, and select new hire.
            if (index2 == -1 || (index2+1 == size2)) {
                listModel2.addElement(String.valueOf(per.getValue()));
                list2.setSelectedIndex(size2);
            //Otherwise insert the new hire after the current selection,
            //and select new hire.
            } else {
                listModel2.insertElementAt(String.valueOf(per.getValue()), index2+1);
                list2.setSelectedIndex(index2+1);
    public void valueChanged(ListSelectionEvent e) {
        if (e.getValueIsAdjusting() == false) {
            if (list.getSelectedIndex() == -1) {
            //No selection, disable fire button.
                fireButton.setEnabled(false);
                employeeName.setText("");
            } else {
            //Selection, update text field.
                fireButton.setEnabled(true);
                String name = list.getSelectedValue().toString();
                employeeName.setText(name);
            if (list2.getSelectedIndex() == -1) {
            //No selection, disable fire button.
                fireButton.setEnabled(false);
//                percent.setText("");
            } else {
            //Selection, update text field.
                fireButton.setEnabled(true);
                String name = list2.getSelectedValue().toString();
//                percent.setText(name);
    public static void main(String s[]) {
        JFrame frame = new ListDemo();
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);
        frame.pack();
        frame.setVisible(true);
}

Similar Messages

  • I am doing two people's jobs and I need to use two separate log-ins on the same website. How can I keep both log-ins open at the same time. Everytime I switch tabs I have to log in again.

    I am doing two people's jobs and I need to use two separate log-ins on the same website. How can I keep both log-ins open at the same time. Everytime I switch tabs I have to log in again.

    Try one of these extensions for multiple cookie sessions.
    Multifox: <br />
    http://br.mozdev.org/multifox/ <br />
    Cookie Swap extension: <br />
    https://addons.mozilla.org/firefox/3255/ <br />
    Cookie Pie extension: <br />
    http://www.nektra.com/oss/firefox/extensions/cookiepie/

  • How can I keep synchronized my macbook pro at the office and a traveling macbook air?

    How can I keep synchronized my macbook pro at the office and a traveling macbook air?

    Have you tried doing the sync via Time Machine?
    I thought it would be possible to backup the travelling machine and restore the machine at the office from the new backup.
    I read a warning from Apple that it is not advisable.
    I would be very interested in your opinion.

  • Flash Builder 4.6 - How can I keep unit test classes out of the finished swc?

         I have a library of code I'm building and I'm working on unit testing but I have a major issue. When my finished swc compiles no matter what I do it includes the unit test classes as part of the intellisense if you load the swc via flash. The classes aren't really in the swc since if you just try and import them they'll come up undefined. They only appear to go into the intellisense for the swc. Does anyone know how can I keep this from happening in the finished source? Currently my folder setup is like this in flash builder.
    src\main - source documents for the library to get compiled
    src\mock - mock class area for unit testing
    src\test - unit test classes
         In the project Properties panel > the first tab of my Flex Library Build path I have selected only the src\main folder for the classes to inlude in the library. No other folder paths are selected.
    The "Flex Library Build Path" doesn't change my results with any setting.
    Thanks,

    Mel Riffe,
    Here's a Help topic about compiler options in Flash Builder: http://help.adobe.com/en_US/flashbuilder/using/WSe4e4b720da9dedb524b8220812e5611f28f-7fe7. html
    For information on using mxmlc, the application compiler, to compile SWF files from your ActionScript and MXML source files, you can see: http://help.adobe.com/en_US/flex/using/WS2db454920e96a9e51e63e3d11c0bf69084-7fcc.html
    Hope this helps,
    Mallika Yelandur
    Flash Builder Community Help & Learning
    Adobe Systems Incorporated

  • How can I keep iTunes on my Mac but the Movies on an external hard drive and still have them accessible to my Apple TV etc through Home Sharing?

    I have a 2TB external hard drive that I want to store my ripped movies on and free up space on my Mac. How can I do this?

    Is there a reason you don't want to keep your entire iTunes folder on the external.
    Everything will work just fine and it is simpler if everything in iTunes is in one location (the iTunes folder).
    Copy entire /Music/iTunes/ folder to external.
    Hold Option and launch iTunes.
    Select Choose library... and select the iTunes folder on the external.
    That is all you need to do.

  • How can I keep all of my students on the same page in an iBook?

    My school is in the process of giving each student an iPad Mini, one grade at a time. As a ninth grade teacher, all of my students have one, but we are having some trouble staying on the same page  when we are reading a novel ( no pun intended ). What I mean is that what appears on page fifty for me will appear on page forty for one student and on page sixty for another. I tried to fix this by having all of my students keeping their iPads in landscape orientation, but that did not solve the issue. I then tried to have students adjust the size the font on their books so we would have a uniform text, but the tool for adjusting the size images this tricky as well.
    I am considering having all of my students make their font size as small as possible and then giving them a specific number of times to tap on the font increase, but I am hoping to find a simpler method. Am I overlooking something?
    I would appreciate any tips that you might have.

    You can render the ebook on an instructional application called Zankura. Not only can you control the screen scrolling, but all the students can freely annotate with their stylus. www.zankura.com.

  • How can I keep AppleScript repeat resetting Safari in the background?

    I want to have an AppleScript which resets Safari every 10 seconds. Now I got a problem with repeating the script. After the script resets Safari it closes the app. I want to keep Safari open while the script is operating in the background.
    That was my try:
    =================
    tell application "Safari" to launch
              tell application "Safari" to activate
              tell application "Safari" to open location "http://www.apple.com"
    repeat
              tell application "Safari" to close every window
              try
                        tell application "Safari" to quit
              on error errmsg
                        display dialog "Safari App beenden gescheitert" with icon caution
              end try
              try
                        do shell script "rm -f ~/Library/Safari/history.plist"
              on error errmsg
                        display dialog "history.plist löschen gescheitert" with icon caution
              end try
              try
                        do shell script "rm -f ~/Library/Safari/HistoryIndex.sk"
              on error errmsg
                        display dialog "HistoryIndex.sk löschen gescheitert" with icon caution
              end try
              try
                        do shell script "rm -f ~/Library/Caches/com.apple.Safari/Cache.db"
              on error errmsg
                        display dialog "Cache.db löschen gescheitert" with icon caution
              end try
              try
                        do shell script "rm -rf ~/Library/Caches/Metadata/Safari/History"
              on error errmsg
                        display dialog "History löschen gescheitert" with icon caution
              end try
              try
                        do shell script "rm -f ~/Library/Cookies/Cookies.plist"
              on error errmsg
                        display dialog "Cookies.plist löschen gescheitert" with icon caution
              end try
              try
                        do shell script "rm -f ~/Library/Safari/LastSession.plist"
              on error errmsg
                        display dialog "LastSession.plist löschen gescheitert" with icon caution
              end try
              try
                        do shell script "rm -f ~/Library/Safari/TopSites.plist"
              on error errmsg
                        display dialog "TopSites.plist löschen gescheitert" with icon caution
              end try
              try
                        do shell script "rm -rf ~/Library/Caches/com.Apple.Safari/*"
              on error errmsg
                        display dialog "Safari Cache löschen gescheitert" with icon caution
              end try
              try
                        do shell script "rm -f ~/Library/Caches/Adobe/Flash Player/AssetCache"
              on error errmsg
                        display dialog "Flash Player AssetCache löschen gescheitert" with icon caution
              end try
              try
                        do shell script "rm -rf ~/Library/Preferences/Macromedia/Flash*/macromedia.com/support/flashplayer/sys/ #*"
              on error errmsg
                        display dialog "Flash Player macromedia.com löschen gescheitert" with icon caution
              end try
              try
                        do shell script "rm -rf ~/Library/Preferences/Macromedia/Flash*/#SharedObjects/*"
              on error errmsg
                        display dialog "Flash Player #SharedObjects löschen gescheitert" with icon caution
              end try
      delay 10
    end repeat
    =================
    PS: The dialogues are in German… But that shouldn't be a problem

    You can use the applescript Script Menu to run scripts in Photoshop (or any application).
    If you don't have it installed, run the AppleScript Utility.app (find it in the Applescript folder in your applications folder) and make sure the 'Show Script Menu in menu bar' is checked.
    Edit: I thought you'd be able to use this with an action by inserting a menu item, but apparently it doesn't recognize the appescript menu.

  • TS3274 How can I keep my items on 'Reminders' in the order that I enter them?

    ...they won't stay in the place that I put them.

    You sure shouldn't have to do anything special. And I assume that you mean they don't stay in the order that you type them or arrange them afterward.
    I can't think of any reason why they would be jumping out of order, and really can't think of what to do to correct it, so try something really simple and basic. Close the reminders app and reboot the iPad.
    Double tap the home button and you will see apps lined up going left to right across the screen. Swipe to get to the app that you want to close and then swipe "up" on the app preview thumbnail to close it.
    Reboot the iPad by holding down on the sleep and home buttons at the same time for about 10-15 seconds until the Apple Logo appears - ignore the red slider if it appears on the screen - let go of the buttons. Let the iPad start up.

  • How can I keep just one of two accounts offline in Mac Mail?

    I recently switched from Comcast to Cox Cable. Cox has a known issue with push notifications and email doesn't show up at regular intervals. You have to go offline and back on or quit Mail and then open it again to see new messages. It's a pain but it works.
    I still have my Comcast email account enabled on Mac Mail because I need access to old emails and if I disable it (via Preferences), it disappears. I want to take it offline but clicking on the Comcast account and "take comcast.net offline" always takes my Cox account offline as well. I can't get them to both stay online because the Comcast account hangs when it can't connect to Comcast. This really exacerbates the already annoying issue of having to take Cox offline and back on.
    I tried going into the Comcast account via Preferences and unchecking "include when automatically checking for new messages" but when I did so, it kept the Cox account from receiving any messages at all (I confirmed this by checking webmail, and by toggling it on and off to see what happened).
    I need some solution that allows me to see the comcast account in mail without having it be active in any way. I have other mailboxes archived but that process doesn't offer the search capability that I need.

    Aha! I have been doing just that. However, what has been tripping me up is that I am also used to clicking the Go Online/Go Offline toggle button on the top menu bar when I manually check for messages on Cox. Apparently when you take one inbox offline, that button switches to Off even though the other inbox is still online. If I just ignore that button and go on or off via the cox mailbox listing, it keeps comcast from being reactivated.
    Thanks so much for helping me think this through.
    Edited to add: I removed that dang button from my menu so I can stop clicking it.

  • How can I keep my iPod Touch cool in the sun?

    So I am going on holiday at the end of this week camping abroad where it will be hot and I am planning to take my iPod touch with me so I can access my music, emails, Facebook, Twitter, Skype etc. I am slightly concerned that iPod touch will be damaged by the heat as it can get very hot in the tent and car and also on the beach in direct sun. I had a heat warning the other week from leaving it on the table in the garden in the 30 degrees sun (yes that was silly of me!) It has a Zagg screen protector and a basic black skin. It is an iPod touch 4th generation. Is there any way of protecting from sunlight and heat? Also is there an app to download that will read the iPods current temperature and what is its maximum temperature it can withstand to?

    All you can do is keep it shaded and not in a unventilated space (like a car or tent) exposed to the sun.
    There is no temperature app.
    Hot temperatures can permently damage the iPod, especially the battery.

  • How can I keep music playing longer without using the web.

    I listen to siriusxm through the web. After about 20 min the system turns off if I do nothing on the web. How I fix this?

    You need to keep your computer from going to sleep. this is a windows setting and not a Firefox one, but here is something to point you in the right direction:
    http://windows.microsoft.com/en-us/windows7/sleep-and-hibernation-frequently-asked-questions

  • How can I keep a network drive mounted all the time?

    I have a Mac Mini hooked to my TV which is running Boxee. All of the videos/music is pulled from a network drive.
    I have the drive set up to mount on Mac boot by putting it in my start up items. The problem I am running into is sometimes the drive will go offline or I may have to reboot it for one reason or another. When this happens the Mac Mini looses the mounted drive and I have to reboot the computer.
    What I need is some kind of application that sits in the background and constantly checks to see if the drive is mounted and if it is not it mounts it again for me like it does on start up.
    Any Ideas???

    Cron isn't used by OS X anymore, launchd handles scheduled tasks now, but you could still use cron if you wanted to schedule a task. This is a good place to start: http://hints.macworld.com/article.php?story=2001020700163714
    You can definitely set up a launchd daemon, but it might be pretty complicated if you've never done it, it also may be more than you want to invest in this particular issue. Read about it here:
    http://developer.apple.com/library/mac/#documentation/MacOSX/Conceptual/BPSystem Startup/Articles/LaunchOnDemandDaemons.html
    I've also seen people recommend just setting an event to repeat in iCal. For the event, add an alarm, and as the alarm, tell it to run a script. Have the event repeat as often as you like, indefinitely. That, my friend, is a poor man's scheduled task solution.

  • How can you keep full view of Safari on the screen when it opens up?

    Can't see full view of Safari when I start it up.

    System Preferences > General
    Uncheck the box next to    "Close windows windows when quitting an application".

  • How can I keep tracks playing when I'm browsing?

    There must be an obvious answer to this question, but I don't know what it is.
    If I'm playing an album, but then start to browse somewhere else (as one would do if listening to a CD), the music will stop after the track has finished, and not go on to the next track. (because the tracks are no longer in the browser window)
    How can I keep playing what I want, in the order that I want, while I am browsing other music?
    Thanks

    I find this to be a problem as well, especially since I know I was able to work with iTunes this way before I installed iTunes 7.3?
    I'm reading some other posts which suggest that being able to play tracks from an library subset (genre, album, artist) AND browse other playlists at the same time was never a feature of iTunes.
    Since I know I'm not imagining that I used to use iTunes quite happily, I'm wondering is there an option in 7.3 that I'm not paying attention to?
    It seems crazy not to be able to do this.

  • I have a new Iphone 5, my wife has a 4S and an iPod Touch.  When I sync my new 5 to the Mac, it pick up ALL of the stupid game apps that my wife uses on her two devices.  How can I keep them separate?

    I have a new Iphone 5, my wife has a 4S and an iPod Touch.  When I sync my new 5 to the Mac, it pick up ALL of the stupid game apps that my wife uses on her two devices.  How can I keep them separate?

    go to itunes preferences, store, uncheck automatic downloads. also when your phone is connected you can click  on apps and only check the ones you want on your phone, go down to the bottom right and click apply.

Maybe you are looking for

  • Yosemite dictation not working in safari and others

    I was using dictation in all apps until recently. now it only works in Mail. I've tried turning it off, restart, on, restart. Not working. Any suggestions?

  • SOA INFRA Not Coming Up

    Hello, I have installed SOA 11.1.1.5. Both Admin & SOA Servers are UP, but soa-infra is still down. I have deleted tmp folder in /var/tmp/ and Then I deleted tmp folder in servers/admin server, but still the issue exists. ERROR: ###<Nov 6, 2012 7:39:

  • Personal development Issue

    I come from a web development background. I've persuaded "upstairs" to allow me to build a small Java component to our product but I'm having trouble getting them to invest in training. Since we are a Microsoft house I would probably get a lot more r

  • Obscured Labels - Graphs and tab controls

    In LV 2012 new options (Preferences or Options on the Mac) allow placing labels on new controls and indicators in various positions. I have noticed that for graphs and tab controls some of the options result in obscured labels.  See the image below.

  • Multiple Speakers goes Wonky when using a wireless bridge

    I used to use multiple speakers on iTunes, but lost a lot of connections to the AE due to distance. My WLAN is a D-LINK DI-624. I put in a DLINK DWL-G710 bridge (it took about 3 hours to get working, not 2 minutes, as they claim). Now, I can always S