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

Similar Messages

  • Best way to repaint/refresh JFrame classes.

    Hello everyone,
    I am developing a small application for my studies. I have several classes many representing a user form allowing interaction with my system.
    One of my first class instances is a Menu Screen from which the user can for example update their details. When the Update Details frame is closed by the user I invoke
    frameName.setVisible(false);
    frameName.dispose();This removes the Update Details frame and the Menu Screen is now fully visible.
    However this screen does not get refreshed and remains partially obscured by the background color of the JFrame, even if I bring say a browser to the foreground and then click the original Menu Screen to the foreground it does not refresh the Menu Screen and remains half painted.
    I was wondering about a few things.
    1. Is there a way of detecting when the current JFrame has just received the focus, at which point I could repaint the screen.
    2. Is there a way of Menu Screen discussed above being able to detect the closure of the Update Details JFrame (a separate class) and then take appropriate steps to repaint/refresh itself.
    3. Ideally what I would like to do is Hide the Menu Screen then allow the user to interact with their menu selection and then Un-hide the Meun Screen when the user is done interacting with their menu selection.
    4. Are there any tutorials on this type of thing, that anynone could direct me to.
    Thank you for your consideration.
    Cheers
    Mark

    Hello everyone,
    I am developing a small application for my studies. I
    have several classes many representing a user form
    allowing interaction with my system.
    One of my first class instances is a Menu Screen from
    which the user can for example update their details.
    When the Update Details frame is closed by the user I
    invoke
    frameName.setVisible(false);
    frameName.dispose();This removes the Update Details frame and the Menu
    Screen is now fully visible.
    However this screen does not get refreshed and remains
    partially obscured by the background color of the
    JFrame, even if I bring say a browser to the
    foreground and then click the original Menu Screen to
    the foreground it does not refresh the Menu Screen and
    remains half painted.
    I was wondering about a few things.
    1. Is there a way of detecting when the current JFrame
    has just received the focus, at which point I could
    repaint the screen.
    2. Is there a way of Menu Screen discussed above being
    able to detect the closure of the Update Details
    JFrame (a separate class) and then take appropriate
    steps to repaint/refresh itself.
    3. Ideally what I would like to do is Hide the Menu
    Screen then allow the user to interact with their menu
    selection and then Un-hide the Meun Screen when the
    user is done interacting with their menu selection.
    4. Are there any tutorials on this type of thing, that
    anynone could direct me to.
    Thank you for your consideration.
    Cheers
    Mark

  • Repainting/Refreshing a JPanel

    Hi all. I have a JPanel that I'm loading buffered images into. I can change the image in the panel by selecting a new image from a JComboBox. However, the panel just goes blank, even though the images has been loaded. It only pops up if I move the frame. What am I doing wrong? E-mail [email protected]

    Hi
    I'm doing something similar and here's what i got (just part of it):
    public class JImagePanel extends JPanel {
        BufferedImage imgSrc;
        public void setImage(BufferedImage img)
            imgSrc = img;
        public void paintComponent(Graphics g)
            // Paint background
            super.paintComponent(g);
            // Draw image
            Graphics2D g2 = (Graphics2D)g;
            if(imgSrc != null)
                g2.drawImage(imgSrc, null, 0, 0);
        } then in main frame i call:
    panel.setImage(image);
    // set size, get image info etc
    panel.update(panel.getGraphics()); // repaints the imageThat's all. But i'm really a newbie so maybe there's a simpler/better way.

  • 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?

  • 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();

  • 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

  • Problem repaint ( Refresh ) window

    Hi Friends,
    I have GUI JFrame window , in which i have added
    combo box and add button when i click add one new JFrame window
    opens and ask for name and when click OK, that is added to database.
    1) Main Window in which add button is there
    2) Secondary JFrame inputs the Username
    Now i want to show name should be added in Main Window's combo
    while clicking the Secondary windows OK button.
    How can I repaint thing ??
    I tried
    panel.updateUI( )but still it not showing me new added name.
    When i close application and restart it , it will showing me last added name , but it should not be the solution.
    HELP.

    MyExpenseTracker.java
    (Main Class)
    * MyExpenseTracker.java
    * Created on October 11, 2007, 6:10 PM
    * To change this template, choose Tools | Template Manager
    * and open the template in the editor.
    package app;
    import app.AddNewItem;
    import java.util.*;
    * @author Administrator
    public class MyExpenseTracker
        /** Creates a new instance of MyExpenseTracker */
        public MyExpenseTracker()
        public static void main(String args[])   
                ExpTracker t = new ExpTracker();
                MyExpenseTracker mymain = new MyExpenseTracker();
                //LoginForm loginf = new LoginForm();
                t.setVisible(true);
    }ExpTracker.java ( Main Window for project - no main method )
    * ExpTracker.java
    * Created on October 11, 2007, 1:39 PM
    package app;
    import app.AddNewItem;
    import app.AddNewName;
    import java.sql.*;
    import java.text.*;
    import java.util.*;
    * @author  Administrator
    public class ExpTracker extends javax.swing.JFrame
        /** Creates new form ExpTracker */
        Connection con = null;
        Statement stmt = null;
        ResultSet rs = null;
        String query;
        int status =0;
        String URL="jdbc:mysql://localhost:3306/exptracker";
        String DRIVER ="com.mysql.jdbc.Driver";
        //String user =loginf.getAuthenticatedUser();
        Calendar cal = Calendar.getInstance();
        int day = cal.get(Calendar.DATE);
        int month = cal.get(Calendar.MONTH)+1;
        int year = cal.get(Calendar.YEAR);
        public ExpTracker()
            super("Expense Tracker v1.0");
            initComponents();
            //System.out.println("User name got :"+user);
            //javax.swing.JOptionPane.showMessageDialog(this,"Username:"+ user);
            //System.out.println("user :"+user);
            loadNameCombo();
            cmbdate.setSelectedItem(day);
            cmbmonth.setSelectedIndex(month-1);
            cmbyear.setSelectedItem(year);
        public void doConnection()
            //make connection
            try
                Class.forName(DRIVER).newInstance();
            catch(Exception e)
            { System.out.println("driver not found"+e.getMessage());     }
            //making query
            try
                con = DriverManager.getConnection(URL, "root", "");
                stmt = con.createStatement();
            catch(Exception e)
            { System.out.println("Connection Failure !"+ e.getMessage());  }
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        // <editor-fold defaultstate="collapsed" desc=" Generated Code ">                         
        private void initComponents()
            jp1 = new javax.swing.JPanel();
            lbldate = new javax.swing.JLabel();
            cmbdate = new javax.swing.JComboBox();
            cmbmonth = new javax.swing.JComboBox();
            cmbyear = new javax.swing.JComboBox();
            lblfixdate = new javax.swing.JLabel();
            lblitem = new javax.swing.JLabel();
            cmbitem = new javax.swing.JComboBox();
            lblqty = new javax.swing.JLabel();
            tfqty = new javax.swing.JTextField();
            lblprice = new javax.swing.JLabel();
            tfprice = new javax.swing.JTextField();
            lblqtyfix = new javax.swing.JLabel();
            lblpricefix = new javax.swing.JLabel();
            btnAdd = new javax.swing.JButton();
            jLabel1 = new javax.swing.JLabel();
            lblname = new javax.swing.JLabel();
            jScrollPane1 = new javax.swing.JScrollPane();
            ta = new javax.swing.JTextArea();
            btnReport = new javax.swing.JButton();
            btnAddRecord = new javax.swing.JButton();
            jLabel2 = new javax.swing.JLabel();
            cmbname = new javax.swing.JComboBox();
            btnAddname = new javax.swing.JButton();
            jMenuBar1 = new javax.swing.JMenuBar();
            menu = new javax.swing.JMenu();
            menu1exit = new javax.swing.JMenuItem();
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            jp1.setBorder(javax.swing.BorderFactory.createTitledBorder("Expense Detail"));
            lbldate.setFont(new java.awt.Font("Tahoma", 0, 10));
            lbldate.setText("Date :");
            cmbdate.setFont(new java.awt.Font("Tahoma", 0, 10));
            for(int i=1; i<=31; i++)
                cmbdate.addItem(i);
            cmbmonth.setFont(new java.awt.Font("Tahoma", 0, 10));
            cmbmonth.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }));
            cmbyear.setFont(new java.awt.Font("Tahoma", 0, 10));
            for(int i=2006; i<=2050; i++)
                cmbyear.addItem(i);
            lblfixdate.setFont(new java.awt.Font("Tahoma", 0, 10));
            lblfixdate.setText("*Format is dd-MM-yyyy");
            lblitem.setFont(new java.awt.Font("Tahoma", 0, 10));
            lblitem.setText("Item :");
            cmbitem.setFont(new java.awt.Font("Tahoma", 0, 10));
            lblqty.setFont(new java.awt.Font("Tahoma", 0, 10));
            lblqty.setText("Quantity :");
            tfqty.setFont(new java.awt.Font("Tahoma", 0, 10));
            lblprice.setFont(new java.awt.Font("Tahoma", 0, 10));
            lblprice.setText("Price :");
            tfprice.setFont(new java.awt.Font("Tahoma", 0, 10));
            lblqtyfix.setFont(new java.awt.Font("Tahoma", 0, 10));
            lblqtyfix.setText("*you can write like 2 ,3 or 300gm");
            lblpricefix.setFont(new java.awt.Font("Tahoma", 0, 10));
            lblpricefix.setText("*ex. 300, 13.50 etc. no characters");
            btnAdd.setFont(new java.awt.Font("Tahoma", 0, 10));
            btnAdd.setText("Add");
            btnAdd.addActionListener(new java.awt.event.ActionListener()
                public void actionPerformed(java.awt.event.ActionEvent evt)
                    btnAddActionPerformed(evt);
            jLabel1.setFont(new java.awt.Font("Tahoma", 0, 10));
            jLabel1.setText("*if item is not in list, click Add button");
            org.jdesktop.layout.GroupLayout jp1Layout = new org.jdesktop.layout.GroupLayout(jp1);
            jp1.setLayout(jp1Layout);
            jp1Layout.setHorizontalGroup(
                jp1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(jp1Layout.createSequentialGroup()
                    .addContainerGap()
                    .add(jp1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
                        .add(jp1Layout.createSequentialGroup()
                            .add(jp1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING, false)
                                .add(org.jdesktop.layout.GroupLayout.LEADING, lblitem, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .add(org.jdesktop.layout.GroupLayout.LEADING, lbldate, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 44, Short.MAX_VALUE))
                            .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                            .add(jp1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                                .add(org.jdesktop.layout.GroupLayout.TRAILING, jp1Layout.createSequentialGroup()
                                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                                    .add(cmbdate, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                                    .add(cmbmonth, 0, 59, Short.MAX_VALUE)
                                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                                    .add(cmbyear, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 70, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                                .add(jp1Layout.createSequentialGroup()
                                    .add(10, 10, 10)
                                    .add(lblfixdate, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 119, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                                .add(cmbitem, 0, 168, Short.MAX_VALUE)
                                .add(jLabel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 168, Short.MAX_VALUE)))
                        .add(jp1Layout.createSequentialGroup()
                            .add(jp1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                                .add(lblqty)
                                .add(lblprice))
                            .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                            .add(jp1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                                .add(tfprice, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 151, Short.MAX_VALUE)
                                .add(tfqty, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 149, Short.MAX_VALUE)
                                .add(lblqtyfix, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 164, Short.MAX_VALUE)
                                .add(lblpricefix, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 164, Short.MAX_VALUE))))
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                    .add(btnAdd, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 64, Short.MAX_VALUE)
                    .addContainerGap())
            jp1Layout.setVerticalGroup(
                jp1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(jp1Layout.createSequentialGroup()
                    .addContainerGap()
                    .add(jp1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                        .add(lbldate)
                        .add(jp1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                            .add(cmbyear, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                            .add(cmbdate, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                            .add(cmbmonth, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
                    .add(5, 5, 5)
                    .add(lblfixdate)
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                    .add(jp1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                        .add(lblitem)
                        .add(cmbitem, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .add(btnAdd))
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                    .add(jLabel1)
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                    .add(jp1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                        .add(lblqty)
                        .add(tfqty, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                    .add(1, 1, 1)
                    .add(lblqtyfix)
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                    .add(jp1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                        .add(lblprice)
                        .add(tfprice, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                    .add(lblpricefix)
                    .addContainerGap(41, Short.MAX_VALUE))
            lblname.setFont(new java.awt.Font("Tahoma", 0, 10));
            lblname.setText("Name :");
            ta.setColumns(20);
            ta.setLineWrap(true);
            ta.setRows(5);
            jScrollPane1.setViewportView(ta);
            btnReport.setFont(new java.awt.Font("Tahoma", 0, 10));
            btnReport.setText("Report");
            btnAddRecord.setFont(new java.awt.Font("Tahoma", 0, 10));
            btnAddRecord.setText("Add New Expense");
            jLabel2.setFont(new java.awt.Font("Tahoma", 0, 10));
            jLabel2.setText("Comments :");
            cmbname.addFocusListener(new java.awt.event.FocusAdapter()
                public void focusGained(java.awt.event.FocusEvent evt)
                    cmbnameFocusGained(evt);
            btnAddname.setFont(new java.awt.Font("Tahoma", 0, 10));
            btnAddname.setText("Add");
            btnAddname.addActionListener(new java.awt.event.ActionListener()
                public void actionPerformed(java.awt.event.ActionEvent evt)
                    btnAddnameActionPerformed(evt);
            menu.setText("File");
            menu1exit.setText("Exit");
            menu1exit.addActionListener(new java.awt.event.ActionListener()
                public void actionPerformed(java.awt.event.ActionEvent evt)
                    menu1exitActionPerformed(evt);
            menu.add(menu1exit);
            jMenuBar1.add(menu);
            setJMenuBar(jMenuBar1);
            org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(layout.createSequentialGroup()
                    .addContainerGap()
                    .add(jp1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                    .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                        .add(layout.createSequentialGroup()
                            .add(10, 10, 10)
                            .add(btnReport, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 102, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                            .add(28, 28, 28)
                            .add(btnAddRecord, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 158, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                        .add(layout.createSequentialGroup()
                            .add(lblname, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 52, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                            .add(15, 15, 15)
                            .add(cmbname, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 194, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                            .add(btnAddname, 0, 0, Short.MAX_VALUE)
                            .add(28, 28, 28)
                            .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                                .add(jLabel2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 89, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                                .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 253, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))))
                    .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            layout.setVerticalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(layout.createSequentialGroup()
                    .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING, false)
                        .add(org.jdesktop.layout.GroupLayout.LEADING, layout.createSequentialGroup()
                            .add(39, 39, 39)
                            .add(jLabel2)
                            .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                            .add(jScrollPane1))
                        .add(org.jdesktop.layout.GroupLayout.LEADING, layout.createSequentialGroup()
                            .add(20, 20, 20)
                            .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                                .add(lblname)
                                .add(cmbname, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                                .add(btnAddname))
                            .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .add(jp1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                    .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                        .add(btnReport)
                        .add(btnAddRecord))
                    .addContainerGap(15, Short.MAX_VALUE))
            pack();
        }// </editor-fold>                       
        private void cmbnameFocusGained(java.awt.event.FocusEvent evt)                                   
    // TODO add your handling code here:
           this.jp1.updateUI();
        public void loadNameCombo()
            doConnection();
            try{
                query ="select name from name_master";
                rs = stmt.executeQuery(query);
                while(rs.next())
                    cmbname.addItem(rs.getString("name"));
            }catch(Exception e){ e.printStackTrace(); }
             // this.repaint();    
        public void reloadComboName()
            cmbname.removeAllItems();
            loadNameCombo();
            this.repaint();
        public void loadItemCombo()
            doConnection();
            try{
                query ="select item_name from item_master";
                rs = stmt.executeQuery(query);
                while(rs.next())
                    cmbitem.addItem(rs.getString("item_name"));
            }catch(Exception e){ e.printStackTrace(); }
        private void btnAddnameActionPerformed(java.awt.event.ActionEvent evt)                                          
    // TODO add your handling code here:
            AddNewName n = new AddNewName();
            n.setVisible(true);
        private void btnAddActionPerformed(java.awt.event.ActionEvent evt)                                      
    // TODO add your handling code here:
            AddNewItem i = new AddNewItem();
            i.setVisible(true);
        private void menu1exitActionPerformed(java.awt.event.ActionEvent evt)                                         
            // TODO add your handling code here:
             System.out.println("Current :"+ day +":"+month+":"+year);
    }AddNewName.java
    * AddNewName.java
    * Created on October 13, 2007, 2:52 PM
    package app;
    import app.ExpTracker;
    import java.sql.*;
    import java.util.Vector;
    * @author  Administrator
    public class AddNewName extends javax.swing.JFrame
        /** Creates new form AddNewName */
        Connection con = null;
        Statement stmt = null;
        ResultSet rs = null;
        String query;
        int status =0;
        String URL="jdbc:mysql://localhost:3306/exptracker";
        String DRIVER ="com.mysql.jdbc.Driver";
        public AddNewName()
            initComponents();
        public void doConnection()
            //make connection
            try
                Class.forName(DRIVER).newInstance();
            catch(Exception e)
            { System.out.println("driver not found"+e.getMessage());     }
            //making query
            try
                con = DriverManager.getConnection(URL, "root", "");
                stmt = con.createStatement();
            catch(Exception e)
            { System.out.println("Connection Failure !"+ e.getMessage());  }
        public void doInsert()
            String name2add = tfnameadd.getText().trim();
            query = "INSERT INTO name_master(name) VALUES ('"+name2add+"')";
            System.out.println("QUERY:"+query);
            try
               status = stmt.executeUpdate(query);
               //System.out.println("Query Status :"+status);
               //con.commit();
            } catch (SQLException ex)
                ex.printStackTrace();
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        // <editor-fold defaultstate="collapsed" desc=" Generated Code ">                         
        private void initComponents()
            jPanel1 = new javax.swing.JPanel();
            lblnewname = new javax.swing.JLabel();
            tfnameadd = new javax.swing.JTextField();
            btnaddname = new javax.swing.JButton();
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Add New Name"));
            lblnewname.setText("Enter Name :");
            tfnameadd.setBorder(javax.swing.BorderFactory.createEtchedBorder());
            btnaddname.setText("Add Name");
            btnaddname.setBorder(javax.swing.BorderFactory.createEtchedBorder());
            btnaddname.addActionListener(new java.awt.event.ActionListener()
                public void actionPerformed(java.awt.event.ActionEvent evt)
                    btnaddnameActionPerformed(evt);
            org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
            jPanel1.setLayout(jPanel1Layout);
            jPanel1Layout.setHorizontalGroup(
                jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(jPanel1Layout.createSequentialGroup()
                    .addContainerGap()
                    .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                        .add(btnaddname, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 108, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .add(jPanel1Layout.createSequentialGroup()
                            .add(lblnewname, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 72, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                            .add(37, 37, 37)
                            .add(tfnameadd, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 218, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
                    .addContainerGap(20, Short.MAX_VALUE))
            jPanel1Layout.setVerticalGroup(
                jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(jPanel1Layout.createSequentialGroup()
                    .addContainerGap()
                    .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                        .add(lblnewname)
                        .add(tfnameadd, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                    .add(btnaddname, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 32, Short.MAX_VALUE)
                    .addContainerGap())
            org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(layout.createSequentialGroup()
                    .addContainerGap()
                    .add(jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addContainerGap())
            layout.setVerticalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(layout.createSequentialGroup()
                    .addContainerGap()
                    .add(jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addContainerGap())
            pack();
        }// </editor-fold>                       
        private void btnaddnameActionPerformed(java.awt.event.ActionEvent evt)                                          
    // TODO add your handling code here:
            ExpTracker et = new ExpTracker();
             doConnection();
             doInsert();
                if(status == 1)
                    javax.swing.JOptionPane.showMessageDialog(this,"Record Inserted Successfully.");
                    this.setVisible(false);
                    et.repaint();
                    et.reloadComboName();
                    //this.repaint();
                else
                    javax.swing.JOptionPane.showMessageDialog(this,"Record Failed to Insert.","Error",2);
         * @param args the command line arguments
        // Variables declaration - do not modify                    
        private javax.swing.JButton btnaddname;
        private javax.swing.JPanel jPanel1;
        private javax.swing.JLabel lblnewname;
        private javax.swing.JTextField tfnameadd;
        // End of variables declaration                  
    }AddNewItem.java
    * AddNewItem.java
    * Created on October 13, 2007, 2:19 PM
    package app;
    import java.sql.*;
    import java.util.*;
    * @author  Administrator
    public class AddNewItem extends javax.swing.JFrame
        /** Creates new form AddNewItem */
        Connection con = null;
        Statement stmt = null;
        ResultSet rs = null;
        String query;
        int status =0;
        String URL="jdbc:mysql://localhost:3306/exptracker";
        String DRIVER ="com.mysql.jdbc.Driver";
        public AddNewItem()
            super("Add New Item");
            initComponents();
        public void doConnection()
            //make connection
            try
                Class.forName(DRIVER).newInstance();
            catch(Exception e)
            { System.out.println("driver not found"+e.getMessage());     }
            //making query
            try
                con = DriverManager.getConnection(URL, "root", "");
                stmt = con.createStatement();
            catch(Exception e)
            { System.out.println("Connection Failure !"+ e.getMessage());  }
        public void doInsert()
            String item2add = tfadditem.getText().trim();
            query = "INSERT INTO item_master(item_name) VALUES ('"+item2add+"')";
            System.out.println("QUERY:"+query);
            try
               status = stmt.executeUpdate(query);
               //System.out.println("Query Status :"+status);
               //con.commit();
            } catch (SQLException ex)
                ex.printStackTrace();
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        // <editor-fold defaultstate="collapsed" desc=" Generated Code ">                         
        private void initComponents()
            jPanel1 = new javax.swing.JPanel();
            lblitemname = new javax.swing.JLabel();
            tfadditem = new javax.swing.JTextField();
            btnAddItem = new javax.swing.JButton();
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            setAlwaysOnTop(true);
            jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Add New Item"));
            lblitemname.setText("Item to add :");
            tfadditem.setBorder(javax.swing.BorderFactory.createEtchedBorder());
            btnAddItem.setText("Add Item");
            btnAddItem.setBorder(javax.swing.BorderFactory.createEtchedBorder());
            btnAddItem.addActionListener(new java.awt.event.ActionListener()
                public void actionPerformed(java.awt.event.ActionEvent evt)
                    btnAddItemActionPerformed(evt);
            org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
            jPanel1.setLayout(jPanel1Layout);
            jPanel1Layout.setHorizontalGroup(
                jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(jPanel1Layout.createSequentialGroup()
                    .add(18, 18, 18)
                    .add(jPanel1Layout.createParallelGroup(org.jd                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Repaint/Refreshing AWT components

    Hi there,
    I'm writing a chess game and for the GUI I've added 8x8 panels into a frame with a grid layout. Currently I'm just using labels for the pieces, in the middle of panels. I'm having a problem updating my GUI after a move has been made - a call to repaint() does nothing. I'm just using basic AWT.
    I've also tried removeAllComponents() of the frame and adding them again with the updated data, but nothing happens - I just lose all my panels. Can anyone help please?
    Many thanks!

    scsi-boy :
    I want to have a more general method of refreshing the
    graphics so that later if/when I 'upgrade' to using
    images (or whatever) instead of labels I can simplyi believe my suggestion is certainly compatible with that.
    adapt it. I would think that calling setText for the
    Labels would mean that I would have to give the
    location of the panel as a parameter somewhere, and
    would also have to remove the label where the piece
    was previously (ie if a knight moves, I'd have to
    target its destination to setText and remove it from
    where it was).here is what i would do, please note that this will work with a variety
    of implementations including using all Graphics later on or whatever.
    // here we have a bunch of constants that represent the possible status
    // of board postions
    final int EMPTY_SPACE = 0;
    final int B_KING = 1;
    final int W_KING = 2;
    final int B_QUEEN = 3;
    final int W_QUEEN = 5;
    final int B_BISHOP = 6;
    final int W_BISHOP = 7;
    final int B_KNIGHT = 8;
    final int W_KNIGHT = 9;
    final int B_ROOK = 10;
    final int W_ROOK = 11;
    final int B_PAWN = 12;
    final int W_PAWN = 13;
    // the game board is used to store the status of all the postitions in
    // a game
    int[][] gameBoard;
    // the game display is the array of Labels that we use to present the
    // board in our GUI
    Label[][] gameDisplay;
    // in the constructor;
    gameBoard = new int[8][8];
    for(int i=0;i<gameBoard.length;i++){
      for(int j=0;i<8;j++){
        gameBoard[i][j] = EMPTY_SPACE;
    // here is where you would add the various pieces to gameBoard...
    gameDisplay = new Label[8][8];
      Now wherever you interaction and logic are you can use a method. You
      can call this method repaint(); so that it will be compatible with
      what you do later.
    public void repaint(){
      for(int i=0;i<gameBoard.length;i++){
        for(int j=0;j<8;j++){
          switch(gameBoard[i][j]){
            case B_KING:
              gameDisplayj].setText("Black King");
    break;
    case W_KING:
    gameDisplay[i]j].setText("White King");
    break;
    case B_QUEEN:
    gameDisplay[i]j].setText("Black Queen");
    break;
    // and so on and so forth... until
    default:
    gameDisplay[i]j].setText("");
    anyway the above code is just a sample of how you can build this so you
    can seperate out your logic from your GUI so you can change your GUI
    later without hassle.
    finally i would ask how are you changing the text on the screen. are you
    creating new Labels and sticking them in the Panels? i suspect something
    like this... don't do that. two reasons, one as you may have noticed it
    doesn't work that way or you have to use some sort of hack to get it to
    work and two it's more efficient in terms of memory and speed if you
    re-use the awt ot Swing components by making use of methods such as
    setText rather than creating new objects each time.
    i hope you find this helpful.

  • Preventing applet from repainting/refreshing on resize

    hi,
    anyone has any idea on how one can prevent an applet from repainting the GUI screen when the applet is resized (minimized, maximized etc). i have a chat applet, but whenever the applet is minimized, all the present chat transcripts are lost and a new/refreshed window is displayed. how can we prevent this from happening? in effect, i want my applet to be displayed in the same state as it was before it was minimized.
    is there something i am missing?
    thanks,
    Satyen

    hi all,
    is this doubt really difficult, or i am missing something so very obvious, that no one out there wants to point it out.
    any suggestions would be very helping. and please, i am not looking for code snippets, any pointers/suggestions to the solution of the problem would suffice.
    thanks,
    Satyen.

  • 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: 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]

  • 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 refresh JPanel?

    Hello
    I'm writing applet and I got stuck. I have JPanel which is in createAndShowGUI() and it's invoked from init() with invokeAndWait. This JPanel contains array of images. I'd like to
    remove JPanel and paint different configuration of images. All in the same applet window. This would happen after I pushed one of the images.
    How can it be done?.
    Cheers
    Message was edited by:
    macmacmac

    you can use keyword "repaint". you can write that keyword to the method void paintComponent(Graphics g). or you can use remove method from JPanel and create the new JPanel

  • 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 ...

Maybe you are looking for

  • Why can I no longer capture DV clips?

    I can no longer capture DV clips that are useable. Is it a wrong setting or maybe bad hardware? I'm logging and capturing clips as DV anamorphic (downconverted by my deck from HDV), and when I play back the captured clip, the image in the viewer isn'

  • Upgrade oracle 10.2.0.3 32bit to oracle 11.1.7 x64

    Hi There, I'm trying to upgrade from oracle 10.2.0.3 to 11.1.7 and I'm wondering what's the best way of doing this. THe problem is that production server is windows 2003 server 32 bit running oracle 10.2.0.3 standard edition. The new server is window

  • Need help in preparation of BR30 and BP80

    Dear Gurus, I am new to the implementation and we are about to complete requirement gathering.... soon i need to prepare BP 80 and BR 30 for OM, INV and PO, i have gone through the available information on the web. Still some confusion, can anyone pl

  • Itunes update failed and now itunes won't open

    If I uninstall and then reinstall itunes, will my music "reappear"?  What about the music that I manually added to my itunes (via CD)? Any help would be great!  Thanks so much!!

  • My new Online number not displaying on the phones....

    My new online number is not showing up when i call mobiles (tried several of them). It is impossible to select it from the pre-selected numbers or anything of that kind. I can select that skype shows all my previous historical numbers that i have eve