boolean error java console when trying to build - java

I seem to hit a java error in the following java code when i try to clean and build the project:
public class DisplayPerson extends javax.swing.JFrame{
String driverName = "net.sourceforge.jtds.jdbc.Driver";
String serverName = "xx";
String serverPort = "xx";
String database = serverName + ":" + serverPort;
String url = "jdbc:jtds:sqlserver:/" + database;
String username = "xx";
String password = "xx";
public DisplayPerson() throws SQLException {
ArrayList columnNames = new ArrayList();
ArrayList data = new ArrayList();
try {
Class.forName(driverName);
Connection connection = DriverManager.getConnection(url, username, password);
// Create and execute an SQL statement that returns some data.
String SQL = "";
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(SQL);
ResultSetMetaData rsmetadata = rs.getMetaData();
int columns = rsmetadata.getColumnCount();
// Get column names
for (int i = 1; i <= columns; i++)
{
boolean add;
add = columnNames.add( rsmetadata.getColumnName(i) );
}
// Get row data
while (rs.next())
{
ArrayList row;
row = new ArrayList(columns);
for (int i = 1; i <= columns; i++)
{
boolean add;
add = row.add( rs.getObject(i) );
}
boolean add;
add = data.add( row );
}
}
catch (SQLException e)
{
System.out.println( e.getMessage() );
} catch (ClassNotFoundException ex) {
Logger.getLogger(DisplayPerson.class.getName()).log(Level.SEVERE, null, ex);
}
// Create Vectors and copy over elements from ArrayLists to them
// Vector is deprecated but I am using them in this example to keep
// things simple - the best practice would be to create a custom defined
// class which inherits from the AbstractTableModel class
Vector columnNamesVector = new Vector();
Vector dataVector = new Vector();
for (int i = 0; i < data.size(); i++)
{
ArrayList subArray = (ArrayList)data.get(i);
Vector subVector = new Vector();
for (int j = 0; j < subArray.size(); j++)
{
boolean add;
add = subVector.add(subArray.get(j));
}
boolean add;
add = dataVector.add(subVector);
}
for (int i = 0; i < columnNames.size(); i++ )
boolean add
add = columnNamesVector.add(columnNames.get(i));
// Create table with database data
JTable table;
table = new JTable(dataVector, columnNamesVector)
{
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 );
getContentPane().add( scrollPane );
JPanel buttonPanel = new JPanel();
getContentPane().add( buttonPanel, BorderLayout.SOUTH );
}

you can avoid this error by changing this code
for (int i = 1; i <columnNames.size(); i++)
boolean add //here is a missing semicolon
add = columnNamesVector.add(columnNames.get(i));//variable declaration not allowed here
as follow
for (int i = 0; i < columnNames.size(); i++ ){
boolean add ;
add = columnNamesVector.add(columnNames.get(i));
}
Leaving off the brackets isn't good idea.

Related

Appending two Object[][]s together

How would I append an Object[][] to another Object[][]?
I have created Object dhadj[][] = new Object[0][6], which I've initialized to 0 because I don't know the number of rows, but I do know the number of columns.
In a loop I create another Object[][] called dha, and search for some data in the database. My intention is, at the end of every loop I want to add dha to dhadj using an append function. However, I get an error; there is a problem with converting array to object return (Object[][]) with temp.toArray().
What can I do to fix this? Is there another approach?
Here is my code:
Object dhadj[][] = new Object[0][6];
v = vector;
ro = size;
for (int i = 0; i < ro; i++) {
int d;
d = Integer.valueOf(v[i]);
query = "SELECT * FROM hadj WHERE id=?";
try (PreparedStatement preparedStatement = c.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY)) {
preparedStatement.setInt(1, d);
ResultSet rs = preparedStatement.executeQuery();
if (rs != null) {
rs.last();
int siz = rs.getRow();
rs.beforeFirst();
ResultSetMetaData rsMeta = rs.getMetaData();
int a = 0;
Object dha[][] = new String[siz][6]; //the neew object dha
while (rs.next()) {
dha[a][0] = rs.getString("id");
dha[a][1] = rs.getString("idh");
dha[a][2] = rs.getString("ticket");
dha[a][3] = rs.getString("montant");
dha[a][4] = rs.getString("datei");
dha[a][5] = rs.getString("nombrep");
a = a + 1;
}//end while
dhadj = appendValue(dhadj, dha); //here I add it using fuction
} else {
dhadj[0][0] = Integer.toString(d);
for (int ii = 1; ii < 6; ii++) {
dhadj[0][ii] = "";
}
}
}//end try
}//end for v
This is the function I'm using to append the arrays together:
private Object[][] appendValue(Object[][] obj, Object[][] newObj) {
ArrayList<Object> temp = new ArrayList<Object>(Arrays.asList(obj));
temp.add(newObj);
return (Object[][]) temp.toArray();
} //end appendvalue
If you don't know the number of elements, you should be using a List. I'd go with an ArrayList or an ArrayDeque:
List<Object[]> results = new ArrayList<>();
Object[] set = new Object[6];
Once you've finished creating your Object[] with the 6 results, call results.add(set);

