Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7987997
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 4, 20262026-06-04T12:18:31+00:00 2026-06-04T12:18:31+00:00

I’ve got a problem connected with my previous question: JList: sorting by Up/down buttons

  • 0

I’ve got a problem connected with my previous question: JList: sorting by Up/down buttons
My Up/Down buttons work properly now, but here’s the other thing:
I need to make Top/Bottom buttons also. They seem to be harder. I use actionPerformed to button “Top”:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
 int indexOfSelected = jList1.getSelectedIndex();
 swapElements2(indexOfSelected, 0);
 indexOfSelected = 0;
 jList1.setSelectedIndex(indexOfSelected );
 jList1.updateUI();
}

And swapElements2 method looks like that:

private void swapElements2(int pos1, int pos2) {
  String tmp1 =  (String) listModel.get(pos1);
  String tmp2 =  (String) listModel.get(pos2);
  listModel = (DefaultListModel) jList1.getModel();
  int sizeOfList = listModel.getSize();

  listModel.set(pos2, listModel.get(sizeOfList-1));
  for (int i=sizeOfList-2;i>0;i--){
    listModel.set(i+1, listModel.get(i));
  }

  listModel.set(pos2, tmp1);
  listModel.set(pos2+1, tmp2);
}

Of course, it works only if the last element of jList is selected. Has anyone an idea how to make an universal method which will move the element from selected position to 0 position? Method should also move all other elements forwards and the last element should stay at it’s place if it’s not selected.

I’d be grateful for any help.

Edit from comments, which also doesn’t work:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
 String temp = (String) listModel.remove(jList1.getSelectedIndex());
 listModel.add(0, temp);
}

Error:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
name podziwiaj.jpg
at java.io.File.<init>(File.java:222)

Which is:

public File(String pathname) {
if (pathname == null) {
    throw new NullPointerException();
}
this.path = fs.normalize(pathname);
this.prefixLength = fs.prefixLength(this.path);
}

