display database table in java - java

I am trying to get a table to populate from my database. I followed a tutorial and my code is displayed below, however I am getting this error and cannot figure out why. In my database I have 'first name, last name, address, city, state, zip' not sure if this info is needed to help me with my question
Could someone please help
thank you in advanced for your help.
package medicalrecords;
import java.awt.*;
import java.sql.*;
import java.util.*;
import javax.swing.*;
public class TableFromDatabase extends JPanel {
private Connection conexao = null;
public TableFromDatabase() {
Vector columnNames = new Vector();
Vector data = new Vector();
try {
// Connect to an Access Database
conexao = DriverManager.getConnection("jdbc:derby://" + "localhost"
+ ":1527/Medical Records", "root", "password");
// Read data from a table
String sql = "select * from SD2799.PATIENTRECORDS";
try (Statement stmt = conexao.createStatement();
ResultSet rs = stmt.executeQuery(sql)) {
ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();
// Get column names
for (int i = 1; i <= columns; i++) {
columnNames.addElement(md.getColumnName(i));
}
// Get row data
while (rs.next()) {
Vector row = new Vector(columns);
for (int i = 1; i <= columns; i++) {
row.addElement(rs.getObject(i));
}
data.addElement(row);
}
}
conexao.close();
} catch (Exception e) {
System.out.println(e);
}
// Create table with database data
JTable table = new JTable(data, columnNames) {
#Override
public Class getColumnClass(int column) {
for (int row = 0; row < getRowCount(); row++) {
Object o = getValueAt(row, column);
if (o != null) {
return o.getClass();
}
}
return Object.class;
}
};
JScrollPane scrollPane = new JScrollPane(table);
add(scrollPane);
JPanel buttonPanel = new JPanel();
add(buttonPanel, BorderLayout.SOUTH);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame("Patient Records");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
TableFromDatabase newContentPane = new TableFromDatabase();
newContentPane.setOpaque(true); //content panes must be opaque
frame.setContentPane(newContentPane);
//Display the window.
frame.pack();
frame.setVisible(true);
});
}
}

Your message "uses unchecked or unsafe operations. Note: Recompile with -Xlint:unchecked for details" is not an error, but it is a warning. The Vector class is generic (Generics were added to Java in 1.5), which means that it takes a type parameter. Here, it means the type of objects it can hold.
If you were to re-compile with the command line option "-Xlint:unchecked" as the warning suggests, the compiler will give you more details about the warning, including the offending lines.
You didn't supply a type parameter for any of your Vectors, so they are raw, meaning no type parameter was supplied. The compiler is warning you that you are using raw types, and that your type safety is at risk.
You can supply the appropriate type parameters to eliminate the warnings. In the TableFromDatabase constructor, towards the top:
Vector<String> columnNames = new Vector<String>();
Vector<Vector<Object>> data = new Vector<Vector<Object>>();
and later on in the same constructor:
Vector<Object> row = new Vector<Object>(columns);
However, Vector was superseded by ArrayList (and its List interface) in Java 1.2. In fact Vector was retrofitted then to implement the new-then List interface. It doesn't look like you need Vector's thread safety, so it's recommended to use ArrayList instead.
List<String> columnNames = new ArrayList<String>();
List<Vector<Object>> data = new ArrayList<List<Object>>();
and
List<Object> row = new ArrayList<Object>(columns);
As of Java 1.7, you can use the "diamond operator", and remove the type parameter on the right side of the assignment operator, letting Java infer the proper type, e.g.:
List<String> columnNames = new ArrayList<>();
List<Vector<Object>> data = new ArrayList<>();
and
List<Object> row = new ArrayList<>(columns);

Related

Star rank in table row are displayed outside the table