how can I "refresh" my table, so that I could display same table with different data?

How can I "refresh" my table, so that I could display same table with different data?
String columnNames[] = {"First Name", "Last Name", "Phone Number", "E-mail"};
JTable contactTable = new JTable(data, columnNames);
jScrollPane = new JScrollPane(contactTable,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
where is your data saved ?
i save it in a text file and use this way to refresh my data but you need a button to refresh every time
here is my code
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
// Refresh Button
try {
for (int r = 0; r < 100; r++) { //initializing row
for (int c = 0; c < 4; c++) { //initializing column
jTable1.setValueAt(null, r, c);
}
}
BufferedReader rdfile = new BufferedReader(new FileReader("items.txt"));
String[] item = new String[100];
String[] temp;
int x = 0; //read item
while ((item[x] = rdfile.readLine()) != null) {
temp = item[x].split("\t");
jTable1.setValueAt((1000 + x + 1), x, 0);
for (int j = 1; j < 4; j++) {
jTable1.setValueAt(temp[j - 1], x, j);
}
x++;
}
rdfile.close();
} catch (IOException e) {
}
}

Update Jtable content in the gui without reinitating the method to redraw the table?

The method I've provided here is supposed to create a new table, perform the recall, and then update the table with the message that is received by the person contacted. It all works fine, except for the received message. I can even click the button again that initiates the recall and it then updates the table to include the message that was received, but nothing I add to the code seems to update the table automatically. As you can see here I've even tried completely redrawing the table and that doesn't work either. The only thing that actually makes the message show up is by re initiating the recall.
I've tried re validate and repaint but those don't seem to work.
public void doRecall() throws Exception {
newFrame = new JFrame("Recall Initiated Awaiting Replies");
newFrame.setSize(600, 300);
newFrame.setIconImage(img);
Member con = new Member();
String columnNames[] = { "First Name", "Last Name", "Phone No.",
"Response" };
Object[][] data = new Object[v.size()][4];
for (int j = 0; j < v.size(); j++) {
con = (Member) v.elementAt(k);
data[j][0] = con.getFName();
data[j][1] = con.getLName();
data[j][2] = con.getPhoneNo();
data[j][3] = con.getResponse();
k++;
}
k = 0;
abtable = new JTable(data, columnNames);
JScrollPane scrollPane = new JScrollPane(abtable);
abtable.setPreferredScrollableViewportSize(new Dimension(500, 370));
JPanel pane = new JPanel();
JLabel label = new JLabel("Members Currently In The Recall Roster");
pane.add(label);
newFrame.getContentPane().add(pane, BorderLayout.SOUTH);
newFrame.getContentPane().add(scrollPane, BorderLayout.CENTER);
newFrame.setLocation(screenWidth / 4, screenHeight / 4);
newFrame.setVisible(true);
String customMessage = getMessage();
k = 0;
for (int j = 0; j < v.size(); j++) {
con = (Member) v.elementAt(k);
try {
String toPhoneNumber = con.getPhoneNo();
customMessage = customMessage.replaceAll("\\s+", "+");
System.out.println(customMessage);
String requestUrl = ("http://cloud.fowiz.com/api/message_http_api.php?username=&phonenumber=+"
+ toPhoneNumber + "&message=" + customMessage + "&passcode=");
URL url = new URL(requestUrl);
HttpURLConnection uc = (HttpURLConnection) url.openConnection();
System.out.println(uc.getResponseMessage());
String reply = uc.getResponseMessage();
if (reply.equalsIgnoreCase("ok")) {
}
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
k++;
}
k = 0;
for (int j = 0; j < v.size(); j++) {
con = (Member) v.elementAt(k);
boolean phoneCheck = false;
while (phoneCheck != true) {
for (int j1 = 0; j1 < v.size(); j1++) {
con = (Member) v.elementAt(k);
mR2 = new MailReader();
String host = "pop.gmail.com";// change accordingly
String mailStoreType = "pop3";
String username = "";// change
// accordingly
String password = "";// change accordingly
MailReader.check(host, mailStoreType, username, password);
if (MailReader.searchForPhone(con.getPhoneNo()) == true) {
con.setResponse(MailReader.getReply(con.getPhoneNo()));
newFrame.addNotify();
System.out.println("IT WORKED");
newFrame.remove(scrollPane);
JTable abctable = new JTable(data, columnNames);
JScrollPane scrollPane2 = new JScrollPane(abctable);
newFrame.getContentPane().add(scrollPane2,
BorderLayout.CENTER);
abtable.repaint();
newFrame.repaint();
newFrame.revalidate();
phoneCheck = true;
}
}
}
}
}
When interacting with the data of the table, we want to use the TableModel of the table. The TableModel is what actually holds the data, and allows us to easily manipulate the data in the table.
You can either implement your own AbstractTableModel or use the DefaultTableModel, which already provides an implementation, that comes equipped with method for adding row and other goodies.
With DefaultTableModel, you can simply call the method addRow(Object[]) or addRow(Vector) to add a row dynamically at runtime. For example:
String columnNames[] = {
"First Name", "Last Name", "Phone No.", "Response" };
DefaultTableModel model = new DefaultTableModel(columnNames, 0):
JTable table = new JTable(model);
...
// dynamically add a row
Object[] row = { data1, data2, data2, data4 };
model.addRow(row);
The DefaultTableModel implementation will fire the necessary updates to call for a repainting of the table.
See the DefaultTableModel API for other useful methods and constructors. Add see How to Use Tables for general information on using tables.

INSERT row does not update JTable in GUI

As mentioned in the header I cannot get my JTable to update with a new row unless I restart the program. When I restart, the new row is there and everything is as it should be. I have tried revalidating/repainting the panel and frame, I have tried the fire methods. I'm at a loss. Thanks in advance
ActionListener (in adminGUI class) for 'Add' button:
if(source.equals(add2)){
String c = itb.getText();
int a = main.getResults();
boolean matches = Pattern.matches("[A-Z][a-z]+", c);
if(matches == true){
main.addGenre(a, c);
}
String Method(in main class) to add a row to the database table:
public static void addGenre(int a, String b){
int rowsAdded;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection connect =DriverManager.getConnection("jdbc:odbc:MovieDB");
Statement stmt = connect.createStatement();
String query = "INSERT INTO Genres (genre_id, genre_name)" + "VALUES(" + a + ", '" + b + "')";
rowsAdded = stmt.executeUpdate(query);
}catch(Exception exc){}
}
Method(also in main class) to increment the auto-increment-key column:
public static int getResults(){
int a = 0;
ResultSet ints = main.getResults("Select genre_id from Genres");
try {
while(ints.next()){
int d = ints.getInt("genre_id");
if(d>a){
a = d;
}
a++;
}
} catch (SQLException ex) {
Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
}
return a;
}
JTable details:
ResultSet rs1 = main.getResults("Select * from Genres");
JTable tab1 = new JTable(DbUtils.resultSetToTableModel(rs1));
DbUtils.resultSetToTableModel details :
public class DbUtils {
public static TableModel resultSetToTableModel(ResultSet rs) {
try {
ResultSetMetaData metaData = rs.getMetaData();
int numberOfColumns = metaData.getColumnCount();
Vector columnNames = new Vector();
// Get the column names
for (int column = 0; column < numberOfColumns; column++) {
columnNames.addElement(metaData.getColumnLabel(column + 1));
}
// Get all rows.
Vector rows = new Vector();
while (rs.next()) {
Vector newRow = new Vector();
for (int i = 1; i <= numberOfColumns; i++) {
newRow.addElement(rs.getObject(i));
}
rows.addElement(newRow);
}
return new DefaultTableModel(rows, columnNames);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
"I cannot get my JTable to update with a new row unless I restart the program."
I think what you're expecting is that when the database table update, so should your JTable. It doesn't really work like that. You need to update the TableModel, and the JTable will be automatically updated
Since resultSetToTableModel returns a DefuaultTableModel, you can use either of the two methods from DefaultTableModel:
public void addRow(Object[] rowData) - Adds a row to the end of the model. The new row will contain null values unless rowData is specified. Notification of the row being added will be generated.
public void addRow(Vector rowData) - Adds a row to the end of the model. The new row will contain null values unless rowData is specified. Notification of the row being added will be generated.
So when your are adding the data to the database, you also want to update the DefaultTableModel like this
public static void addGenre(Integer a, String b){
...
rowsAdded = stmt.executeUpdate(query);
if (rowsAdded > 0) {
DefaultTableModel model = (DefaultTableModel)tab1.getModel();
model.addRow( new Object[] { a, b });
}
}
Also noticed I changed the method signature to Integer instead of int so it will fit with the Object[] passed to addRow. The int you pass to it will get autoboxed to Integer
SIDE NOTES
Don't swallow you exception by putting nothing in the catch block. Put something meaningful that will notify you of any exceptions that may occur, like
catch(Exception ex) {
ex.printStackTrace();
}
You should also close your Connections, Statements, and ResultSets
You should use PreparedStatement instead of Statement, to avoid SQL injection.
private void resetListData() throws ClassNotFoundException, SQLException
{
Connection cne = null;
try {
Class.forName("org.sqlite.JDBC");
cne = DriverManager.getConnection("jdbc:sqlite:table.sqlite");
cne.setAutoCommit(false);
PreparedStatement psd = (PreparedStatement) cne.prepareStatement("Select * from Genres");
psd.execute();
ResultSet r = psd.getResultSet();
ResultSetMetaData rsmd = r.getMetaData();
int count = rsmd.getColumnCount();
String[] meta = new String[count];
for (int i = 0; i < count; i++)
{
String name = rsmd.getColumnName(i + 1);
meta[i] = name;
//System.out.println(name);
}
model = new DefaultTableModel(new Object[][]{}, new String[]{"name", "address"});
jTable1.setModel(model);
while (r.next())
{
Object[] row = new Object[count];
for (int i = 1; i <= count; ++i)
{
row[i - 1] = r.getString(i); // Or even rs.getObject()
}
model.addRow(row);
}
cne.close();
} catch (ClassNotFoundException | SQLException e) {
}
}
Use this code. so you can insert one row at the end of Jtable without restarting application.,
Thanks..

Unable to display header for jTable

These are my codes for my jTable in java swing.
private JTable getJTable() {
if (jTable == null) {
Vector columnNames = new Vector(); //Vector class allows dynamic array of objects
Vector data = new Vector();
JPanel panel = new JPanel();
panel.setSize(new Dimension(198, 106));
try {
DBController db = new DBController();
db.setUp("IT Innovation Project");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
String dsn = "IT Innovation Project";
String s = "jdbc:odbc:" + dsn;
Connection con = DriverManager.getConnection(s, "", "");
String sql = "Select * from forumTopics";
java.sql.Statement statement = con.createStatement();
ResultSet resultSet = statement.executeQuery(sql);
ResultSetMetaData metaData = resultSet.getMetaData();
int columns = metaData.getColumnCount();
for (int i = 1; i <= columns; i++) {
columnNames.addElement(metaData.getColumnName(i));
}
while (resultSet.next()) {
Vector row = new Vector(columns);
for (int i = 1; i <= columns; i++) {
row.addElement(resultSet.getObject(i));
}
data.addElement(row);
}
resultSet.close();
((Connection) statement).close();
} catch (Exception e) {
System.out.println(e);
}
jTable = new JTable(data, columnNames);
TableColumn column;
for (int i = 0; i < jTable.getColumnCount(); i++) {
column = jTable.getColumnModel().getColumn(i);
column.setMaxWidth(250);
}
String header[] = {"description", "title", "category", "posted by"};
for(int i=0;i<jTable.getColumnCount();i++) {
TableColumn column1 = jTable.getTableHeader().getColumnModel().getColumn(i);
column1.setHeaderValue(header[i]);
}
jTable.setBounds(new Rectangle(82, 218, 736, 292));
jTable.setEnabled(false);
jTable.setRowHeight(50);
jTable.getRowHeight();
}
return jTable;
}
I set an array for the header of my table. However, the program only shows the data inside my database without any header. Can somebody please enlighten me? Thanks in advance.
Put your JTable in JScrollPane like
add(new JScrollPane( getJTable() ) );

Categories

Resources