Urgent: Repaint, JTable, JPanel...

I know there've been a few posts about using repaint() for JTable...but my layout's a bit different than the ones already mentioned and trying to update my table is driving me crazy...
i have a table class which extends a JPanel...
an instance of this is created in a separate class within a JPanel...THIS Panel is inside a scrollpane (the table itself isn't)...this class has a button, on the click of which the table needs to be updated.
Now, should i be repainting the table, the table's panel, the parent panel, or the scrollpane? Or should i be doing something compeltely different?
PLEASE HELP!

[http://forum.java.sun.com/thread.jspa?threadID=5306228&tstart=0]

Similar Messages

  • Repaint() in JPanel doesn't align correctly

    Hey all,
    I'm running into this problem with a program I'm writing for work. It's basically a dispatch board which connects to our SQL server via ODBC. When the user presses a "Next" or "Prev" button, the dates will change and show the dispatching for the next or previous week respectively. However, the refreshed components go where they are supposed to, but the old screen is underneath, and shifted slightly so that nothing aligns. In turn, you can make heads or tails as to what's happening. However, if you select File -> Refresh from my menubar (calls repaint() the same way) everything is repainted correctly. Any ideas?
    package dispatchBoard.DispatchBoard;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Font;
    import java.awt.Graphics;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.awt.event.MouseMotionListener;
    import java.util.Calendar;
    import java.util.GregorianCalendar;
    import java.sql.*;
    import javax.swing.JPanel;
    import sun.misc.Queue;
    public class DB_MainWindow extends JPanel implements MouseListener{
         private static final long serialVersionUID = 1L;
         private int _xRes, _yRes;
         private int _techs;
         private String _dayOption, _monday, _tuesday, _wednesday, _thursday, _friday, _odbcName, _databaseName, _currYear;
         private String[] _months;
         private Tech _myTechList;
         private Font _defaultFont;
         DB_Frame _mainFrame;
         private Calendar cal = new GregorianCalendar();
         public DB_MainWindow(String _resolution, String optionString, String ofTechs, DB_Frame frame, String _odbc, String _database, String _year)
              _xRes = Integer.valueOf(_resolution.substring(0, findCharPosition(_resolution, 'x'))).intValue() - 5;
              _yRes = Integer.valueOf(_resolution.substring(findCharPosition(_resolution, 'x')+1)).intValue() - 30;
              _techs = Integer.valueOf(ofTechs).intValue();
              _dayOption = optionString;
              _mainFrame = frame;
              _odbcName = _odbc;
              _databaseName = _database;
              _currYear = _year;
              setDaysFiveStraight();
              System.out.println(_xRes + " " + _yRes);
              this.setBackground(Color.GRAY);
              this.setPreferredSize(new Dimension(_xRes,_yRes));
              this.addMouseListener(this);
         public void paint(Graphics g)
              _myTechList = null;
              int _spacing = 0;
              int _spacing2 = 0;
              g.setColor(Color.BLACK);
              g.drawLine(60,0,60,_yRes);
              _defaultFont =g.getFont();
              //draw tech barriers
              for (int i = 1; i < _techs+1; i ++)
                   _spacing = _yRes / (_techs+1);
                   g.drawLine(0, _spacing*i, 1366, _spacing*i);
              //draw day barriers
              for (int j = 1; j < 5; j++)
                   _spacing2 = (_xRes-60) / 5;
                   g.drawLine(_spacing2*j + 60, 0, _spacing2*j + 60, 768);
              int _curPos = 60, _timePos = 0;
              int _time[] = {8,9,10,11,12,1,2,3,4,5};
              for (int k = 0; k < 5; k++)
                   _curPos = 60+(k*_spacing2);
                   for (int l = 0; l < 9; l++)
                        g.drawLine( _curPos + (l*(_spacing2/9)), 0+_spacing, _curPos + (l*(_spacing2/9)), _yRes);
                        String _tempString = ""+_time[_timePos];
                        g.drawString(_tempString, _curPos + (l*(_spacing2/9)), _spacing);
                        _timePos++;
                   _timePos = 0;
              //draw graph labels
              System.out.println(_dayOption);
              g.drawString("TECHS", 10, _spacing);
              g.drawString("Monday "+_monday, 60+(_spacing2/2) - 23, _spacing/2);
              g.drawString("Tuesday "+_tuesday, 60+_spacing2+(_spacing2/2) - 26, _spacing/2);
              g.drawString("Wednesday "+_wednesday, 60+2*_spacing2+(_spacing2/2) - 33, _spacing/2);
              g.drawString("Thursday "+_thursday, 60+3*_spacing2+(_spacing2/2) - 28, _spacing/2);
              g.drawString("Friday "+_friday, 60+4*_spacing2+(_spacing2/2) - 25, _spacing/2);
               * At this point the default grid, including all labels, have been drawn on
               * the dispatch board.  Now, we have to fetch the data from the SQL server,
               * place it into some sort of form (possibly 2d array?!) and then print it out
               * on the board....
               * Here goes!
    //          this.addMouseMotionListener(this);
    //          g.drawRect(_mousePosition.x, _mousePosition.y, 10, 10);
              fillInTimes(g, _spacing, _spacing2);
         public void setDaysFiveStraight()
              if (_dayOption.equals(new String("work_week")))
                   _monday = new String("");
                   _tuesday = new String("");
                   _wednesday = new String("");
                   _thursday = new String("");
                   _friday = new String("");
                   String[] _months2 = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"};
                   _months = _months2;
                    * Sunday = 1
                    * Monday = 2
                   System.out.println("DAY OF THE WEEK = "+cal.get(Calendar.DAY_OF_WEEK));
                   if (cal.get(Calendar.DAY_OF_WEEK) == 2)
                        _monday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+1);
                        _tuesday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+1);
                        _wednesday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+1);
                        _thursday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+1);
                        _friday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                   else if (cal.get(Calendar.DAY_OF_WEEK) == 3)
                   {     //tuesday
                        _tuesday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        System.out.println("TUESDAY = "+_tuesday);
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+1);
                        _wednesday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+1);
                        _thursday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+1);
                        _friday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)-4);
                        _monday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                   else if (cal.get(Calendar.DAY_OF_WEEK) == 4)
                        _wednesday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+1);
                        _thursday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+1);
                        _friday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)-4);
                        _monday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+1);
                        _tuesday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        //System.out.println("TUESDAY = "+_tuesday);
                   else if (cal.get(Calendar.DAY_OF_WEEK) == 5)
                   {     //thursday
                        _thursday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+1);
                        _friday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)-4);
                        _monday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+1);
                        _tuesday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+1);
                        _wednesday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                   else if (cal.get(Calendar.DAY_OF_WEEK) == 6)
                   {     //friday
                        _friday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)-4);
                        _monday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+1);
                        _tuesday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+1);
                        _wednesday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+1);
                        _thursday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
         private void fillInTimes(Graphics g, int _spacing, int _spacing2) {
              // need to get the data first, building pre-defined array for test data...
              //****START REAL DATA LOAD****\\
    //          Calendar cal = new GregorianCalendar();
             try {
                 // Load the JDBC-ODBC bridge
                 Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver");
                 // specify the ODBC data source's URL
                 String url = "jdbc:odbc:"+_odbcName;
                 // connect
                 Connection con = DriverManager.getConnection(url,"sa",_currYear);
                 // create and execute a SELECT
                 Statement stmt = con.createStatement();
                 Statement stmt2 = con.createStatement();
                 ResultSet techList = stmt2.executeQuery("USE "+_databaseName+" SELECT Distinct(SV00301.Technician) from SV00301 join SV00115 on SV00301.Technician = SV00115.Technician where SV00115.SV_Inactive<>1");
                 // traverse through results
                 Tech temp;
                 int counter = 0;
                 while(techList.next())
                      if (_myTechList == null)
                           _myTechList = new Tech(techList.getString(1).trim());
                           System.out.println(_myTechList.getName());
                           counter++;
                      else if (!_myTechList.hasNext())
                           _myTechList.setNext(new Tech(techList.getString(1).trim()));
                           System.out.println(_myTechList.getNext().getName());
                           counter++;
                      else
                           temp = _myTechList.getNext();
                           while(temp.hasNext())
                                temp = temp.getNext();
                           temp.setNext(new Tech(techList.getString(1).trim()));
                           System.out.println(temp.getNext().getName());
                           counter++;
    //             printTechList();
                 String nextMonth, prevMonth;
                 if(cal.get(Calendar.MONTH)==11)
                      nextMonth=_months[0];
                 else
                      nextMonth = _months[cal.get(Calendar.MONTH)+1];
                 if(cal.get(Calendar.MONTH) == 0)
                      prevMonth = _months[11];
                 else
                      prevMonth = _months[cal.get(Calendar.MONTH)-1];
                 ResultSet rs = stmt.executeQuery
                 ("USE "+_databaseName+" SELECT * from SV00301 JOIN SV00300 on SV00300.Service_Call_ID = SV00301.Service_Call_ID JOIN SV00115 on SV00300.Technician = SV00115.Technician JOIN SV000805 on SV000805.Service_Call_ID = SV00301.Service_Call_ID and SV000805.Note_Service_Index='Description' where (Month(SV00301.Task_Date)="+_months[cal.get(Calendar.MONTH)]+" or Month(SV00301.Task_Date)="+prevMonth+" or Month(SV00301.Task_Date)="+nextMonth+") and SV00300.Status_of_Call='OPEN' and SV00115.SV_Inactive<>1");
                 System.out.println("USE "+_databaseName+" SELECT * from SV00301 JOIN SV00300 on SV00300.Service_Call_ID = SV00301.Service_Call_ID JOIN SV00115 on SV00300.Technician = SV00115.Technician JOIN SV000805 on SV000805.Service_Call_ID = SV00301.Service_Call_ID and SV000805.Note_Service_Index='Description' where (Month(SV00300.Date_of_Service_Call)="+_months[cal.get(Calendar.MONTH)]+" or Month(SV00300.Date_of_Service_Call)="+prevMonth+" or Month(SV00300.Date_of_Service_Call)="+nextMonth+") and SV00300.Status_of_Call='OPEN' and SV00115.SV_Inactive<>1");
                  while (rs.next()) {
                      // get current row values
                       String servicecallid = rs.getString(1).trim(),
                               tech = rs.getString(4).trim(),
                               rawDate = rs.getString(6).trim(),
                               startTime = rs.getString(7).trim(),
                               _length = rs.getString(9).trim(),
                               description = rs.getString(33).trim(),
                               customernumber = rs.getString(35).trim(),
                               custname = rs.getString(45).trim(),
                               location = rs.getString(46).trim(),
                               calltype = rs.getString(54).trim(),
                               notes = rs.getString(268).trim();   
    //                  String formattedDate = month+"/"+day+"/"+year;
    //                  System.out.println(formattedDate);
    //                  String tech = rs.getString(142).trim();
    //                  String rawDate = rs.getString(144);
                      System.out.println(rawDate);
                      String day = rawDate.substring(8,10);
                      String month = rawDate.substring(5,7);
                      String year = rawDate.substring(0,4);
                      formatNumber(day);
                      formatNumber(month);
    //                  startTime = rs.getString(145);
    //                  String _length = rs.getString(147);
                      int hour = Integer.valueOf(startTime.substring(11,13)).intValue();
                      String minute = startTime.substring(14,16);
                      int minutes = Integer.valueOf(minute).intValue();
                      minutes = minutes / 60;
                      double length = (Integer.valueOf(_length).intValue())/100;
                      // print values
                      //System.out.println ("Service_Call_ID = " + Surname);
                      if (hour!=0)
                           sortJob(new Job(servicecallid, custname, new MyDate(month,day,year), hour+minutes,length, description, customernumber, location, calltype, notes), _myTechList, tech);
                  // close statement and connection
                  stmt.close();
                  con.close();
                  catch (java.lang.Exception ex) {
                      ex.printStackTrace();
              //draw techs and blocks of jobs!!!!!
              //***TECHS***\\
             Tech _tempTech = new Tech("DOOKIE");
              int multiplier = 2;
              if (_myTechList.hasNext())
                   g.setColor(Color.BLACK);
                   _tempTech = _myTechList.getNext();
                   g.drawString(_myTechList.getName(),5,(_spacing)*multiplier);
                   System.out.println("printJobs(g, "+_myTechList.getName()+","+multiplier+","+_spacing+","+_spacing2+")");
                   printJobs(g,_myTechList,multiplier, _spacing,_spacing2);
                   multiplier++;
              while(_tempTech.hasNext())
                   g.setColor(Color.BLACK);
                   g.drawString(_tempTech.getName(),5,(_spacing)*multiplier);
                   System.out.println("printJobs(g, "+_tempTech.getName()+","+multiplier+","+_spacing+","+_spacing2+")");
                   printJobs(g,_tempTech,multiplier, _spacing,_spacing2);
                   multiplier++;
                   _tempTech = _tempTech.getNext();
              g.setColor(Color.BLACK);
              g.drawString(_tempTech.getName(),5,(_spacing)*multiplier);
              System.out.println("printJobs(g, "+_tempTech.getName()+","+multiplier+","+_spacing+","+_spacing2+")");
              printJobs(g,_tempTech,multiplier, _spacing,_spacing2);
              //***TIME BLOCKS***\\\
         private void printTechList() {
              // TODO Auto-generated method stub
              boolean temp = !_myTechList.hasNext();
              Tech tempTech = _myTechList;
              System.out.println("BEGINNING TECH LIST PRINTOUT!!!!");
              while (tempTech.hasNext() || temp)
                   System.out.println(tempTech.getName());
                   if (temp)
                        temp = !temp;
                   else
                        tempTech = tempTech.getNext();
              System.out.println(tempTech.getName());
              System.out.println("END TECH LIST PRINTOUT!!!");
         private void formatNumber(String month) {
              // TODO Auto-generated method stub
              if (month.equals(new String("01")))
                   month = new String("1");
              else if (month.equals(new String("02")))
                   month = new String("2");
              else if (month.equals(new String("03")))
                   month = new String("3");
              else if (month.equals(new String("04")))
                   month = new String("4");
              else if (month.equals(new String("05")))
                   month = new String("5");
              else if (month.equals(new String("06")))
                   month = new String("6");
              else if (month.equals(new String("07")))
                   month = new String("7");
              else if (month.equals(new String("08")))
                   month = new String("8");
              else if (month.equals(new String("09")))
                   month = new String("9");
         private void printJobs(Graphics g, Tech techList, int multiplier, int _spacing, int _spacing2) {
              Job tempJob = techList.getJobs();
              boolean temp = false;
              if (tempJob != null)
              {     temp = !tempJob.hasNext();
              while (tempJob.hasNext() || temp)
                   g.setColor(Color.RED);
                   String _tempDate = new String(tempJob.getDate().toString());
    //               System.out.println("This job has date of: "+_tempDate);
                   int horizontalMultiplier = 0;
                   if (_tempDate.equals(_monday))
                        horizontalMultiplier = 0;
                   else if (_tempDate.equals(_tuesday))
                        horizontalMultiplier = 1;
                   else if (_tempDate.equals(_wednesday))
                        horizontalMultiplier = 2;
                   else if (_tempDate.equals(_thursday))
                        horizontalMultiplier = 3;
                   else if (_tempDate.equals(_friday))
                        horizontalMultiplier = 4;
                   else
                        horizontalMultiplier = 5;
    //               System.out.println("HorizontalMultiplier = "+horizontalMultiplier);
                   if (horizontalMultiplier !=5)
                        if (tempJob.getJobCallType().equals(new String("TM"))) g.setColor(new Color(0,255,0));
                        else if (tempJob.getJobCallType().equals(new String("SU"))) g.setColor(new Color(0,255,255));
                        else if (tempJob.getJobCallType().equals(new String("SPD"))) g.setColor(new Color(44,148,67));
                        else if (tempJob.getJobCallType().equals(new String("QUO"))) g.setColor(new Color(0,255,255));
                        else if (tempJob.getJobCallType().equals(new String("MCC"))) g.setColor(new Color(255,0,255));
                        else if (tempJob.getJobCallType().equals(new String("MC"))) g.setColor(new Color(128,0,255));
                        else if (tempJob.getJobCallType().equals(new String("CBS"))) g.setColor(new Color(0,0,255));
                        else if (tempJob.getJobCallType().equals(new String("AS"))) g.setColor(new Color(255,255,255));
                        else g.setColor(Color.red);
                        g.fillRect(/*START X*/(int)(60+(horizontalMultiplier*_spacing2)+(tempJob.getStarTime()-8)*(_spacing2/9)+1),/*START Y*/_spacing*(multiplier-1)+1,/*LENGTH*/(int)(tempJob.getJobLength()*(_spacing2/9)-1),/*WIDTH*/_spacing-1);
                        System.out.println("g.fillRect("+((int)(60+(horizontalMultiplier*_spacing2)+(tempJob.getStarTime()-8)*(_spacing2/9)+1))+","+(_spacing*(multiplier-1)+1)+","+((int)(tempJob.getJobLength()*(_spacing2/9)-1))+","+(_spacing-1)+") :: Multiplier = "+multiplier+" :: JOB NAME = "+tempJob.getJobName()+" :: JOB NUMBER = "+tempJob.getJobNumber());
                        g.setColor(Color.BLACK);
                        g.setFont(new Font("Monofonto", Font.PLAIN, 22));
                        if ((int)(tempJob.getJobLength()*(_spacing2/9)-1) >0)
                             g.drawString(formatStringLength(tempJob.getJobName().toUpperCase(), tempJob.getJobLength()), (int)(60+(horizontalMultiplier*_spacing2)+(tempJob.getStarTime()-8)*(_spacing2/9)+1), (_spacing*(multiplier)+1)-_spacing/2+5);
                        g.setFont(_defaultFont);
                        if (!temp)
                             tempJob = tempJob.getNext();
                             if (tempJob.hasNext() == false)
                                  temp = true;
                        else
                             temp = !temp;
                   else
                        System.out.println("*g.fillRect("+((int)(60+(horizontalMultiplier*_spacing2)+(tempJob.getStarTime()-8)*(_spacing2/9)+1))+","+(_spacing*(multiplier-1)+1)+","+((int)(tempJob.getJobLength()*(_spacing2/9)-1))+","+(_spacing-1)+") :: Multiplier = "+multiplier+" :: JOB NAME = "+tempJob.getJobName()+" :: JOB NUMBER = "+tempJob.getJobNumber());
                        if (!temp)
                             tempJob = tempJob.getNext();
                             if (tempJob.hasNext() == false)
                                  temp = true;
                        else
                             temp = !temp;
         //     g.fillRect((int)(60+(tempJob.getStarTime()-8)*(_spacing2/9)+1),_spacing*(multiplier-1)+1,(int)(tempJob.getJobLength()*(_spacing2/9)-1),_spacing-1);
         private String formatStringLength(String string, double jobLength) {
              // TODO Auto-generated method stub
              if (jobLength*3>string.length())
                   return string;
              return string.substring(0, new Double(jobLength*3).intValue());
         private void sortJob(Job job, Tech techList, String techName) {
              Tech _tempTech2;
              if (techName.equals(techList.getName()))
                   techList.insertJob(job);
                   System.out.println("ADDED " + job.getJobName() +" TO " + techName);
              else
                   _tempTech2 = techList.getNext();
                   while (!_tempTech2.getName().equals(techName) && _tempTech2.hasNext())
                        _tempTech2 = _tempTech2.getNext();
    //                    System.out.println(_tempTech2.getName()+" vs. " + techName);
                   if (_tempTech2.getName().equals(techName))
                        _tempTech2.insertJob(job);
                        System.out.println("ADDED " + job.getJobName() +" TO " + techName);
                   else
                        System.out.println("TECH NAME: "+_tempTech2.getName()+" NOT FOUND :: COULD NOT INSERT JOB");
         private int findCharPosition(String _resolution2, char c) {
              // TODO Auto-generated method stub
              for (int i = 0; i < _resolution2.length(); i++)
                   if (_resolution2.charAt(i) == c)
                        return i;
              return 0;
         public void mouseReleased(MouseEvent arg0) {
              // TODO Auto-generated method stub
              System.out.println("Mouse clicked at coordinates: "+arg0.getX()+", "+arg0.getY()+"\nAttempting to intelligently find the job number");
               * Find the tech
              int techNum = arg0.getY()/(_yRes / (_techs+1));
              String techName= new String("");
              int counter = 0;
              Tech temp = _myTechList;
              boolean found = true;
              while(temp.hasNext() && found)
                   counter++;
                   if (counter == techNum)
                        techName = temp.getName();
                        found = false;
                   else
                        temp = temp.getNext();
              System.out.println("The "+techNum+"th tech was selected... which means you clicked "+techName);
               * Find the day
              int day = (arg0.getX()-60)/(0 + ((_xRes-60)/5));
              String days[] = {_monday, _tuesday, _wednesday, _thursday, _friday};
              System.out.println("The day you chose was "+days[day]);
               * Find the time
              int blocksIn = ((arg0.getX()-60)/(((_xRes-60)/5)/9))%9;
              System.out.println(blocksIn+" blocks inward!!!!");
               * Find the job
               *           - temp is already initialized to the current tech!!
              System.out.println(temp.getName()+" has "+temp.getNumberOfJobs()+" jobs");
              Job current = temp.getJobs();
              Queue jobQueue = new Queue();
              boolean first = true;
              while(current.hasNext() || first)
                   if(current.getDate().toString().equals(days[day]))
                        jobQueue.enqueue(current);
                        System.out.println("Queued the job on "+current.getDate().toString()+"::"+current.getJobNumber());
                        if (first)
                             first = false;
                             current = current.getNext();
                        else
                             current = current.getNext();
                   else
                        System.out.println("Did not queued the job on "+current.getDate().toString()+"::"+current.getJobNumber());
                        if (first)
                             first = false;
                             current = current.getNext();
                        else
                             current = current.getNext();
              if(current.getDate().toString().equals(days[day]))
                   jobQueue.enqueue(current);
                   System.out.println("Queued the job on "+current.getDate().toString()+"::"+current.getJobNumber());
              else
                   System.out.println("Did not queue the job on "+current.getDate().toString()+"::"+current.getJobNumber());
              blocksIn+=8;
              while(!jobQueue.isEmpty())
                   try {
                         * Get a job off the queue... now check the times
                        Job dqJob = (Job)jobQueue.dequeue();
                        System.out.println(dqJob.getStarTime()+"<="+blocksIn +" && "+(dqJob.getStarTime()+dqJob.getJobLength()-1)+">="+blocksIn+" :: "+dqJob.getJobName());
                        if (dqJob.getStarTime()<=blocksIn && dqJob.getStarTime()+dqJob.getJobLength()-1>=blocksIn)
                             System.out.println("MONEY!!!! Found job: "+dqJob.getJobName());
                             new JobDisplayer(dqJob, _xRes, _yRes);
                   } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
         public void mouseEntered(MouseEvent arg0) {
              // TODO Auto-generated method stub
         public void mouseExited(MouseEvent arg0) {
              // TODO Auto-generated method stub
         public void mousePressed(MouseEvent arg0) {
              // TODO Auto-generated method stub
         public void mouseClicked(MouseEvent arg0) {
              // TODO Auto-generated method stub
         public void nextDay() {
              // TODO Auto-generated method stub
              if (_dayOption.equals(new String("work_week")))
                   cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+7);
                   setDaysFiveStraight();
              this.repaint();
         public void prevDay() {
              // TODO Auto-generated method stub
              if (_dayOption.equals(new String("work_week")))
                   cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)-7);
                   setDaysFiveStraight();
                   this.repaint();
              this.repaint();
    }Sorry for the huge chunk of code.
    Thanks in advance,
    Jeff

    Sorry for the huge chunk of code.
    Mm, yes, I'm far too lazy to read all that.
    But you should be overriding paintComponent(), not paint().
    http://www.google.co.uk/search?hl=en&q=java+swing+painting&btnG=Google+Search&meta=
    I've not bothered to work out from that pile of magic numbers exactly what you're tring to draw but is it not something that JTable would happily do?

  • How to repaint a JPanel in bouncing balls game?

    I want to repaint the canvas panel in this bouncing balls game, but i do something wrong i don't know what, and the JPanel doesn't repaint?
    The first class defines a BALL as a THREAD
    If anyone knows how to correct the code please to write....
    package fuck;
    //THE FIRST CLASS
    class CollideBall extends Thread{
        int width, height;
        public static final int diameter=15;
        //coordinates and value of increment
        double x, y, xinc, yinc, coll_x, coll_y;
        boolean collide;
        Color color;
        Rectangle r;
        bold BouncingBalls balls; //A REFERENCE TO SECOND CLASS
        //the constructor
        public CollideBall(int w, int h, int x, int y, double xinc, double yinc, Color c, BouncingBalls balls) {
            width=w;
            height=h;
            this.x=x;
            this.y=y;
            this.xinc=xinc;
            this.yinc=yinc;
            this.balls=balls;
            color=c;
            r=new Rectangle(150,80,130,90);
        public double getCenterX() {return x+diameter/2;}
        public double getCenterY() {return y+diameter/2;}
        public void move() {
            if (collide) {
            x+=xinc;
            y+=yinc;
            //when the ball bumps against a boundary, it bounces off
            //bounce off the obstacle
        public void hit(CollideBall b) {
            if(!collide) {
                coll_x=b.getCenterX();
                coll_y=b.getCenterY();
                collide=true;
        public void paint(Graphics gr) {
            Graphics g = gr;
            g.setColor(color);
            //the coordinates in fillOval have to be int, so we cast
            //explicitly from double to int
            g.fillOval((int)x,(int)y,diameter,diameter);
            g.setColor(Color.white);
            g.drawArc((int)x,(int)y,diameter,diameter,45,180);
            g.setColor(Color.darkGray);
            g.drawArc((int)x,(int)y,diameter,diameter,225,180);
            g.dispose(); ////////
        ///// Here is the buggy code/////
        public void run() {
            while(true) {
                try {Thread.sleep(15);} catch (Exception e) { }
                synchronized(balls)
                    move();
                    balls.repairCollisions(this);
                paint(balls.gBuffer);
                balls.canvas.repaint();
    //THE SECOND CLASS
    public class BouncingBalls extends JFrame{
        public Graphics gBuffer;
        public BufferedImage buffer;
        private Obstacle o;
        private List<CollideBall> balls=new ArrayList();
        private static final int SPEED_MIN = 0;
        private static final int SPEED_MAX = 15;
        private static final int SPEED_INIT = 3;
        private static final int INIT_X = 30;
        private static final int INIT_Y = 30;
        private JSlider slider;
        private ChangeListener listener;
        private MouseListener mlistener;
        private int speedToSet = SPEED_INIT;
        public JPanel canvas;
        private JPanel p;
        public BouncingBalls() {
            super("fuck");
            setSize(800, 600);
            p = new JPanel();
            Container contentPane = getContentPane();
            final BouncingBalls xxxx=this;
            o=new Obstacle(150,80,130,90);
            buffer=new BufferedImage(getSize().width, getSize().height, BufferedImage.TYPE_INT_RGB);
            gBuffer=buffer.getGraphics();
            //JPanel canvas start
            final JPanel canvas = new JPanel() {
                final int w=getSize().width-5;
                final int h=getSize().height-5;
                @Override
                public void update(Graphics g)
                   paintComponent(g);
                @Override
                public void paintComponent(Graphics g) {
                    super.paintComponent(g);
                    gBuffer.setColor(Color.ORANGE);
                    gBuffer.fillRect(0,0,getSize().width,getSize().height);
                    gBuffer.draw3DRect(5,5,getSize().width-10,getSize().height-10,false);
                    //paint the obstacle rectangle
                    o.paint(gBuffer);
                    g.drawImage(buffer,0,0, null);
                    //gBuffer.dispose();
            };//JPanel canvas end
            addWindowListener(new WindowAdapter() {
                @Override
                public void windowClosing(WindowEvent e) {
                    System.exit(0);
            addButton(p, "Start", new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    CollideBall b = new CollideBall(canvas.getSize().width,canvas.getSize().height
                            ,INIT_X,INIT_Y,speedToSet,speedToSet,Color.BLUE,xxxx);
                    balls.add(b);
                    b.start();
            contentPane.add(canvas, "Center");
            contentPane.add(p, "South");
        public void addButton(Container c, String title, ActionListener a) {
            JButton b = new JButton(title);
            c.add(b);
            b.addActionListener(a);
        public boolean collide(CollideBall b1, CollideBall b2) {
            double wx=b1.getCenterX()-b2.getCenterX();
            double wy=b1.getCenterY()-b2.getCenterY();
            //we calculate the distance between the centers two
            //colliding balls (theorem of Pythagoras)
            double distance=Math.sqrt(wx*wx+wy*wy);
            if(distance<b1.diameter)
                return true;
            return false;
        synchronized void repairCollisions(CollideBall a) {
            for (CollideBall x:balls) if (x!=a && collide(x,a)) {
                x.hit(a);
                a.hit(x);
        public static void main(String[] args) {
            JFrame frame = new BouncingBalls();
            frame.setVisible(true);
    }  And when i press start button:
    Exception in thread "Thread-2" java.lang.NullPointerException
    at fuck.CollideBall.run(CollideBall.java:153)
    Exception in thread "Thread-3" java.lang.NullPointerException
    at fuck.CollideBall.run(CollideBall.java:153)
    Exception in thread "Thread-4" java.lang.NullPointerException
    at fuck.CollideBall.run(CollideBall.java:153)
    and line 153 is: balls.canvas.repaint(); in Method run() in First class.
    Please help.

    public RepaintManager manager;
    public BouncingBalls() {
            manager = new RepaintManager();
            manager.addDirtyRegion(canvas, 0, 0,canvas.getSize().width, canvas.getSize().height);
        public void run() {
            while(true) {
                try {Thread.sleep(15);} catch (Exception e) { }
                synchronized(balls)
                    move();
                    balls.repairCollisions(this);
                paint(balls.gBuffer);
                balls.manager.paintDirtyRegions(); //////// line 153
       but when push start:
    Exception in thread "Thread-2" java.lang.IllegalMonitorStateException
    at java.lang.Object.notifyAll(Native Method)
    at fuck.CollideBall.run(CollideBall.java:153)
    Exception in thread "Thread-3" java.lang.IllegalMonitorStateException
    at java.lang.Object.notifyAll(Native Method)
    at fuck.CollideBall.run(CollideBall.java:153)
    i'm newbie with Concurrency and i cant handle this exceptons.
    Is this the right way to do repaint?

  • Problem with repaint() in JPanel

    Hi,
    This is the problem: I cyclically call the repaint()-method but there is no effect of it.
    When does it appear: The problem occurs by calling the repaint()-method of a JPanel -class.
    This is what i am doing: The repaint() is called from a different class which is my GUI. I do this call in an endless loop which is done within a Thread.
    I tried to add a KeyListener to the JPanel-class and there I called the repaint()-method when i press a Key. Then the Panel is repainted.
    so I implemented a "callRepaint"-method in the JPanel-class that does nothing else than call repaint() (just like the keyPressed()-method does). But when i cyclically call this "callRepaint"-method from my GUI nothing happens.
    Now a few codedetails:
    // JPanel-class contains:
    int i = 0;
    public void callRepaint(){
                    repaint();
    public void paintComponent(Graphics g){
            super.paintComponent(g);
            g.drawLine(i++,0,200,200);
    public void keyPressed(KeyEvent e) {
            repaint();                       // This is working
    //GUI-class contains:
    // This method is called cyclically
    public void draw() {
                  lnkJPanelclass.repaint();             // This calling didn't work
                  // lnkJPanelclass.callRepaint();  // This calling didn't work     
    Thanks for your advices in advance!
    Cheers spike

    @ARafique:
    This works fine:
    import java.awt.*;
    import java.awt.event.*;
    import java.util.Date;
    import javax.swing.*;
    public class Test extends JFrame implements ActionListener{
        private JTextField label;
        private Timer timer;
        private Container cont;
        public Test() {
            label = new JTextField("",0);
            timer = new Timer(1000,this);
            cont = getContentPane();
            cont.add(label);
            setSize(250,70);
            setDefaultCloseOperation(3);
            setVisible(true);
            timer.start();
        public void actionPerformed(ActionEvent e){
            label.setText(new Date(System.currentTimeMillis()).toString());
        public static void main(String[] args){
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    new Test();
    }no repaint()/revalidate() needed

  • Repaint() for JPanels

    HI ALL,
    I am doing a line plot of image data, and displaying it on a JPanel.
    In my App, I added some buttons for I can transition between the plots.
    I can grab all the data at once and display all in separate tabs, but
    when I changed it to this buttons format, the plot never updates.
    Here is my button function to update the panel.
         myPrevButton.addActionListener(new ActionListener() {
              public void actionPerformed(ActionEvent ae) {
                        try{
                             p = (Plotable)myPlotables.elementAt(currentPlot-2);
                        myMeanPlotPanel = new XYPlotJPanel(p);
                   p = (Plotable)list.nextElement();
                             currentPlot = myPlotables.indexOf(p);
              mySDPlotPanel = new XYPlotJPanel(p);
                             myMainPanel.repaint();
              } catch (NotEnoughDataException nede){
                   MsgPopup msg = new MsgPopup(LocalizedError.constructFormattedErrorString(nede));
                   msg.show();
    When I read the images, I use a vector to order the images, and "list" is an enumertion variable in this function.
    The mainPanel holds both subpanels. Now the app will show only the first plot, but will not update any other plots. I have tried repaint() all panels before, it did not work.
    Does anyone know how to get this to update or replot,refresh, ...or etc....?
    I have not ideas now.
    Thanks!

    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.util.*;
    import java.util.List;
    import javax.swing.*;
    public class SelectingGraphs {
      static int plotIndex = 0;
      public static void main(String[] args) {
        float[] data1 = {
          1.2f, 2.0f, 3.7f, 4f, 2.9f, 4.9f, 3.1f, 4.02f
        float[] data2 = {
          29f, 18.2f, 75f, 34f, 92f, 15f, 50.9f, 42.3f
        float[] data3 = {
          90f, 44f, 53.7f, 67.2f, 49.2f, 79f, 80.3f, 55.2f
        final float[][] allData = {
          data1, data2, data3
        Plot
          plot1 = new Plot(),
          plot2 = new Plot(),
          plot3 = new Plot();
        final Plot[] plots = {
          plot1, plot2, plot3
        for(int i = 0; i < plots.length; i++)
          for(int j = 0; j < allData.length; j++)
    plots[i].plot(allData[i][j]);
    final JPanel panel = new JPanel();
    panel.add(plot1);
    // south panel
    final JButton
    lastButton = new JButton("last"),
    nextButton = new JButton("next");
    ActionListener l = new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    JButton button = (JButton)e.getSource();
    panel.remove(plots[plotIndex % 3]);
    if(button == lastButton) {
    --plotIndex;
    if(plotIndex < 0)
    plotIndex = 2;
    if(button == nextButton)
    ++plotIndex;
    panel.add(plots[plotIndex % 3]);
    panel.revalidate();
    panel.repaint();
    lastButton.addActionListener(l);
    nextButton.addActionListener(l);
    JPanel southPanel = new JPanel();
    southPanel.add(lastButton);
    southPanel.add(nextButton);
    JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.getContentPane().add(panel);
    f.getContentPane().add(southPanel, "South");
    f.setSize(400,300);
    f.setLocation(400,300);
    f.setVisible(true);
    class Plot extends JPanel {
    float PAD = 25;
    List dataList;
    public Plot() {
    dataList = new ArrayList();
    setBackground(Color.white);
    setPreferredSize(new Dimension(200,200));
    public void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D)g;
    float width = getWidth();
    float height = getHeight();
    float xStep = (width - 2*PAD)/(dataList.size() - 1);
    float x = PAD;
    float y;
    // scale data
    float max = ((Float)Collections.max(dataList)).floatValue();
    float min = ((Float)Collections.min(dataList)).floatValue();
    float vertSpace = height - 2*PAD;
    float yOffset = height - PAD;
    float yDataOffset = (min >= 0 ? min : max > 0 ? 0 : max);
    float scale = vertSpace/(max - min);
    float yOrigin = yOffset + (min > 0 ? 0 : max > 0 ? scale*min : - vertSpace);
    // draw ordinate
    g2.draw(new Line2D.Float(PAD, PAD, PAD, yOffset));
    // draw abcissa
    g2.draw(new Line2D.Float(PAD, yOrigin, width - PAD, yOrigin));
    // label ordinate limits
    g2.drawString(String.valueOf(max), 10, PAD - 10);
    g2.drawString(String.valueOf(min), 10, yOffset + PAD/2);
    g2.setStroke(new BasicStroke(4f));
    g2.setPaint(Color.red);
    for(int j = 0; j < dataList.size(); j++) {
    y = yOrigin - scale * (((Float)dataList.get(j)).floatValue() - yDataOffset);
    g2.draw(new Line2D.Float(x, y, x, y));
    x += xStep;
    protected void plot(float input) {
    dataList.add(new Float(input));
    repaint();

  • Repaint clears JPanel

    I have created a subclass a JPanel that has a drawing in its graphics. I have overriden the paintComponent method and updates the graphics using repaint() whenever the underlying data model is modified. But the repaint() method clears the JPanel, what can I do?

    Am using a grid layout package i built. When the application loads at first all the componets are in the right order. But a button with an event triggers the removeAll() and then repaint then a method that defines the components and there layout then revalidate().
    It actually draws all the components but they are not using the layout that i specified in the method that was called before revalidate(). And its the same method that i call when the application loads at first and all components are draw accuratly.
    I have a mainPanel that holds other panels. So when i removeAll components i want to add other panels to it. Then later want to be able to return those same components i removed later. i can achive this using CardLayout but i dont want to because that makes the coding long.
    What i am trying to achive is that i want to removeAll components and then add new components to the same mainPanel. and later want to be able to return those components removed .

  • How to repaint a JPanel.

    Hi
    I am building a GUI in which i have a fixed panel.........in this panel there is a jpanel....i want to change its contents at run time............like at first there are buttons when someone presses these buttons.....the panel changes to a textbox for instance...........any ideas

    Maybe CardLayout and public void remove(Component comp) will help ...

  • Urgent Regarding Jtable TAB and Arrow keys

    Hi guys and gals,
    In my project i need urgnet help regarding Jtable.I want to use DOWN ARROW key same as TAB function.When i reach the first row last editing coulmn by using arrow key,then i habe to creating a new row with default values.And if press UP key if that row contains no values i have to delete.Plz help me in this regard.
    sreeni

    I meant that the laptop freezes in gdm and in console (tty1). In gdm i can't even type any character. And in console i can login but when i press the tab key (autocompletation) it stops. The only thing i can do is press the power button.
    Actually my keymap is es_ES. And i think that it's working fine because the n tilde and pipes work fine.

  • Hmm..repaint, refresh jpanel?

    Hi,
    I had a problem and i dun have codes to show. All I can say are just descriptions.
    Well, here it goes. I had use jPanel to display Unicode characters. It is able to display but when another frame, say msn, overlaps the jPanel, partial of the character drawn on it will disappear.
    This is dependent on the amount of overlapping of that particular frame. If the whole jpanel is covered, then the whole character would be gone when the overlapping is removed.
    What can I do to enable the character to be displayed even when i remove the overlapping?
    Hope my descriptions are vivid to you all.
    Shoker

    Hi,
    Thanks for your replies!
    Well after searching through the forum, I realised that my problem lies with 'getGraphics()'. This function only stores the data temporary. Therefore, when a frame overlaps it, the that overlapped portion is erased. Shown below are my codes:
    Graphics g2 = null;
    g2 = jPanel8.getGraphics(); //problem
    jPanel8.paint(g2);
    g2.setFont(new Font("Arial",Font.PLAIN,12));
    g2.drawString(rClassify[count_rClass],10,10);
    g2.dispose();
    I tried using 'super.paintComponents(g2)' but during runtime, there is an error regarding some null pointers. Hence, the problem still exist.
    Would appreciate greatly if you guys can enlighten me!
    Thanks.
    Shoker

  • JPanel.repaint() or JPanel.repaint(args)

    Hi,
    Im wondering which one is the most efficent way to update the panel.
    Ive read [suns tutorial about painting|http://java.sun.com/docs/books/tutorial/uiswing/painting] and it says that its more efficent to use the multiargument repaint method.
    But im wondering if it really is more effeicent, if you have over 200 objects to repaint, or more?
    It feels like when you have over 200 objects, that it justifies repainting the whole panel instead.

    Hmm, I just remember that google exists. But to late now.

  • Urgent: Making JTable detect a JButton event

    The GUI I'm working on displays a JTable along with an "Add" JButton. Upon launching the program there is already a list of things in the table. When "Add" is pressed a dialog box comes up. This dialog box has a JTextField, and the user enters the name of the new item s/he wishes to add. How can I "refresh" the table to add one more row, with the item added, when the "Confirm" button is pressed? The examples in the JTable tutorial seem to deal only with direct editing of cells. But this is sort of an indirect way of adding data...please help!
    James

    Work with the table's model (myTable.getModel()). In the default case, your working with an instance of DefaultTableModel. That class has all the modification methods you will need. Any changes to the model will cause the appropriate event to be thrown up to the table to cause it to change.

  • JPanel repaint in an ActionListener and Frame title change

    I have been trying to repaint a JPanel from a method in a nested class. The JOption pane works that retrieves the string for the color and I believe the string is being converted to a color properly, however when the repaint takes place nothing happens. The JPanel sits in a Frame.
    My other issue is that I am supposed to in this assignment change the title text of the Frame after it has been instantiated? and I read somewhere else on the forum that the only time this can be done is when the frame is being initialized.
    Any thoughts? Mind you this is the third real program I have ever tried and most of it was already written and in a book, we are just supposed to cahnge a few things.
    private class SetBackground implements ActionListener
    private String whatColor;
    public void actionPerformed (ActionEvent event)
    whatColor = new String();
    whatColor = JOptionPane.showInputDialog("Type red, blue, yellow, or green to change the color.");
    whatColor = whatColor.toLowerCase();
    panColor = Color.getColor(whatColor);
    panel.setBackground(panColor);
    panel.repaint();
    Is it because the ActionEvent is 'void', should I pass the panColor back up to main class as a variable for the color?

    nope, if i set the color initially the panel just goes back to the default color
    this tells me that my code is not being understood, like java is expecting some other value, i looked in some references and found that the 'Color' is a class and likes three values for the r,g,b in either floats or ints should i try passing these three values back or try it right here in the method?
    any suggestions?

  • JPanel repainting

    I overwrite JPanel's paintComponent to draw a picture.
    When the user selects a picture from JDialog, i need to repaint the
    JPanel:
    Which function of JPanel to call to repaint the JPanel correctly?

    Normally you should have a panel that looks like this :
    import java.awt.*;
    import javax.swing.*;
    public class MyPanel extends JPanel {
         public BufferedImage image;
         public MyPanel() {
              image = null;
         public void paintComponent(Graphics g) {
              super.paintComponent(g);
              if (image != null) {
                   g.drawImage(image, 0,0,this);
         public void setImage(BufferedImage im) {
              if (im!= null) {
                   image = im;
                   repaint();
    }Denis

  • Urgent!!!! problems with Toolbar

    Hi ,
    I have Toolbar with buttons on it. I also have 3 tables
    and i'm trying to display them in a panel depending upon the button that is being clicked by the user.For this i have written action listeners which are not working properly. Following is the code and i'll be greatful if u can advise me in this regard. Any kind of suggestion or direction to helpful links is appreciated.....Treat this as
    very urgent......
    import javax.swing.JToolBar;
    import javax.swing.JButton;
    import javax.swing.ImageIcon;
    import javax.swing.AbstractButton;
    import javax.swing.JFrame;
    import javax.swing.JTextArea;
    import javax.swing.JScrollPane;
    import javax.swing.JPanel;
    import javax.swing.JTable;
    import java.awt.*;
    import java.awt.event.*;
    public class ToolBarTest extends JFrame {
        protected JTextArea textArea;
        protected String newline = "\n";
        JPanel contentPane = new JPanel();
        public ToolBarTest() {
            //Do frame stuff.
            super("ToolBarDemo");
            addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                    System.exit(0);
            //Create the toolbar.
            JToolBar toolBar = new JToolBar();
            addButtons(toolBar);
            //Create the text area used for output.
    //        textArea = new JTextArea(5, 30);
             TableDemo1 generaltable=new TableDemo1();
              JTable table=new JTable();
              table.setModel(generaltable);
               JScrollPane scrollPane = new JScrollPane(table);
               scrollPane.setViewportView(table);
            //Lay out the content pane.
    //        JPanel contentPane = new JPanel();
            contentPane.setLayout(new BorderLayout());
            contentPane.setPreferredSize(new Dimension(400, 100));
            contentPane.add(toolBar, BorderLayout.NORTH);
            contentPane.add(scrollPane, BorderLayout.CENTER);
            setContentPane(contentPane);
        protected void addButtons(JToolBar toolBar) {
            JButton button = null;
            ImageIcon general=new ImageIcon("ql3nava.gif");
            //first button
            button = new JButton("General",general);
            button.setToolTipText("General");
            button.setVerticalTextPosition(AbstractButton.BOTTOM);
            button.setHorizontalTextPosition(AbstractButton.CENTER);
            button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
            repaint();
                    JTable  table1=new JTable();
                    TableDemo1 test1=new TableDemo1();
                    table1.setModel(test1);
               JScrollPane scrollPane1 = new JScrollPane(table1);
               scrollPane1.setViewportView(table1);
               JPanel panel1=new JPanel();
               panel1.add(scrollPane1);
            toolBar.add(button);
            ImageIcon chart=new ImageIcon("ql3nava.gif ");
            //second button
            button = new JButton("BarGraph",chart);
            //new ImageIcon("Chart.bmp"));
            button.setToolTipText("Bar Graph");
            button.setVerticalTextPosition(AbstractButton.BOTTOM);
            button.setHorizontalTextPosition(AbstractButton.CENTER);
            button.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    JTable  table2=new JTable();
                    TableDemo2 test2=new TableDemo2();
                    table2.setModel(test2);
               JScrollPane scrollPane2 = new JScrollPane(table2);
               scrollPane2.setViewportView(table2);
               JPanel panel2=new JPanel();
               panel2.add(scrollPane2);
            toolBar.add(button);
            ImageIcon pie=new ImageIcon("ql3nava.gif");
            //third button
            button = new JButton("PieGraph",pie);
            //new ImageIcon("pie.bmp"));
            button.setToolTipText("Pie Graph");
            button.setVerticalTextPosition(AbstractButton.BOTTOM);
            button.setHorizontalTextPosition(AbstractButton.CENTER);
            button.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    JTable  table3=new JTable();
                    TableDemo3 test3=new TableDemo3();
                    table3.setModel(test3);
               JScrollPane scrollPane3 = new JScrollPane(table3);
               scrollPane3.setViewportView(table3);
               JPanel panel3=new JPanel();
               panel3.add(scrollPane3);
            toolBar.add(button);
        //Fourth Button
            ImageIcon refresh=new ImageIcon("ql3nava.gif");
            button = new JButton("Refresh",refresh);
            //new ImageIcon("Refresh.bmp"));
            button.setToolTipText("Refresh");
            button.setVerticalTextPosition(AbstractButton.BOTTOM);
            button.setHorizontalTextPosition(AbstractButton.CENTER);
            button.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
      //  protected void displayResult(Component comp) {
           // JPanel.add(Component comp);
    //        System.out.println(comp);
        public static void main(String[] args) {
            ToolBarTest frame = new ToolBarTest();
            frame.pack();
            frame.setVisible(true);
    }Thanks,
    Anita

    Anita,
    Your program misses one line in all ActionListeners
    add this line after
    <pre>
    panel2.add(scrollPane2);
    //add this
    getContentPane().add(panel2);
    </pre>
    let me know if it helps.,
    vinod

  • Refreshing Jtable data

    Hi:
    I am also working on a Application where I hav eto update my data (i.e. vector<vector>) for rows.
    Help is urgent.Since the data updated is overlapping.
    I have added my Jtable toa panel.
    and i put>>
    jtable.refresh();
    This idoesn't work.
    Thanking yu.
    Regards
    Ritesh

    Hi keene:
    I am attaching my source code.Please tell me where am I going wrong.
    Send me the modified code.
    to this email id:[email protected]
    Regards
    Ritesh
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    //Declare the Packages going to be imported here below
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.table.*;
    import java.util.*;
    import java.sql.*;
    //<Applet code="JApplicationSql.class" width=500 height=500></Applet>
    public class JApplicationSql extends JFrame implements ItemListener
         //Initialize the Components
         DefaultTableModel     defaulttablemodel;//     =     new DefaultTableModel();
         JTable          jtable     ;//=     new     JTable(defaulttablemodel);//A Dynamic Modifiable JTable
         Vector          row,column,row_1,column_1;//No. of rows and columns in a JTable
         JLabel label_combo=new JLabel();
         JComboBox comboBox =new JComboBox();
         JPanel jpanel;
         //comboBox.setEditable(true);
         //Declare the Container1
         Container contentPane;
         //Database Declarations
         //Connection connection;
         //String dbUrl = "jdbc:odbc:mydsn";
         //String user = "sa";
         //String password = "";
         private Statement stmt;
         private ResultSet rs;
         private ResultSetMetaData rmeta;
         String combo_value="";
         //String row_value="";
         //Initialization of Constructor
         public JApplicationSql()
              jpanel     =     new JPanel();
              label_combo.setText("Select the Department");
              label_combo.setFont(new Font("Verdana",1,17));
              comboBox.addItem(" 10 ");
              comboBox.addItem(" 20 ");
              comboBox.addItem(" 30 ");
              comboBox.addItem(" 40 ");          
              comboBox.addItem(" 50 ");
              //contentPane.setLayout(new FlowLayout());
              jpanel.add(label_combo);
              jpanel.add(comboBox);
              //Add the Listeners
              comboBox.addItemListener(this);
              contentPane     =     getContentPane();
              contentPane.add(jpanel,BorderLayout.NORTH);                    
              //Load the Drivers and Connection Objects and Establish the connection
              try
                   System.out.println("Locating Drivers");
                   Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                   System.out.println("Connecting to Database");
                   //connection = DriverManager.getConnection(dbUrl,user,password);
                   Connection connection = DriverManager.getConnection("jdbc:odbc:mydsn;UID=sa;PWD=");
                   System.out.println("Got Connection");
                   stmt = connection.createStatement();
              catch (Exception sqlex)
                   System.out.println("Unable to Connect!!");
                   sqlex.printStackTrace();
         public static void main(String args[])
              try
                   JApplicationSql app=new JApplicationSql();
                   app.setSize(500,350);
                   app.setVisible(true);
              }catch(Exception e)
         public void itemStateChanged(ItemEvent ite)     
              try
                   if (ite.getStateChange()==ItemEvent.SELECTED)
                        combo_value=(String)comboBox.getSelectedItem();
                        populate(combo_value);
                        jtable.repaint();
              catch(Exception SqlE)
                        System.out.println("Error in retrieving");
         //The Column Data
         public Vector retrieveColumns()
              column=new Vector();
              try
                   for(int i=1;i<=rmeta.getColumnCount();i++)
                             column.addElement(rmeta.getColumnName(i));
                   //System.out.println(column.size());
              catch(Exception e)
                   System.out.println("The column Exception is :"+e);
              return column;          
         //The Row Data
         public Vector retrieveRows()
              row=new Vector();
              try
                   while(rs.next())
                        Vector currow=new Vector();//Current Row     
                        for(int i=1;i<=rmeta.getColumnCount();i++)
                   currow.addElement(rs.getString(i));
                        System.out.println(currow.size());
                        row.addElement(currow);
         catch(SQLException se)
                   System.out.println("The Exception is :"+se);
              return row;          
         public void populate(String val)
              try
                   System.out.println("Value of the combo is "+val);
                   String sql_query="SELECT A.DeptId,A.EmpId,A.Name,A.Designation, B.DeptName FROM EmployeeDetails A,Master_Department B where A.DeptId = B.DeptId and A.DeptId ="+val;
                   //The Resultset Based Sql Query
                   //rs = stmt.executeQuery("SELECT EmployeeDetails.EmpId,EmployeeDetails.Name,EmployeeDetails.Designation, EmployeeDetails.DeptId,Master_Department.DeptName FROM EmployeeDetails INNER JOIN Master_Department ON EmployeeDetails.DeptId = 'index'");
                   rs=stmt.executeQuery(sql_query);
                   rmeta=rs.getMetaData();                                   
                   //Retrieve the number of columns and rows and add the number to Vectors
                   column_1= retrieveColumns();
                   //Row Data from the Vector Object
                   row_1=retrieveRows();
                   //Display the ResultSet data in a JTable
                   defaulttablemodel =new DefaultTableModel(row_1,column_1);
                   jtable =new JTable(defaulttablemodel);
                   defaulttablemodel.addTableModelListener(jtable);               
                   JScrollPane scrolltab=new JScrollPane(jtable);
                   jtable.setPreferredScrollableViewportSize(new Dimension(500, 70));
                   jpanel.add(scrolltab);
                   contentPane.add(scrolltab,BorderLayout.CENTER);
                   //jpanel.repaint();
                   //jtable.repaint();
                   //contentPane.add(jpanel,BorderLayout.CENTER);
                   //contentPane.validate(true);
              catch(Exception eop){System.out.println(eop);}

Maybe you are looking for

  • Error Publishing Policy

    Hi, I encountered an error when publishing a policy to the clients. The error message is displayed in a dialog box after clicking on "Publish". "The Management Console was unable to complete the policy assignment. The requested policy assignment has

  • Calendar trouble

    hi there, I have an irritating problem with the Calendar class : Since I work on a french calendar (first day of week is monday and first week of year is the first full week within that year), i wrote : Calendar c = Calendar.getInstance(); c.setFirst

  • Slow query results for simple select statement on Exadata

    I have a table with 30+ million rows in it which I'm trying to develop a cube around. When the cube processes (sql analysis), it queries back 10k rows every 6 seconds or so. I ran the same query SQL Analysis runs to grab the data in toad and exported

  • Deploying small JSF app to OC4J 10.13.10

    Hi all, I'm having a small problem deploying my JSF application on oas 10.13.10. Deploying actually works fine but when I try to surf to my app it gives me a HTTP 500 - Internal server error. When I check the logs in the entreprise manager I see the

  • .Mac web galleries

    Anyone figure out what ATV 2 wants when it asks for info regarding .Mac web gallery? the URL? the name of the gallery? my .mac user name? not frustrated, just excited!