when I Run the project the table rows are displayed correctly except the rank stars the show outside the table and inside the colonne a text appears as displayed in the image :
public ListTasksForm(Form previous) {
SpanLabel sp = new SpanLabel();
sp.setText(ServiceTask.getInstance().getAllArticles().toString());
ArrayList<Articles> articles = ServiceTask.getInstance().getAllArticles();
Object[][] rows = new Object[articles.size()][];
for (int iter = 0; iter < rows.length; iter++) {
rows[iter] = new Object[]{
articles.get(iter).getName(), articles.get(iter).getDescription(), articles.get(iter).getLabel(), articles.get(iter).getQuantity(),
articles.get(iter).getRating(), add(createStarRankSlider(articles.get(iter).getId_article()))
};
}
TableModel model = new DefaultTableModel(new String[]{"name", "description", "label", "quantity", "rating", "rate"}, rows);
Table table = new Table(model);
add(table);
getToolbar().addMaterialCommandToLeftBar("", FontImage.MATERIAL_ARROW_BACK, e -> previous.showBack());
}
});
and this is the function for the star rank creation
private Slider createStarRankSlider(int id) {
Slider starRank = new Slider();
starRank.setEditable(true);
starRank.setMinValue(0);
starRank.setMaxValue(10);
int fontSize = Display.getInstance().convertToPixels(3);
Font fnt = Font.createTrueTypeFont("Handlee", "Handlee-Regular.ttf").
derive(fontSize, Font.STYLE_PLAIN);
Style s = new Style(0xffff33, 0, fnt, (byte) 0);
Image fullStar = FontImage.createMaterial(FontImage.MATERIAL_STAR, s).toImage();
s.setOpacity(100);
s.setFgColor(0);
Image emptyStar = FontImage.createMaterial(FontImage.MATERIAL_STAR, s).toImage();
initStarRankStyle(starRank.getSliderEmptySelectedStyle(), emptyStar);
initStarRankStyle(starRank.getSliderEmptyUnselectedStyle(), emptyStar);
initStarRankStyle(starRank.getSliderFullSelectedStyle(), fullStar);
initStarRankStyle(starRank.getSliderFullUnselectedStyle(), fullStar);
starRank.setPreferredSize(new Dimension(fullStar.getWidth() * 5, fullStar.getHeight()));
starRank.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
ServiceTask.getInstance().UpdateRank(id,starRank.getIncrements());
}
});
return starRank;
}
You didn't include the code for the initStarRankStyle but it's pretty obvious what you did here. You just relied on the behavior of the container. Table derives Container so it includes all of its methods e.g. add(Component).
But these methods won't work correctly since a table fetches its data from the model and invokes add internally. So you're logic is conflicting with the table.
You need to derive table and define how you want that data to be rendered. You can do that by overriding the method protected Component createCell(Object value, int row, int column, boolean editable) as explained here.

getting values from Database to JLabel

