Results 1 to 9 of 9
  1. #1
    xyknight is offline Member
    Join Date
    Mar 2011
    Posts
    29
    Rep Power
    0

    Default Problem with ComboBox in a table

    I am trying to create a quiz in a table format where Column 1 is the Question, Column 2 is the ComboBox showing the possible answers, and Column 3 shows the points available for that question. I know Column 2 will need an actionListener but for now I want to make sure it shows. However, I cannot get the ComboBox to show properly.

    Here is my code:

    Java Code:
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.util.*;
    
    import javax.swing.*;
    import javax.swing.table.DefaultTableModel;
    
    
    public class Homework3_Kimmel extends JFrame implements ActionListener{
            private JButton button1;
            private JButton button2;
            private JPanel panel;
            private JTextArea textArea;
            private  String data;
            private String columnNames;
            public FileReader file;
            private BufferedReader buff;
            private File inFile;
            MyTableModel dtm;
            JTable table;
            private ArrayList<Questions> quizQuestions;
            private ArrayList<Answers> quizAnswers;
            private ArrayList<Correct> quizCorrect;
    
    
            //Object[][] questionList= new ArrayList<Quest>();
            public Homework3_Kimmel(String str){
                    super(str);
            }
            public static void main(String[] args) {
                    //creating and showing this application's GUI.
                    Homework3_Kimmel hwObject = new Homework3_Kimmel("Quiz");
    
                    hwObject.createAndShowGUI();
                    hwObject.readFile();
            }
            private void createAndShowGUI() {
                    JFrame frame  = new JFrame("Quiz");
                    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    Container contentPane = getContentPane();
                    contentPane.setLayout(new BorderLayout());
    
                    button1 = new JButton("Load Questions");
                    JPanel buttonPanel = new JPanel();
                    buttonPanel.add(button1);
                    button1.addActionListener(this);
    
                    button2 = new JButton("Calculate Score");
                    buttonPanel.add(button2);
                    button2.addActionListener(this);
    
                    contentPane.add(buttonPanel,BorderLayout.NORTH);
    
                    String[] columnNames = {"Question", "Answers", "Points"};
                    dtm = new MyTableModel(columnNames,0);
                    table = new JTable(dtm);
    
                    // dtm.addColumn(columnNames);
    
                    
    
    
                    JScrollPane scrollPane = new JScrollPane(table);
    
                    table.setPreferredScrollableViewportSize(new Dimension(500, 70));
                    contentPane.add(scrollPane,BorderLayout.CENTER);
    
    
    
                    setSize(700, 300);
                    setVisible(true);
            }
    
            public void readFile(){
                    String question;
                    String[]answer;
                    String correct;
                    Integer points;
                    
            
                    try{
                    	FileReader file = new FileReader("outdata.txt");
                    	BufferedReader buff = new BufferedReader(file);
                    	String line = null;
                   
                        while ((line=buff.readLine())!=null) {
                    	
                    		
                    		String parts[]=line.split(";");
                    		question=parts[0];
                    		
                    		answer=parts[1].split("/");
                    		JComboBox answerCombo = new JComboBox(answer);
                    		points=new Integer(parts[2]);
                    		correct=parts[3];
                    		                		
                    		Object[] quest = {question, answerCombo, points};
                            dtm.addRow(quest);
                            
                           
                            
                    }
                    buff.close();
                    
                    }
                    catch(Exception ex){
                            ex.printStackTrace();
                    }
                    
                    
            }
    
    }
    
    class MyTableModel extends DefaultTableModel {
            MyTableModel(Object[] c, int i){
                    super(c,i);
            }
    
    public boolean isCellEditable(int row, int col) {
        if (col != 1) {
            return false;
        } else {
            return true;
        }
    }
    }
    My text file is in the following format:

    Question;Answer1/Answer2/Answer3;Points;CorrectAnswer

    My column 2 shows the following:

    Java Code:
    [Ljava.lang.String;@e49d67c
    What am I doing wrong?

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by xyknight View Post
    My column 2 shows the following:

    Java Code:
    [Ljava.lang.String;@e49d67c
    What am I doing wrong?
    That's the toString() result of a String array. If you want to display an array of String, you'll either need to iterate through the array putting its items in a String or StringBuilder or else use java.utils.Arrays.toString(myArray).

  3. #3
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,765
    Blog Entries
    7
    Rep Power
    21

    Default

    Quote Originally Posted by xyknight View Post
    My column 2 shows the following:

    Java Code:
    [Ljava.lang.String;@e49d67c
    What am I doing wrong?
    That's how arrays of Strings display themself; arrays are kind of stupid. Have a look at the Arrays class for a (static) method that can display an entire array in a more human readable form.

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  4. #4
    xyknight is offline Member
    Join Date
    Mar 2011
    Posts
    29
    Rep Power
    0

    Default

    thanks but that tells me how to put out the array. what i want is to read the answer1/answer2/answer3 from my text file and put it as a combobox in my table.

  5. #5
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by xyknight View Post
    thanks but that tells me how to put out the array. what i want is to read the answer1/answer2/answer3 from my text file and put it as a combobox in my table.
    Iterate through your array and add it to the combo box via its addItem(...) method.

  6. #6
    xyknight is offline Member
    Join Date
    Mar 2011
    Posts
    29
    Rep Power
    0

    Default

    in my mind I am getting each part of the answer array and adding it to the combobox, but it still isn't working. i even am printing the current value to see if it is working and although i am getting each element of the array, it won't add to the combobox

    Java Code:
    while ((line=buff.readLine())!=null) {
                    	
                    		
                    		String parts[]=line.split(";");
                    		question=parts[0];
                    		
                    		answer=parts[1].split("/");
                    		JComboBox answerCombo = new JComboBox(answer);
                    		for(int i = 0;i< answer.length; i++){
                    			answerCombo.addItem(answer[i]);
                    			System.out.println(i + answer[i]);
                    			
                    		}
    
                    		
                    		
                    		points=new Integer(parts[2]);
                    		correct=parts[3];
                    		                		
                    		Object[] quest = {question,answerCombo, points};
                            dtm.addRow(quest);

    this is the system output:
    Java Code:
    0Blue
    1Red
    2Green
    0New York
    1Albany
    2Baltimore
    0Red
    1Blue
    2White
    0Rough
    1Woof
    2Meow
    0Reagan
    1Washington
    2Grant

  7. #7
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by xyknight View Post
    in my mind I am getting each part of the answer array and adding it to the combobox, but it still isn't working. i even am printing the current value to see if it is working and although i am getting each element of the array, it won't add to the combobox

    Java Code:
    while ((line=buff.readLine())!=null) {
                    	
                    		
                    		String parts[]=line.split(";");
                    		question=parts[0];
                    		
                    		answer=parts[1].split("/");
                    		JComboBox answerCombo = new JComboBox(answer);
                    		for(int i = 0;i< answer.length; i++){
                    			answerCombo.addItem(answer[i]);
                    			System.out.println(i + answer[i]);
                    			
                    		}
    
                    		
                    		
                    		points=new Integer(parts[2]);
                    		correct=parts[3];
                    		                		
                    		Object[] quest = {question,answerCombo, points};
                            dtm.addRow(quest);

    this is the system output:
    Java Code:
    0Blue
    1Red
    2Green
    0New York
    1Albany
    2Baltimore
    0Red
    1Blue
    2White
    0Rough
    1Woof
    2Meow
    0Reagan
    1Washington
    2Grant
    Let's see your latest compilable/runnable code.

  8. #8
    xyknight is offline Member
    Join Date
    Mar 2011
    Posts
    29
    Rep Power
    0

    Default

    I made some changes to my code and I am now getting a combobox in the table. However, the combobox keeps repeating the same value.

    Here is the new code:

    Java Code:
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.util.*;
    
    import javax.swing.*;
    import javax.swing.table.DefaultTableCellRenderer;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.TableColumn;
    
    
    public class Homework3_Kimmel extends JFrame implements ActionListener{
            private JButton button1;
            private JButton button2;
            private JPanel panel;
            private JTextArea textArea;
            private  String data;
            private String columnNames;
            public FileReader file;
            private BufferedReader buff;
            private File inFile;
            MyTableModel dtm;
            JTable table;
            private ArrayList<Questions> quizQuestions;
            private ArrayList<Answers> quizAnswers;
            private ArrayList<Correct> quizCorrect;
            JComboBox answerCombo;
    
    
            //Object[][] questionList= new ArrayList<Quest>();
            public Homework3_Kimmel(String str){
                    super(str);
            }
            public static void main(String[] args) {
                    //creating and showing this application's GUI.
                    Homework3_Kimmel hwObject = new Homework3_Kimmel("Quiz");
    
                    hwObject.createAndShowGUI();
                    hwObject.readFile();
            }
            private void createAndShowGUI() {
                    JFrame frame  = new JFrame("Quiz");
                    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    Container contentPane = getContentPane();
                    contentPane.setLayout(new BorderLayout());
    
                    button1 = new JButton("Load Questions");
                    JPanel buttonPanel = new JPanel();
                    buttonPanel.add(button1);
                    button1.addActionListener(this);
    
                    button2 = new JButton("Calculate Score");
                    buttonPanel.add(button2);
                    button2.addActionListener(this);
    
                    contentPane.add(buttonPanel,BorderLayout.NORTH);
    
                    String[] columnNames = {"Question", "Answers", "Points"};
                    dtm = new MyTableModel(columnNames,0);
                    table = new JTable(dtm);
    
                    // dtm.addColumn(columnNames);
    
                    
    
    
                    JScrollPane scrollPane = new JScrollPane(table);
    
                    table.setPreferredScrollableViewportSize(new Dimension(500, 70));
                    contentPane.add(scrollPane,BorderLayout.CENTER);
    
    
    
                    setSize(700, 300);
                    setVisible(true);
            }
    
            public void readFile(){
                    String question;
                    String[]answer;
                    String correct;
                    Integer points;
                    
            
                    try{
                    	FileReader file = new FileReader("outdata.txt");
                    	BufferedReader buff = new BufferedReader(file);
                    	String line = null;
                   
                        while ((line=buff.readLine())!=null) {
                    	
                    		
                    		String parts[]=line.split(";");
                    		question=parts[0];
                    		
                    		answer=parts[1].split("/");
                    		answerCombo = new JComboBox(answer);
                    		//for(int i = 0;i< answer.length; i++){
                    			//answerCombo.addItem(answer[i]);
                    			//System.out.println(i + answer[i]);
                    			
                    		//}
    
                    		
                    		
                    		points=new Integer(parts[2]);
                    		correct=parts[3];
                    		                		
                    		Object[] quest = {question,answer, points};
                            dtm.addRow(quest);
                            //System.out.println(java.util.Arrays.toString(
                            	      //answer));
    
                            TableColumn aColumn = table.getColumnModel().getColumn(1); 
                             
                            answerCombo.addItem(answer); 
                            		
                            aColumn.setCellEditor(new DefaultCellEditor(answerCombo)); 
    
                            
                    }
                    buff.close();
                    
                    }
                    catch(Exception ex){
                            ex.printStackTrace();
                    }
                    
                    
            }
           
            public void actionPerformed(ActionEvent evt) {
    
                    Object source = evt.getSource();
                    if(source == button1){
                            /*try{
                                    outFile = new File ("outdata.txt");
                                    fw = new FileWriter(outFile, true);
                                    fbw = new BufferedWriter(fw);
                                    String text = textArea.getText();
                                    fbw.write(text);
                                    fbw.close();
                                    fw.close();
                                    System.out.print("successful print");
                            } catch (Exception ex){
                                    ex.printStackTrace();}*/
                            readFile();
                    }
            }
    }
    
    class MyTableModel extends DefaultTableModel {
            MyTableModel(Object[] c, int i){
                    super(c,i);
            }
    
    public boolean isCellEditable(int row, int col) {
        if (col != 1) {
            return false;
        } else {
            return true;
        }
    }
    }
    here is what is repeated in the Answer Column for questions 1-5:

    Java Code:
    Reagan
    Washington
    Grant
    [Ljava.lang.String;@710d85cc
    and this is the contents of the outdata.txt file where the questions and answers are coming from:
    Java Code:
    What color is the sky?;Blue/Red/Green;20;Blue
    What is the capital of New York?;New York/Albany/Baltimore;20;New York
    What color is Papa Smurf's hat?;Red/Blue/White;20;Red
    What sound does a cat make?;Rough/Woof/Meow;20;Meow
    Who is burried in Grant's tomb?;Reagan/Washington/Grant;20;Grant

  9. #9
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    I think that to solve this you're probably best served to create a custom cell editor class, a custom cell renderer class, and an answers class to hold the data. Since this is homework, I'm not going to show you my full solution, but will give you suggestions based on it.

    First off I created a class called MyAnswers whose objects would be held in your table model for the combobox column. It has a private JComboBox field (comboBox) that was filled in the constructor via the answer array of String (I also first gave it an empty String to allow the user the option of giving no answer, and to show no answer as the default). It has two public methods, getComboBox that returns the combo box and getSelectedAnswer that returns the selected item String (by calling getSelectedItem() on the combo box).

    I then created the MyAnswersCellEditor class that extends AbstractCellEditor and implements TableCellEditor. It has one private MyAnswers field (called myAnswers) and two methods, getTableCellEditorComponent and getCellEditorValue, the first method sets the myAnswers variable and then returns myAnswer's combo box, and the second method simply returns the myAnswers variable that was set in the first method.

    Finally I created a very simple MyAnswersCellRenderer class that extends DefaultTableCellRenderer that has no fields and only one method, setValue, that gets the MyAnswers object from the JTable via its parameter and gets the String returned by its getSelectedAnswer method and calls setText(...) with this String.

    I then set the TableColumn's cell editor and cell renderer once, before the while loop where you read your text file. In the while loop, I don't create any comboboxes or editors or renderes, but I do create a MyAnswer object and add it to the row array of Object[] that you call quest in the middle spot.

    Check the Oracle Swing Table tutorial and sample code for examples and the API for AbstractCellEditor, TableCellEditor, and DefaultTableCellRenderer for more details on the method signatures.

    Hope this helps!
    Last edited by Fubarable; 04-25-2011 at 04:11 AM.

Similar Threads

  1. Combobox Problem?
    By waqasahmed_03235001393 in forum Advanced Java
    Replies: 1
    Last Post: 07-27-2010, 11:56 AM
  2. problem with <rich:comboBox>
    By raj18 in forum JavaServer Faces (JSF)
    Replies: 1
    Last Post: 11-15-2009, 06:26 AM
  3. problem in combobox
    By 435.mahesh in forum AWT / Swing
    Replies: 3
    Last Post: 05-04-2009, 06:12 AM
  4. Problem in combobox
    By santhosh_el in forum AWT / Swing
    Replies: 4
    Last Post: 04-03-2009, 05:01 AM
  5. problem with combobox as a TableCellEditor
    By sandeepsai39 in forum New To Java
    Replies: 0
    Last Post: 03-20-2009, 12:39 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •