Search code examples
javaarraysswingeventsapplet

Array of Objects to JList and JList to JPanel


I have following two classes whose basical purpose to create an array of objects...

class MovieInfo
    { private String movieTitle;
      private String movieRating;
      private String movieImg;
      private String movieShowTimes;
      private static double adultPrice;
      private static double childPrice;
    MovieInfo(String title, String rating, String img, String showTimes)
      { 
         movieTitle = title;
          movieRating = rating;
         movieImg = img;
         movieShowTimes = showTimes;

      }
    /*....sets gets methods.... */
    }

    ///////////////////////////////
    class MovieList
    {

      MovieInfo[] mList;

      public void createList()
      {

         mList = new MovieInfo[22];

      mList[0] = new MovieInfo("A United Kingdom","PG","A_United_Kingdom.jpg","yyyn");
     mList[1] = new MovieInfo("Amitiville The Awakening","18A","AmitivilleAwakening.jpg","yyyn");
     mList[2] = new MovieInfo("Arrival","14A","arrival.jpg","yyyy");
     mList[3] = new MovieInfo("Baywatch","14A","baywatch.jpg","yyyy");
     mList[4] = new MovieInfo("Beauty and the Beast","PG","Beauty_and_the_Beast.jpg","yyyn");
  }
} 

I also have JList which is attached to JPanel and radio buttons.. And my problem is that I can not get how to display name of the movie from mList[0] on this JList when I click 1st rbutton, name of the movie from mList[1] when I click 2nd rbutton and etc....

Yes I know that I need to register listener for my rbuttons and group them and add ItemStateChange (just did not want to add too much code here)... I am asking here about logic after the lines of

    if(e.getSource() instanceof JRadioButton)
   { 

Please help! Any ideas will be highly appreciated!


Solution

  • You could write a custom CellRenderer, as shown in the docs.

    For example, having a Movie bean and a MoviesListCellRenderer which extends DefaultListCellRenderer you could end up with something like this:

    public class JListCards {
        private JFrame frame;
        private JPanel radiosPane;
        private JRadioButton[] radios;
        private String[] radiosNames = {"Movie", "Classification", "Price"};
        private JList <Movie> moviesList;
        private ButtonGroup group;
    
        private Movie[] movies = new Movie[] {
            new Movie("Happy Feet", "AA", 10),
            new Movie("Star Wars", "B12", 15),
            new Movie("Logan", "C", 20)
        };
    
        public static void main(String[] args) {
            SwingUtilities.invokeLater(() -> new JListCards().createAndShowGui());
        }
    
        public void createAndShowGui() {
            frame = new JFrame(getClass().getSimpleName());
    
            radiosPane = new JPanel(new GridLayout(1, 3));
            radios = new JRadioButton[3];
            group = new ButtonGroup();
    
            for (int i = 0; i < radios.length; i++) {
                radios[i] = new JRadioButton(radiosNames[i]);
                radios[i].addActionListener(listener);
                radiosPane.add(radios[i]);
                group.add(radios[i]);
            }
    
            radios[0].setSelected(true);
            moviesList = new JList<Movie>(movies);
            moviesList.setCellRenderer(new MoviesListCellRenderer(0));
    
            frame.add(moviesList);
            frame.add(radiosPane, BorderLayout.SOUTH);
            frame.pack();
            frame.setVisible(true);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        }
    
        ActionListener listener = new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                for (int i = 0; i < radios.length; i++) {
                    if (e.getSource().equals(radios[i])) {
                        moviesList.setCellRenderer(new MoviesListCellRenderer(i));
                        break;
                    }
                }
            }
        };
    
        class MoviesListCellRenderer extends DefaultListCellRenderer {
            private int attribute;
    
            public MoviesListCellRenderer(int attribute) {
                this.attribute = attribute;
            }
    
            @Override
            public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
                super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
                if (value instanceof Movie) {
                    Movie movie = (Movie) value;
                    switch (attribute) {
                        case 0:
                            setText(movie.getMovieName());
                            break;
                        case 1:
                            setText(movie.getClassification());
                            break;
                        default:
                            setText(String.valueOf(movie.getPrice()));
                            break;
                    }
                }
                return this;
            }
        }
    
        class Movie {
            private String movieName;
            private String classification;
            private double price;
    
            public Movie(String movieName, String classification, double price) {
                super();
                this.movieName = movieName;
                this.classification = classification;
                this.price = price;
            }
    
            public String getMovieName() {
                return movieName;
            }
            public void setMovieName(String movieName) {
                this.movieName = movieName;
            }
            public String getClassification() {
                return classification;
            }
            public void setClassification(String classification) {
                this.classification = classification;
            }
            public double getPrice() {
                return price;
            }
            public void setPrice(double price) {
                this.price = price;
            }
        }
    }
    

    Which as you can see, changes the cell renderer based on the radio selected, this code can still be improved but should give you an idea:

    enter image description here