Forums

Skip to content

Advanced search
  • Quick links
    • Unanswered topics
    • Active topics
    • Search
  • FAQ
  • Login
  • Register
  • Board index Assistance Portage & Programming
  • Search

[JAVA] Need to refresh table in GUI...how?

Problems with emerge or ebuilds? Have a basic programming question about C, PHP, Perl, BASH or something else?
Post Reply
Advanced search
10 posts • Page 1 of 1
Author
Message
FcukThisGame
l33t
l33t
User avatar
Posts: 776
Joined: Wed Apr 20, 2005 10:01 pm
Location: /lost+found

[JAVA] Need to refresh table in GUI...how?

  • Quote

Post by FcukThisGame » Thu Jan 13, 2011 3:32 pm

I'm working on a ticket tracker application in java that connects to a mysql database. (code below).

One main issue with my code currently:


1) The table doesn't properly refresh. Main.refreshTickets() clears the tickets arraylist, repopulates it from the DB, updates rowData which is read directly by the table, and then I don't know what I need to do to repaint the table. table.repaint() does not work.

[resolved] Got ID lookups working by making staff a String[ID] with the actual string being the user's name.

TL;DR What's the standard procedure for refreshing a GUI in Java?

ActionListeners in GUI class:

Code: Select all

	public void actionPerformed(ActionEvent e) {
	        if (e.getActionCommand() == "close") {
	        	//get selected row
	        	int selectedRow = table.getSelectedRow();
	        	//get ticketID for selected row
	        	String closingTicket = data[selectedRow][0].toString();
	        	System.out.print("\nClose ticket # "+closingTicket);
	        	Main.sqlconnect.closeTicket(closingTicket, "21");
	        	
	        	//refresh table
	        	Main.refreshTickets();
	        }
	        if (e.getActionCommand() == "spam") {
	        	//get selected row
	        	int selectedRow = table.getSelectedRow();
	        	//get ticketID for selected row
	        	String spamTicket = data[selectedRow][0].toString();
	        	// mark ticket as spam
	        	System.out.print("\nMarking Ticket # "+spamTicket+" as SPAM");
	        	Main.sqlconnect.markSpam(spamTicket, "99");
	        	
	        	//refresh table
	        	Main.refreshTickets();
	        }
Main:

Code: Select all

package tracker;

import java.util.ArrayList;


public class Main {
	
	static ArrayList<TicketRootObject> tickets = new ArrayList<TicketRootObject>();
	static ArrayList<ITStaff> staff = new ArrayList<ITStaff>();
	static Connect sqlconnect;
	static GUI g;
	public static void main (String[] Args){
		javax.swing.SwingUtilities.invokeLater(new Runnable() {
	          public void run() {
	        	  //establish SQL connection
	        	  sqlconnect = new Connect();
	        	  
	        	  //get list of IT Staff
	        	  sqlconnect.getStaff();
	        	  	        	  
	        	  //pull current tickets from database
	        	  sqlconnect.getOpenTickets();
	        	  	        	  
	        	  // draw the GUI
	        	  g = new GUI();
	        	  g.drawGUI();
	          }
		});
	}
	static void refreshTickets() {
		tickets.clear();
		sqlconnect.getOpenTickets();
		g.frame.removeAll();
		g.drawGUI();
		
	}
}
Connect:

Code: Select all

package tracker;
import java.sql.*;
import java.util.ArrayList;


@SuppressWarnings("unused")
public class Connect{
	 
     private java.sql.Connection  con = null;
     private final String url = "jdbc:mysql://seeeeeeeecret";
               
     private final String userName = "secret";
     private final String password = "secret";
        
     // Constructor
     public Connect(){}
     
     
     
     private java.sql.Connection getConnection(){
          try{
               Class.forName("com.mysql.jdbc.Driver"); 
               con = java.sql.DriverManager.getConnection(url,userName,password);
               if(con!=null) System.out.println("Connection to MySQL database Successful");
          }catch(Exception e){
               e.printStackTrace();
               System.out.println("Error Trace in getConnection() : " + e.getMessage());
         }
          return con;
      }
     String runQuery(String query){
    	 java.sql.ResultSet rs = null;
         try{
             con= this.getConnection();
             Statement stmt = con.createStatement();
             rs = stmt.executeQuery(query+";");
             System.out.println(rs.getString(1));
             return rs.getString(1);
             
         } catch (Exception e){
        	 e.printStackTrace();
        	 return "ERROR";
         }
         
         	
     }
     void getDB(){
    	 java.sql.ResultSet rs = null;
         try{
             con= this.getConnection();
             Statement stmt = con.createStatement();
             rs = stmt.executeQuery("Select * from ticket_root order by date_init desc;");
             while (rs.next()) {
            	Main.tickets.add(new 
            			TicketRootObject(rs.getString(1),
            							rs.getString(2),
            							rs.getString(3),
            							rs.getString(4),
            							rs.getString(5),
            							rs.getString(6),
            							rs.getString(7),
            							rs.getString(8),
            							rs.getString(9),
            							rs.getBoolean(10),
            							rs.getString(11),
            							rs.getString(12),	
            							rs.getString(13),
            							rs.getString(14),
            							rs.getString(15)
            							)
            	);
            	
             }	
             
         } catch (Exception e){
        	 e.printStackTrace();
         }
     }
     
    
     void getOpenTickets(){
    	 java.sql.ResultSet rs = null;
         try{
             con= this.getConnection();
             Statement stmt = con.createStatement();
             rs = stmt.executeQuery("Select * from ticket_root where date_closed is null order by date_init desc;");
             while (rs.next()) {
            	Main.tickets.add(
            			new TicketRootObject(
            					rs.getString(1),
            					rs.getString(2),
            					rs.getString(3),
            					rs.getString(4),
            					rs.getString(5),
            					rs.getString(6),
            					rs.getString(7),
            					rs.getString(8),
            					rs.getString(9),
            					rs.getBoolean(10),
            					rs.getString(11),
            					rs.getString(12),	
            					rs.getString(13),
            					rs.getString(14),
            					rs.getString(15)
            					
            			));
            	
             }	
             
         } catch (Exception e){
        	 e.printStackTrace();
         }
     }
 
     void getStaff(){
    	 java.sql.ResultSet rs = null;
         try{
             con= this.getConnection();
             Statement stmt = con.createStatement();
             rs = stmt.executeQuery("Select * from user_list");
             while (rs.next()) {
            	Main.staff.add(
            			new ITStaff(
            					rs.getString(1),
            					rs.getString(2),
            					rs.getString(3),
            					rs.getBoolean(4)
            					)
            			);
            	
             }	
             
         } catch (Exception e){
        	 e.printStackTrace();
         }
     }
     private void closeConnection(){
          try{
               if(con!=null)
                    con.close();
               con=null;
          }catch(Exception e){
               e.printStackTrace();
          }
     }
     
     void markSpam(String ticketID, String closerID) {
    	 //marks a ticket as SPAM,
    	 //closes the ticket,
    	 //time stamps the closure
    	 //sets ticket's closer.
    	 java.sql.ResultSet rs = null;
         try{
             con= this.getConnection();
             Statement stmt = con.createStatement();
             // Mark as spam
             int rs2 = stmt.executeUpdate("update ticket_root set is_spam='1' where ticket_id is '"+ticketID+"'");
             // Close and time stamp it (by setting date_closed)
             rs2 = stmt.executeUpdate("update ticket_root set date_closed=now() where ticket_id='"+ticketID+"'");
             // Set ticket's closer
             rs2 = stmt.executeUpdate("update ticket_root set closer_id='"+closerID+"' where ticket_id='"+ticketID+"';");
             //Log it
             System.out.print("\nTicket #"+ticketID+" has been marked as spam by "+idToName(closerID)+".");
             
         } catch (Exception e){
        	 e.printStackTrace();
         }
     }
     void closeTicket(String ticketID, String closerID) {
    	 //marks a ticket as SPAM,
    	 //closes the ticket,
    	 //time stamps the closure
    	 //sets ticket's closer.
    	 java.sql.ResultSet rs = null;
         try{
             con= this.getConnection();
             Statement stmt = con.createStatement();
             // Close and time stamp it (by setting date_closed)
             int rs2 = stmt.executeUpdate("update ticket_root set date_closed=now() where ticket_id='"+ticketID+"'");
             // Set ticket's closer
             rs2 = stmt.executeUpdate("update ticket_root set closer_id='"+closerID+"' where ticket_id='"+ticketID+"';");
             System.out.print("\nTicket #"+ticketID+" has been closed by "+idToName(closerID)+".");
             
         } catch (Exception e){
        	 e.printStackTrace();
         }
     }
     String idToName(String ID) {
    	 java.sql.ResultSet rs = null;
    	 String displayName=null;
    	 try{
    		 con= this.getConnection();
             Statement stmt = con.createStatement();
             rs=stmt.executeQuery("select display_name from user_list where user_id = "+ID);
             while (rs.next()) {
            	 displayName = rs.getString(1);
            	 }
         } catch (Exception e){
        	 e.printStackTrace();
    	 }
         return displayName;
     }
     
}

Sysadmin by trade, geek by choice

DESKTOP:
i7-3770K|8800GTS-512|32GB|1x256GB SSD|4x1TB|HD/BDROM|1920x1200+1680x1050
Win8 Pro w/ Hyper-V|Server 2012 VM|Ubuntu VM|Gentoo VM

TABLET: Samsung Ativ 700t
i5-3317U|4GB|128GB SSD|1920x1080 Touch
Win8
Top
doubleagent
Guru
Guru
User avatar
Posts: 444
Joined: Fri Apr 15, 2005 4:12 am
Location: 127.0.0.1

  • Quote

Post by doubleagent » Fri Jan 14, 2011 6:49 am

Just glancing at the code (I didn't read it) I'm guessing your GUI object is whatever you need to repaint, or you've encapsulated it there.

Looking over some old code of mind you need to implement or overwrite paintComponent(Graphics g). Don't forget to call super.paintComponent(g). Calling repaint() on the object should initiate dispatch.

EDIT: Swing is very buggy, btw. Expect to faff about with workarounds.
EDIT2: Here's a simple class from one of my old projects: http://ompldr.org/vNnpjdA
shickapooka wrote:i think they programmed [otw] based on a right-wing jewish-nigger-nazi, his gay, retarded, left-wing love slave with webbed feet, and their three headed cat that poops uncontrollably. the cat is also an apple fanboy
Top
sera
Retired Dev
Retired Dev
Posts: 1017
Joined: Fri Feb 29, 2008 3:03 pm
Location: CET

  • Quote

Post by sera » Fri Jan 14, 2011 9:50 am

Code: Select all

               // draw the GUI
                g = new GUI();
                g.drawGUI();
Rather suspicious. What is your GUI class and why do you call drawGUI() instead of the setVisible(true).

Code: Select all

if (e.getActionCommand() == "close")
Install a window listener instead.

Code: Select all

   static void refreshTickets() {
      tickets.clear();
      sqlconnect.getOpenTickets();
      g.frame.removeAll();
      g.drawGUI();
      
   } 
Where do you update the table model? You call drawGUI() again?

Please post the GUI class.
Top
zixnub
n00b
n00b
User avatar
Posts: 67
Joined: Thu Dec 27, 2007 5:53 pm
Location: Brasschaat, Belgium

  • Quote

Post by zixnub » Fri Jan 14, 2011 10:24 am

Code: Select all

if (e.getActionCommand() == "close")
Another thing, String comparison through == is a no no.
https://github.com/udevbe/greenfield
https://github.com/udevbe/westfield
Top
x22
Apprentice
Apprentice
Posts: 208
Joined: Mon Apr 24, 2006 10:19 am

  • Quote

Post by x22 » Fri Jan 14, 2011 12:58 pm

Standard procedure for refreshing data in JTable is to make your table model class extend AbstractTableModel and use appropriate fire???() method when necessary (in this case it should be fireTableDataChanged()).

(DefaultTableModel should do this automatically in all methods which change the table data but I recommend using your own model class if the table data can change.)
Top
doubleagent
Guru
Guru
User avatar
Posts: 444
Joined: Fri Apr 15, 2005 4:12 am
Location: 127.0.0.1

  • Quote

Post by doubleagent » Sat Jan 15, 2011 5:02 am

zixnub wrote:

Code: Select all

if (e.getActionCommand() == "close")
Another thing, String comparison through == is a no no.
Yeah. Use e.getActionCommand().equals("close")
shickapooka wrote:i think they programmed [otw] based on a right-wing jewish-nigger-nazi, his gay, retarded, left-wing love slave with webbed feet, and their three headed cat that poops uncontrollably. the cat is also an apple fanboy
Top
Shadow Skill
Veteran
Veteran
Posts: 1023
Joined: Sat Dec 04, 2004 8:37 pm

  • Quote

Post by Shadow Skill » Sun Jan 23, 2011 5:09 am

Why is it bad to use == for string comparisons?
Ware wa mutekinari.
Wa ga kage waza ni kanau mono nashi.
Wa ga ichigeki wa mutekinari.

"First there was nothing, so the lord gave us light. There was still nothing, but at least you could see it."
Top
The Doctor
Bodhisattva
Bodhisattva
User avatar
Posts: 2678
Joined: Tue Jul 27, 2010 10:56 pm

  • Quote

Post by The Doctor » Sun Jan 23, 2011 6:48 am

because saying stringa == stringb means:
Does string a live at the same memory location as string b? aka it checks to see if the strings are the same string being pointed at by two pointers (OK thats bad java, but you get the idea)
stringa.equals(stringb);
means go to stringa's equals method and pass in stringb. This checks the length of the char array (string length) and compares each char in the array for equality.

the == equality check only works for primitive types. anything that extends object, ie everything you or the gods at formerly Sun Microsystems wrote uses the equals method.

on the subject of the equals method, the gods also say that thou shalt override the the equals method and the toString method like so

Code: Select all

@Override// overide notation. makes sure the compiler overrides the method in Object
public boolean equals(Object o){
 // equality checks
return false;// really return what the test shows
}

@Override
public String toString(){
return ""; // really return a string representation of this object. usful for saying System.out.println(this); for debuging or for data return
}
there are other methods, but those two are the biggest.
Java API here
First things first, but not necessarily in that order.

Apologies if I take a while to respond. I'm currently working on the dematerialization circuit for my blue box.
Top
The Doctor
Bodhisattva
Bodhisattva
User avatar
Posts: 2678
Joined: Tue Jul 27, 2010 10:56 pm

  • Quote

Post by The Doctor » Sun Jan 23, 2011 6:58 am

form a immutable stand point, I would kill the old JTable and make a new one whenever you change information.
It is a more "thread safe" approach (not that GUI elements need to be, swing is thread unsafe anyway), and the JPanel is easier to use.
First things first, but not necessarily in that order.

Apologies if I take a while to respond. I'm currently working on the dematerialization circuit for my blue box.
Top
The Doctor
Bodhisattva
Bodhisattva
User avatar
Posts: 2678
Joined: Tue Jul 27, 2010 10:56 pm

  • Quote

Post by The Doctor » Sun Jan 23, 2011 5:31 pm

I was playing with the table this morning, I got it to work like this:

Code: Select all

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableModel;


public class JTableTest {
	private JFrame frame;
	private JPanel panel;
	private JButton button;
	private JTable table;
	boolean state = false;
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		JTableTest test = new JTableTest();
		test.GUI();
	}
	
	public void GUI(){
		/* the following code is direcly out of the API
		 * 
		 */
		   TableModel dataModel = new AbstractTableModel() {
		          public int getColumnCount() { return 10; }		// sets the number of columns
		          public int getRowCount() { return 10;}			// sets the number of rows
		          public Object getValueAt(int row, int col) { return new Integer(row*col); }	// returns the data at row and column
		      };
		      table = new JTable(dataModel);
		      JScrollPane scrollpane = new JScrollPane(table);
		   // end of API paste  
		      
		frame = new JFrame("This is only a Test");
		JPanel data = new JPanel();
		data.setLayout(new BorderLayout());
		
		panel = new JPanel();		// make a jpanel
		panel.add(scrollpane);		// add the table
		frame.add(panel);			// add the content to the window
		button = new JButton("new data");
		button.addActionListener(new ButtonListener());
		data.add(button,BorderLayout.SOUTH);
		data.add(panel,BorderLayout.CENTER);
		frame.add(data);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);	// make sure the frame EXITS on close instead of running in the background
		frame.setSize(600, 600);
		frame.setVisible(true);		// show the frame
	}
	
	public class ButtonListener implements ActionListener{
		public void actionPerformed(ActionEvent e) {
			if(state){	// use the state as a switch
				 TableModel dataModel = new AbstractTableModel() {
			          public int getColumnCount() { return 10; }
			          public int getRowCount() { return 10;}
			          public Object getValueAt(int row, int col) { return new Integer(row*col); }
			      };
				table.setModel(dataModel);
				state = false;
			} else {	// else we are in second state
				 TableModel dataModel = new AbstractTableModel() {
			          public int getColumnCount() { return 10; }
			          public int getRowCount() { return 10;}
			          public Object getValueAt(int row, int col) { return new Integer(2*row*col); }
			      };
			      table.setModel(dataModel);
				state = true;
			}	// en if else
		}	// end of action preformed
	}		// end of nesed class

}
I hope that helps. if not, lets see you GUI class
First things first, but not necessarily in that order.

