?
Solved

How can I display LISTS from this code?

Posted on 2008-11-19
5
Medium Priority
?
293 Views
Last Modified: 2012-05-05
I have this working code attached in Code Snippet, now I need to show it in LIST with SCROLLS instead of ShowMessageDialog.
I got this sample code from a book but I don't know how to implement it to my old existing code. Anyone?

//  SimpleList.java
//
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class SimpleList extends JPanel {
    String label[] = { "Zero","One","Two","Three","Four","Five","Six",
                       "Seven","Eight","Nine","Ten","Eleven" };
    JList list;

    public SimpleList( ) {
        this.setLayout(new BorderLayout( ));
        list = new JList(label);
        JScrollPane pane = new JScrollPane(list);
        JButton button = new JButton("Print");
        button.addActionListener(new PrintListener( ));

        add(pane, BorderLayout.CENTER);
        add(button, BorderLayout.SOUTH);
    }

    public static void main(String s[]) {
         JFrame frame = new JFrame("Simple List Example");
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         frame.setContentPane(new SimpleList( ));
         frame.setSize(250, 200);
         frame.setVisible(true);
    }

    // An inner class to respond to clicks of the Print button
    class PrintListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            int selected[] = list.getSelectedIndices( );
            System.out.println("Selected Elements:  ");

            for (int i=0; i < selected.length; i++) {
                String element =
                      (String)list.getModel( ).getElementAt(selected[i]);
                System.out.println("  " + element);
            }
        }
    }
}
import java.sql.*;
 
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
 
import javax.swing.*;
 
public class NewClass {
public static void main(String args[]) {
            
Calendar cal = Calendar.getInstance();
SimpleDateFormat formatter = new SimpleDateFormat ("MM/dd/yyyy");
Date currentTime = cal.getTime();
String dateString = formatter.format(currentTime);
 
String tabletodisplay;
tabletodisplay = "inventorytable";
 
        try { 
            String url = "jdbc:mysql://localhost:3306/alcochatinventory"; 
            Connection conn = DriverManager.getConnection(url,"root","root"); 
            
PreparedStatement stmtInventory = conn.prepareStatement("SELECT * FROM  `"+tabletodisplay+"` WHERE date1 = ?");
 
ResultSet uprsInventory; 
            stmtInventory.setString(1,dateString);
            uprsInventory=stmtInventory.executeQuery();
            
            ResultSetMetaData uprsInventoryMetaData = uprsInventory.getMetaData();
 
 
    int InventorynumberOfColumns = uprsInventoryMetaData.getColumnCount();
int i1;
i1=0;
    String newstring1, newstring2;
newstring2 = "";
 
while (uprsInventory.next ()) {
for (int i=1; i<=InventorynumberOfColumns; i++) {
String columnName = uprsInventoryMetaData.getColumnLabel(i);
//System.out.print(columnName + ": ");
String columnValue = uprsInventory.getString(i);
    
//System.out.println(columnValue);
if (i1<35){
newstring1 = columnName + ": " + columnValue;
newstring2 = newstring2 + newstring1 + "\n";
i1 = i1 + 1;
//System.out.println("i1: " + i1);
}
 
else  {
    JOptionPane.showMessageDialog(null, newstring2);
    newstring2 = "";    
    i1=0;
    //System.out.println("i1: " + i1);
}
 
if (i==InventorynumberOfColumns) {
        JOptionPane.showMessageDialog(null, newstring2);
    
}
}
}
 
stmtInventory.close();
conn.close();
} catch(SQLException ex) {
System.err.print("SQLException: ");
System.err.println(ex.getMessage());
}
}
}

Open in new window

0
Comment
Question by:glynco
  • 3
  • 2
5 Comments
 
LVL 60

Accepted Solution

by:
Kevin Cross earned 1500 total points
ID: 23000819
To start with, you need to put your data in an array instead of one string variable.

newstring1 = columnName + ": " + columnValue;
newstring2 = newstring2 + newstring1 + "\n";

This needs to be and array of 'columnName + ": " + columnValue'.  A good way to accomplish this is to use a List<String> and add values, then you use the List as an array.

e.g.

List<String> strList = new ArrayList<String>();
strList.add(columnName + ": " + columnValue);
strList.toArray(); // http://java.sun.com/j2se/1.5.0/docs/api/java/util/List.html

If you notice above, the JList is being built using String[] (array) called label:
list = new JList(label);

Therefore, if you use the List<String> to hold you values then you can formulate a JList instead of showing a dialog box by doing this in code:
list = new JList(strList.toArray());

Hope that helps.

Best regards,
Kevin
0
 
LVL 60

Expert Comment

by:Kevin Cross
ID: 23000824
Try implementing this and then post back with your code and any specific questions and/or errors/issues you are getting...
0
 

Author Comment

by:glynco
ID: 23000922
Sorry I don't know how to do what you were saying.

But I tried this, but would not recognize "newstring2" as array.
newstring1 = "{" +'"' + columnName + '"' + ", " + '"' + columnValue + '"' + "}";
 
newstring2 = newstring2 + newstring1 + ",";
 
    Object rows[][] = newstring2;
    
    Object headers[] = { "Column Name", "Colomn Value" };
    JFrame frame = new JFrame("Scrollless Table");
    JTable table = new JTable(rows, headers);
    frame.getContentPane().add(table, BorderLayout.CENTER);
    frame.setSize(300, 150);
    frame.setVisible(true);

Open in new window

0
 

Author Comment

by:glynco
ID: 23000943
I also have difficulty in putting all the classes altogether. I tried this putting it in one main class but got errors.

I have not encountered working with more than one class yet.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
 
public class NewClass {
public static void main(String args[]) {
    
    //  SimpleList.java
//
 
 
 
    String label[] = { "Zero","One","Two","Three","Four","Five","Six",
                       "Seven","Eight","Nine","Ten","Eleven" };
    JList list;
 
  
        this.setLayout(new BorderLayout( ));
        list = new JList(label);
        JScrollPane pane = new JScrollPane(list);
        JButton button = new JButton("Print");
        button.addActionListener(new PrintListener( ));
 
        add(pane, BorderLayout.CENTER);
        add(button, BorderLayout.SOUTH);
 
 
 
         JFrame frame = new JFrame("Simple List Example");
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         frame.setContentPane(new SimpleList( ));
         frame.setSize(250, 200);
         frame.setVisible(true);
 
 
    // An inner class to respond to clicks of the Print button
 
            int selected[] = list.getSelectedIndices( );
            System.out.println("Selected Elements:  ");
 
            for (int i=0; i < selected.length; i++) {
                String element =
                      (String)list.getModel( ).getElementAt(selected[i]);
                System.out.println("  " + element);
            
        
            }
}

Open in new window

0
 
LVL 60

Expert Comment

by:Kevin Cross
ID: 23002976
glynco, sorry I missed your messages last night, but by the accepting of the solution I am hoping you saw what I was proposing there.  Instead of using newstring2, just use a List<String> and then instantiate the JList using the List.toArray() method as JList takes an Object[] for list values.

Best regards,
Kevin
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
Suggested Courses
Course of the Month13 days, 20 hours left to enroll

807 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question