i have a table in the database of 4rows and 4columns. each column holds a different data.
now i want to retrieve all the data in the database and put them on JLabel on another form. i.e
in my Database i have.
packageName.....monthlyFee..... YearlyFee....... TotalFee
Regular......................150..................300....................450
Gold.........................300...................400..................700
..... ..... .... ....
now i have a form that i have put 4 empty JLabels in four rows but how do i retrieve the values from the database and place each value in the appropriate Label?.
This is what i've done but i still cant get around it. im stuck.
Thank you anyone.
public void getPrices()
{
String srt ="SELECT * FROM program_tbl";
try
{
con.connect();
ps = con.con.prepareStatement(srt);
rs = ps.executeQuery();
ResultSetMetaData data = rs.getMetaData();
int colums = data.getColumnCount();
while(rs.next())
{
Vector rows = new Vector();
for (int i = 1; i < colums; i++)
{
rows.addElement(rs.getObject(i));
}
.....................................................................
If you want to get this data as a string then you could probably try something like:
Vector<String> rows = new Vector<String>();
while(rs.next()) {
String rowEntry = rs.getString("packageName") +
rs.getString("monthlyFee") +
rs.getString("yearlyFee") +
rs.getString("totalFee") +
rows.add(rowEntry);
}
If not String, but an object to use later, then you can create a class:
public class MyObject {
private String packageName;
private int monthlyFee;
private int yearlyFee;
private int totalFee;
public MyObject (String name, int monthlyFee, int yearlyFee, int totalFee) {
this.packageName = name;
this.monthlyFee = monthlyFee;
this.yearlyFee = yearlyFee;
this.totalFee = totalFee;
}
/*Setters
*And
*Getters*/
}
And then use it as:
Vector<MyObject> rows = new Vector<MyObject>();
while (rs.next()) {
MyObject obj = new MyObject(rs.getString("packageName")
, rs.getInt("montlyFee")
, rs.getInt("yearlyFee")
, rs.getInt("totalFee")
);
rows.add(obj)
}
So say we now have a vector with String values - Vector<String> rows;
now i would like to create those JLabels.
JLabel[] myLabels = new JLabel[v.size()];
for(int i=0; i<rows.size(); i++) {
as[i] = new JLabel(rows.get(i));
}
And now we have an array of JLabels ready to be put to applet.
Don't use a JLabel. There is no way you can easily format the data so that you get tabular data.
Instead you should be using a JTable. Read the section from the Swing tutorial on How to Use Tables for more information. You can also search the forum for examples of using a JTable with a ResultSet.

adding rows with data from a Mysql table to jtable

Adding the colums works, but i am stuck when i want to add the data of the columns stored in a mysql database to the jtable. it ask for a object vector[][] but i have no clue what to give
Connection con;
DefaultTableModel model = new DefaultTableModel();
public Hoofdscherm() {
initComponents();
uitvoerSpelers.setModel(model);
try {
con = DriverManager.getConnection("jdbc:mysql://localhost/fullhouse", "root", "hamchi50985");
// selecteer gegevens uit fullhouse.speler tabel
PreparedStatement stat = con.prepareStatement("SELECT * FROM fullhouse.speler");
// sla deze GEGEVENS op in een resultset
ResultSet resultaat = stat.executeQuery();
// haal alle kolomnamen op PUUR VOOR DE MODEL VAN JTABLE
ResultSetMetaData data = resultaat.getMetaData();
String[] colum = new String[15];
for (int i = 1; i < data.getColumnCount(); i++) {
colum[i] = data.getColumnName(i);
model.addColumn(colum[i]);
while (resultaat.next()) {
Object[] gegevens = new String[] {resultaat.getString(1)};
model.addRow(gegevens[0]);
}
}
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, ex);
}
}
I think you need something like this.
Note
1. Also add your columns separate to resultset data. Like I showed in my code below.
Vector<String> rowOne = new Vector<String>();
rowOne.addElement("R1C1");
rowOne.addElement("R1C2");
Vector<String> rowTwo = new Vector<String>();
rowTwo.addElement("R2C1");
rowTwo.addElement("R2C2");
Vector<String> cols = new Vector<String>();
Vector<Vector> vecRow = new Vector<Vector>();
vecRow.addElement(rowOne);
vecRow.addElement(rowTwo);
cols.addElement("Col1");
cols.addElement("Col2");
JTable table = new JTable(vecRow, cols);
Edit
For you convenience and requirement You can follow code structure below.
Vector<String> rows = new Vector<String>();
Vector<Vector> dBdata = new Vector<Vector>();
// Add Columns to table
for (int i = 1; i < data.getColumnCount(); i++) {
colum[i] = data.getColumnName(i);
model.addColumn(colum[i]);
}
while (resultaat.next()) {
// add column data to rows vector
// Make sure that all data type is in string because of generics
rows.add(resultaat.getString("columnName1"));
rows.add(resultaat.getString("columnName2"));
rows.add(resultaat.getString("columnName3"));
// add whole row vector to dBdata vector
dBdata.addElement(rows);
}
model.addRow(dBdata);
Vector implements a dynamic array. It is similar to ArrayList, but with two differences:
Vector is synchronized.
Vector contains many legacy methods that are not part of the collections framework.
Class Vector Javadoc
I hope this will help you.
The line model.addRow(gegevens[0]);is incorrect.
You should do something like this:
String[] colum = new String[15];
for (int i = 1; i < data.getColumnCount(); i++) {
colum[i] = data.getColumnName(i);
model.addColumn(colum[i]);
while (resultaat.next()) {
Object[] gegevens = new String[] {resultaat.getString(1)};
model.addRow(gegevens);
}
}
Also you need to check DefaultTableModel
According to the documentation of DefaultTableModel:
This is an implementation of TableModel that uses a Vector of Vectors
to store the cell value objects.

JTable Swing retrieve data

I'm trying to populate a table with data from a database however i am having some issues with it. Could someone provide me with an example? (so the table takes in an Object[][] parameter for the data). I have the following basic code to display a table ;
class table extends JFrame
{
JTable table;
public table()
{
setLayout(new FlowLayout());
String[] columnNames = {"test","test","test"};
Object[][] data= {{"test","test","test"},{"test","test","test"}};
table = new JTable(data,columnNames);
table.setPreferredScrollableViewportSize(new Dimension(500,100));
table.setFillsViewportHeight(true);
JScrollPane scrollPane = new JScrollPane(table);
add(scrollPane);
}
}
Two years ago, during my time in technical school, I wrote a little library help solve some of the problems proposed by the exercises, which included a a DatabaseTableModel.
The class extends from AbstractTableModel, which means you can set it as the your JTable's data source.
Here's the algorithm that constructs a model from a ResultSet:
public final void constructModel(ResultSet rs) throws SQLException {
ResultSetMetaData rsmd = rs.getMetaData();
rs.last();
rowCount = rs.getRow();
int columnCount = rsmd.getColumnCount();
// DatabaseColumn simply holds a name and a Class<?>.
columns = new DatabaseColumn[columnCount];
// This is the Object[][] array that you were talking about.
// It holds all the data from the ResultSet.
data = new Object[columnCount][rowCount];
for (int i = 0; i < columnCount; ++i) {
// Figure out the column name and type.
int j = i + 1;
String colName = rsmd.getColumnLabel(j);
Class<?> colClass = String.class;
try {
colClass = Class.forName(rsmd.getColumnClassName(j));
} catch (ClassNotFoundException ex) {
colClass = String.class;
}
columns[i] = new DatabaseColumn(colName, colClass);
// Get the data in the current column as an Object.
rs.beforeFirst();
for (int k = 0; rs.next(); ++k) {
data[i][k] = rs.getObject(j);
}
}
// Notify listeners about the changes so they can update themselves.
fireTableStructureChanged();
}
The class worked when I used it in school, but it isn't exactly production code. When I look at it today, I start to see problems.
One problem is that it is loading the entire contents of the ResultSet into memory. Could get ugly pretty quickly.
Also, the algorithm isn't exactly optimal. It loops around with the database cursor as if it was nothing; I suppose that it would be less costly for the database if it had retrieved all the objects in the current row first and assigned them to their appropriate columns before moving on to the next row.
Nevertheless, I think it is a good enough starting point.

JTable 3 fields arrayList

I am trying to add values to a Jtable, the values are fetched from arrayList,
How do you do that
I tried making Object[][] data; and the populate it inside a loop, but it does not work, How do you fix this?
String[] columns = {"Field String","Field Double"," Field Double"};
Object[][] data;
Iterator<Node> itr = arrayList.iterator();
while (itr.hasNext()) {
Node el = itr.next();
double a = el.getval();
data[i][1] = el.getstring();
data[i][2] = a;
data[i][3] = a*4;
i++;
}
JFrame frame = new JFrame("Title ");
JTable tablE = new JTable(data, columnas);
JPanel panel = new JPanel();
panel.add(table);
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 500);
frame.setVisible(true);
How do you populate "data" inside a while loop?
Use a DefaultTableModel and add rows of data using its addRow(Object[]) or addRow(Vector) method. Set this as your JTable's model. The API and the JTable tutorial can get you started.
For e.g.,
ArrayList arrayList = new ArrayList();
String[] columns = {"Field String","Field Double"," Field Double"};
DefaultTableModel model = new DefaultTableModel(columns, 0);
for (Object item : arrayList) {
Object[] row = new Object[3];
//... fill in row with info from item
model.addRow(row);
}
JTable table = new JTable(model);
This demonstrates doing it with a for loop, but a while loop would be similar.

Categories