Apologies if I take a while to respond. I'm currently working on the dematerialization circuit for my blue box.
Top
Post Reply

10 posts • Page 1 of 1

Return to “Portage & Programming”

Jump to
  • Assistance
  • ↳   News & Announcements
  • ↳   Frequently Asked Questions
  • ↳   Installing Gentoo
  • ↳   Multimedia
  • ↳   Desktop Environments
  • ↳   Networking & Security
  • ↳   Kernel & Hardware
  • ↳   Portage & Programming
  • ↳   Gamers & Players
  • ↳   Other Things Gentoo
  • ↳   Unsupported Software
  • Discussion & Documentation
  • ↳   Documentation, Tips & Tricks
  • ↳   Gentoo Chat
  • ↳   Gentoo Forums Feedback
  • ↳   Duplicate Threads
  • International Gentoo Users
  • ↳   中文 (Chinese)
  • ↳   Dutch
  • ↳   Finnish
  • ↳   French
  • ↳   Deutsches Forum (German)
  • ↳   Diskussionsforum
  • ↳   Deutsche Dokumentation
  • ↳   Greek
  • ↳   Forum italiano (Italian)
  • ↳   Forum di discussione italiano
  • ↳   Risorse italiane (documentazione e tools)
  • ↳   Polskie forum (Polish)
  • ↳   Instalacja i sprzęt
  • ↳   Polish OTW
  • ↳   Portuguese
  • ↳   Documentação, Ferramentas e Dicas
  • ↳   Russian
  • ↳   Scandinavian
  • ↳   Spanish
  • ↳   Other Languages
  • Architectures & Platforms
  • ↳   Gentoo on ARM
  • ↳   Gentoo on PPC
  • ↳   Gentoo on Sparc
  • ↳   Gentoo on Alternative Architectures
  • ↳   Gentoo on AMD64
  • ↳   Gentoo for Mac OS X (Portage for Mac OS X)
  • Board index
  • All times are UTC
  • Delete cookies

© 2001–2026 Gentoo Foundation, Inc.

Powered by phpBB® Forum Software © phpBB Limited

Privacy Policy

 

 

magic