Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 6 of 6

Thread: Rendering the cells of JComboBox in Java

  1. #1
    Member
    Join Date
    Jun 2014
    Posts
    77
    Thanks
    14
    Thanked 0 Times in 0 Posts

    Default Rendering the cells of JComboBox in Java

    Hi guys,

    Say I have a student class with fields names and Gender. Now, I have a students' array. such that I can create multiple students' classes: student a, student b, student c e.t.c and store them into the students' array. Now, I store this students' array in a JComboBox and want to only display the names of these students in the array. Such that the JComboBox lists only the names of student a, student b and student c. . When a user clicks on a selected Item on the JComboBox, even though, it was a student's name that was selected, I want the selectedItem to be a object of the Student class. This, I have learnt works with JList by writing your own custom JList models and then DefaultListCellRenderer. Is there anyway, one could also do this with JComboBox? If possible, could anyone point me to how to go about it? I Been on this for days now. I have NOT implemented the JCombBox as that is where I am finding it difficult to get right. If anyone could point me to how to start implementing it, I will be grateful. Just kindly check the full code and let me know what you think. Below is the MCVE.




    //Main Method

    import StudentList;
    import Student;
    import ViewGui;
    import Controller;
     
    public class SwingMainMethod {
     
    	/**
    	 * @param args
    	 */
    	public static void main(String[] args) {
     
    		 Student student = new Student();
    		 StudentList studentList = new StudentList();
    		 	Student studenta = new Student();
    			studenta.setStudentName("Lance");
    			studenta.setStudentId("01");
    			studentList.add(studenta); // add the student
    			Student studentb = new Student();
    			studentb.setStudentName("John");
    			studentb.setStudentId("02");
    			studentList.add(studentb); // add the student
    			Student studentc = new Student();
    			studentc.setStudentName("Harry");
    			student.setStudentId("03");
    			studentList.add(studentc);
     
     
    	      ViewGui view = new ViewGui(studentList) ;
    	      Controller c = new Controller(view,studentList);
    	}
     
    }



    //The Controller
    package controller;
     
    import java.awt.BorderLayout;
    import java.awt.Font;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
     
    import javax.swing.JFrame;
    import javax.swing.JList;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.ListSelectionModel;
     
    import Student;
    import ViewGui;
    import CustomListCellRenderer;
    import StudentList;
     
    public class Controller {
     
    	private static StudentList studentList; // the JList custom model
    	private ViewGui view; // the view
     
    	public Controller(ViewGui view, StudentList studentList) {
     
    		this.studentList = studentList;
    		this.view = view;
    		view.setVisible(true);
    		this.view.addStudentListener(new AddStudentListener());
    	}
     
    	class AddStudentListener implements ActionListener {
    		public void actionPerformed(ActionEvent e) {
    			if (e.getActionCommand().equals("click me!")) {
    				view.setVisible(false);
    				JFrame c = new JFrame();
    				c.getContentPane();
    				c.setSize(100, 400);
    				c.setLayout(new BorderLayout());
    				JPanel panel = new JPanel();
    				JList<Student> list = new JList<Student>(studentList);
    				list.setCellRenderer(new CustomListCellRenderer());
    				list.setVisibleRowCount(3);
    				list.setFont(new Font("Tahoma", Font.PLAIN, 14));
    				list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    				list.setBounds(0, 0, 30, 40);
    				JScrollPane pane = new JScrollPane(list);
    				panel.add(list);
    				c.add(panel, BorderLayout.NORTH);
    				c.setVisible(true);
     
    			}
    		}
    	}
     
    }

    //The Model

     
     
     
    public class Student {
     
    	private String studentName;
    	private String studentID ;
     
    	public String getStudentName(){
    	return studentName;
    	}
     
    	public String getStudentId(){
    		return studentID;
    		}
     
    	public void setStudentName(String name){
    	this.studentName = name;
    	}
     
    	public void setStudentId(String id){
    	this.studentID = id;
    	}
     
    	public Student(String studentName, String studentId){
    	this.studentName = studentName;
    	this.studentID = studentId;
    	}
     
    	/**
    	*Default constructor
    	**/
    	public Student(){
     
    	}
     
     
     
    	@Override
    	public String toString() {
    		return "Student [studentName=" + studentName + ", studentID=" + studentID + "]";
    	}
     
    }

    //The Gui
     
    package view;
     
    import java.awt.BorderLayout;
    import java.awt.Container;
    import java.awt.Dimension;
    import java.awt.event.ActionListener;
     
    import javax.swing.JButton;
    import javax.swing.JComboBox;
    import javax.swing.JFrame;
    import Student;
     
    import CustomListCellRenderer;
    import StudentComboModel;
    import StudentList;
     
    public class ViewGui extends JFrame{
     
    	private static final long serialVersionUID = 1L;
    	public JButton button = new JButton("click me!");
    	public JComboBox<Student> studentCombo;
    	String[] comboTypes = { "Lance", "John", "Harry" };
     
    	public ViewGui(StudentList studentList){
    		StudentComboModel studentModel = new StudentComboModel(studentList);
    	setTitle("Main Window");
    	setSize(200,200);
    	Container c = getContentPane();
        c.setLayout(new BorderLayout());
        CustomListCellRenderer renderer = new CustomListCellRenderer();
        renderer.setPreferredSize(new Dimension(200, 130));
        studentCombo = new JComboBox<Student>();
    	studentCombo.setModel(studentModel);
    	studentCombo.setRenderer(renderer);
    	studentCombo.setPreferredSize(new Dimension(200, 50));
    	//studentCombo.setSelectedIndex(0);
     
     
        c.add(button,   BorderLayout.NORTH);
        c.add(studentCombo, BorderLayout.SOUTH);
     
     
    	}
     
        public void addStudentListener(ActionListener m){
    			button.addActionListener(m);
    		}
    }

    //====================== The Jlist Model and Renderer classes

    a. Model
     
    import java.util.ArrayList;
    import java.util.List;
     
    import javax.swing.AbstractListModel;
     
    import Student;
     
    public class StudentList extends AbstractListModel<Student> {
     
    	private static final long serialVersionUID = 1L;
    	List<Student> studentList = new ArrayList<Student>();
    	@Override
    	public int getSize() {
    		return studentList.size();
    	}
     
    	@Override
    	public Student getElementAt(int index) {
     
    		return (Student)studentList.get(index);
     
    	}
     
    	/**
    	 * adds a student to the JList panel
    	 * @param student to be added
    	 */
    	public void add(Student student) {
    	    System.out.println("adding");
    	    studentList.add(student);
    	    int index0 = studentList.size() - 1;
    	    int index1 = index0;
    	    fireIntervalAdded(this, index0, index1);
    	    System.out.println(studentList.toString());
    	}
     
     
     
    }

    b.Renderer

     
    package backEndImp;
     
    import java.awt.Color;
    import java.awt.Component;
     
    import javax.swing.DefaultListCellRenderer;
    import javax.swing.JLabel;
    import javax.swing.JList;
     
    import Student;
     
    public class CustomListCellRenderer extends DefaultListCellRenderer {
     
    	private static final long serialVersionUID = 1L;
    	private static final Color HIGHLIGHT_COLOR = new Color(0, 0, 128);
     
    	public CustomListCellRenderer(){
    		setOpaque(true);
    	    setIconTextGap(12);
    	}
     
    	public Component getListCellRendererComponent(
    			JList<?> list, Object value,
    			int index, boolean isSelected, boolean cellHasFocus) {
     
     
    		Component result = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
     
    		if (isSelected) {
    		      setBackground(HIGHLIGHT_COLOR);
    		      setForeground(Color.white);
    		    } else {
    		      setBackground(Color.white);
    		      setForeground(Color.black);
    		    }
    		if (result instanceof JLabel && value instanceof Student) {
     
    			JLabel lbl = (JLabel) result;
    			Student obj = (Student) value;
    			lbl.setText(obj.getStudentName() + "\t" + obj.getStudentId());
     
    		}
    		return result;
    	}
     
    }

    //The JComboBox Model
     
     
    import javax.swing.ComboBoxModel;
    import javax.swing.event.ListDataListener;
     
    import Student;
     
    public class StudentComboModel implements ComboBoxModel<Student> {
    private StudentList list;
    public StudentComboModel(StudentList list){
    this.list = list;
    }
     
    	@Override
    	public int getSize() {
    		// TODO Auto-generated method stub
    		return 0;
    	}
     
    	@Override
    	public Student getElementAt(int index) {
    		// TODO Auto-generated method stub
    		return null;
    	}
     
    	@Override
    	public void addListDataListener(ListDataListener l) {
    		// TODO Auto-generated method stub
     
    	}
     
    	@Override
    	public void removeListDataListener(ListDataListener l) {
    		// TODO Auto-generated method stub
     
    	}
     
    	@Override
    	public void setSelectedItem(Object anItem) {
    		// TODO Auto-generated method stub
     
    	}
     
    	@Override
    	public Object getSelectedItem() {
    		// TODO Auto-generated method stub
    		return null;
    	}
     
    }



    Thanks
    Last edited by help_desk; August 30th, 2014 at 02:41 PM. Reason: Added MCVE


  2. #2
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: Rendering the cells of JComboBox in Java

    You would do it almost the exact same way, just use a ListCellRenderer. What have you tried? Have you looked at the API or tutorials at all?

    You could also just override the toString() method in your Student class.
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  3. #3
    Member
    Join Date
    Jun 2014
    Posts
    77
    Thanks
    14
    Thanked 0 Times in 0 Posts

    Default Re: Rendering the cells of JComboBox in Java

    Hi Kevin,

    Yeah, I have tried things. First, i just set the JComboBox with the ListCellRender. so, jComboBox.setRenderer(ListCellRenderer); but how to create the model is the problem. There has to be a model. I did some research and discovered I have to create a ComboBoxModel first. This comboBoxModel has to contain the students list. and then I can now do things like this : jComboBox.setModel(customComboBoxModel). Only then will the renderer know what to render. For now, writing the customCombBoxModel is the challenge. I don't seem to see how to work around this given my student class with names and Gender.

  4. #4
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: Rendering the cells of JComboBox in Java

    Why does there have to be a custom model?

    Please post an MCVE showing what you've tried so far.
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  5. #5
    Member
    Join Date
    Jun 2014
    Posts
    77
    Thanks
    14
    Thanked 0 Times in 0 Posts

    Default Re: Rendering the cells of JComboBox in Java

    Hi Kevin, I have added an MCVE. I am hoping anyone could help me with this. Thanks

  6. #6
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: Rendering the cells of JComboBox in Java

    That's not an MCVE. Why do you have two different model classes? Why do you need them at all? What does this code do? I'm pretty confused about what your actual question is.
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

Similar Threads

  1. Facing issues while rendering Jpeg200 image in Swing in Java 7
    By chandan2908 in forum What's Wrong With My Code?
    Replies: 1
    Last Post: May 9th, 2013, 07:25 AM
  2. Merge Cells in JTable
    By Stx in forum AWT / Java Swing
    Replies: 0
    Last Post: July 16th, 2012, 04:21 AM
  3. Java 3D Problems - Canvas 3d and QuadArray rendering
    By minime12358 in forum What's Wrong With My Code?
    Replies: 14
    Last Post: May 27th, 2011, 08:00 AM
  4. Randomizing cells in a grid
    By Flowbs in forum AWT / Java Swing
    Replies: 3
    Last Post: December 18th, 2010, 09:53 PM
  5. Counting cells
    By Shyamz1 in forum What's Wrong With My Code?
    Replies: 1
    Last Post: October 28th, 2010, 05:04 PM

Tags for this Thread