List stores path names of files (images) and displays is, when item is selected.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-04T12:18:33+00:00Added an answer on June 4, 2026 at 12:18 pm

    My own preference is to work with the list’s model to do this. Something like:

    DefaultListModel model = (DefaultListModel)jList1.getModel();
    File temp = model.remove(jList1.getSelectedIndex());
    model.add(0, temp);
    

    To see what methods are available to the list’s model, please check out the DefaultListModel API.

    Edit: code works fine.

    Edit 2: My sscce

    import java.awt.event.ActionEvent;
    import javax.swing.*;
    
    public class TestList {
    
       private static void createAndShowGui() {
          String[] data = {"Mon", "Tues", "Wed", "Thurs", "Fri", "Sat", "Sun"};
          final DefaultListModel<String> model = new DefaultListModel<String>();
          for (String datum : data) {
             model.addElement(datum);
          }
          final JList<String> myList = new JList<String>(model);      
          JButton toTop = new JButton(new AbstractAction("To Top") {
    
             @Override
             public void actionPerformed(ActionEvent arg0) {
                int selectedIndex = myList.getSelectedIndex();
                if (selectedIndex < 0) {
                   return;
                }
                String temp = model.remove(selectedIndex);
                model.add(0, temp);
             }
          });
    
    
    
          JPanel mainPanel = new JPanel();
          mainPanel.add(new JScrollPane(myList));
          mainPanel.add(toTop);
    
    
          JFrame frame = new JFrame("TestList");
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.getContentPane().add(mainPanel);
          frame.pack();
          frame.setLocationByPlatform(true);
          frame.setVisible(true);
       }
    
       public static void main(String[] args) {
          SwingUtilities.invokeLater(new Runnable() {
             public void run() {
                createAndShowGui();
             }
          });
       }
    }
    

    If you’re still stuck after reviewing this, then consider reading about SSCCE, and posting your own here that we can modify and correct.

    Edit 3
    Per our discussions in chat,
    Your problem is when you call the To Top JButton, you are deleting the selected item from the list, while the ListSelectionListener is still listening, and this will cause a NPE to be thrown. A possible solution is to remove the ListSelectionListener before removing or adding any items, and then re-adding the listener after performing these actions. This will probably be necessary when you update your list model as well. Please see my SSCCE below. Also see how it is much easier to read and understand SSCCE code than your big code.

    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.Image;
    import java.awt.event.*;
    import java.io.File;
    import java.io.IOException;
    
    import javax.imageio.ImageIO;
    import javax.swing.*;
    import javax.swing.event.*;
    
    @SuppressWarnings("serial")
    public class MyToolView extends JPanel {
    
       public File[] file;
       public static int i = 0;
    
       final static JFileChooser fc = new JFileChooser();
       private static final int PREF_W = 900;
       private static final int PREF_H = 750;
       final DefaultListModel listModel = new DefaultListModel();
       final JList myList = new JList(listModel);
       private JLabel imageLabel = new JLabel();
       private javax.swing.JButton openButton;
       private JButton toTopBtn;
       private javax.swing.JList imageJList;
       private javax.swing.JScrollPane jScrollPane1;
       private javax.swing.JPanel mainPanel;
    
       public MyToolView() {
          initComponents();
       }
    
       private void initComponents() {
          jScrollPane1 = new javax.swing.JScrollPane();
          imageJList = new javax.swing.JList(listModel);
          openButton = new javax.swing.JButton();
          toTopBtn = new JButton("To Top");
    
          JPanel topPanel = new JPanel();
          topPanel.add(jScrollPane1);
          topPanel.add(openButton);
          topPanel.add(toTopBtn);
    
          setLayout(new BorderLayout());
          add(topPanel, BorderLayout.PAGE_START);
          add(new JScrollPane(imageLabel), BorderLayout.CENTER);
    
          toTopBtn.addActionListener(new ActionListener() {
    
             @Override
             public void actionPerformed(ActionEvent e) {
                toTopBtnActionPerformed(e);
             }
          });
    
          jScrollPane1.setFocusable(false);
          jScrollPane1.setName("jScrollPane1"); // NOI18N
    
          imageJList.setModel(new javax.swing.AbstractListModel() {
             String[] strings = { "AAAA.JPG", "BBBB.JPG" };
    
             public int getSize() {
                return strings.length;
             }
    
             public Object getElementAt(int i) {
                return strings[i];
             }
          });
          imageJList.setName("jList1"); // NOI18N
          imageJList.setCellRenderer(new JavaRenderer());
          jScrollPane1.setViewportView(imageJList);
          imageJList.addListSelectionListener(listSelectionListener);
    
          openButton.setFocusable(false);
          openButton.setName("openButton"); // NOI18N
          openButton.setAction(new OpenAction("Open"));
    
       }
    
       @Override
       public Dimension getPreferredSize() {
          return new Dimension(PREF_W, PREF_H);
       }
    
       private void toTopBtnActionPerformed(java.awt.event.ActionEvent evt) {
    
          // ******** here **********
          imageJList.removeListSelectionListener(listSelectionListener);
          int selectedIndex = imageJList.getSelectedIndex();
          if (selectedIndex < 0) {
             return;
          }
          String temp = (String) listModel.remove(selectedIndex);
          listModel.add(0, temp);
    
          // ******** here **********
          imageJList.addListSelectionListener(listSelectionListener);
       }
    
       ListSelectionListener listSelectionListener = new ListSelectionListener() {
          public void valueChanged(ListSelectionEvent listSelectionEvent) {
             System.out.print("First index: " + listSelectionEvent.getFirstIndex());
             System.out.print(", Last index: " + listSelectionEvent.getLastIndex());
    
             String path = (String) imageJList.getSelectedValue();
             System.out.println("path should be here: " + path);
             Image img;
             try {
                System.out.println("path is null: " + (path == null));
                File imageFile = new File(path);
                img = ImageIO.read(imageFile);
                imageLabel.setIcon(new ImageIcon(img));
                imageLabel.setText("");
             } catch (IOException ex) {
                ex.printStackTrace();
             }
          }
       };
    
       private class OpenAction extends AbstractAction {
          public OpenAction(String text) {
             super(text);
          }
    
          public void actionPerformed(ActionEvent evt) {
    
             fc.setMultiSelectionEnabled(true);
             int returnVal = fc.showDialog(null, "Open");
             int len = 0;
    
             if (returnVal == JFileChooser.APPROVE_OPTION) {
                imageJList.removeListSelectionListener(listSelectionListener); //!!
                file = fc.getSelectedFiles();
                len = file.length;
                System.out.println("length = " + len);
    
                // this code should be inside the if block
                for (i = 0; i < len; i++) {
                   String path = file[i].getPath();
                   System.out.printf("%d: %s%n", i, path);
                   listModel.add(i, path);
                }
                imageJList.setModel(listModel);
                imageJList.addListSelectionListener(listSelectionListener); //!!
             }
             // imageJList.updateUI(); //!! you shouldn't call this.
          }
       }
    
       private static void createAndShowGui() {
         MyToolView mainPanel = new MyToolView();
    
          JFrame frame = new JFrame("MyToolView");
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.getContentPane().add(mainPanel);
          frame.pack();
          frame.setLocationByPlatform(true);
          frame.setVisible(true);
       }
    
       public static void main(String[] args) {
          SwingUtilities.invokeLater(new Runnable() {
             public void run() {
                createAndShowGui();
             }
          });
       }
    }
    
    class JavaRenderer extends DefaultListCellRenderer {
       private int a;
    
       @Override
       public Component getListCellRendererComponent(JList jList1, Object value,
             int index, boolean isSelected, boolean hasFocus) {
    
          if (value instanceof String) {
             String name = (String) value;
             String[] splitedArray = null;
             splitedArray = name.split("\\\\");
             a = splitedArray.length - 1;
             name = splitedArray[a];
             System.out.println("name " + name);
             return super.getListCellRendererComponent(jList1, name, index,
                   isSelected, hasFocus);// what we display
          } else {
             return super.getListCellRendererComponent(jList1, value, index,
                   isSelected, hasFocus);// what we take
          }
       }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I want to count how many characters a certain string has in PHP, but
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I have a jquery bug and I've been looking for hours now, I can't
I've got a string that has curly quotes in it. I'd like to replace
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
this is what i have right now Drawing an RSS feed into the php,
Seemingly simple, but I cannot find anything relevant on the web. What is the
I have a French site that I want to parse, but am running into
I am currently running into a problem where an element is coming back from
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.