JPanel doesn't paint graphics

Hi ! I've been writing a program that should graph a linear function, the problem is that I'm trying to draw a line in a JPanel but this doesn't work XD...The program has 2 windows. The first one is the windows from where i get data for the function, after having the data I press a button that I want to open a new window and draw the function...
This is the part of the code in the button on the first window that certainly opens a new window
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
   JFrame frm_grafica = new JFrame("Grafica - B-Rabbit");
   frm_grafica.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   Grafica graph = new Grafica();   
   frm_grafica.getContentPane().add(graph);
   frm_grafica.setSize(250,250);
   frm_grafica.setLocation(this.getLocation().x+this.getWidth()+5, this.getLocation().y);
   frm_grafica.setVisible(true);
}but in the new window [that is located beside the first window] this is the code, that doesn't work...yes maybe there's something i don't do or something that i am passing over..
public class Grafica extends JPanel{
    Grafica(){
        this.setBackground(Color.WHITE);
    protected void PaintComponent(Graphics g){
        super.paint(g);
        g.setColor(Color.BLACK);
        g.drawLine(50,50, 20, 20);
}So Hope someone helps me...

//protected void PaintComponent(Graphics g){
protected void paintComponent(Graphics g){//<-- it's 2.00am, small p
        //super.paint(g);
        super.paintComponent(g);

Similar Messages

  • Scrolling a custom Component (e.g. JPanel) with overridden paint(Graphic g)

    Hi.
    I&#8217;m creating an application for modelling advanced electrical systems in a house. Until now I have focused on the custom canvas using Java2D to draw my model. I can move the model components around, draw lines between them, and so on.
    But now I want to implement a JScrollPane to be able to scroll a large model. I&#8217;m currently using a custom JPanel with a complete override of the paint(Graphic g) method.
    Screen-shot of what I want to scroll:
    http://pchome.grm.hia.no/~aalbre99/ScreenShot.png
    Just adding my custom JPanel to a JScrollPane will obviously not work, since the paint(Graphic g) method for the JPanel would not be used any more, since the JScrollPane now has to analyze which components inside the container (JPanel) to paint.
    So my question is therefore: How do you scroll a custom Component (e.g. JPanel) where the paint(Graphic g) method is totally overridden.
    I believe the I have to paint on a JViewport instructing the JScrollPane my self, but how? Or is there another solution to the problem?
    Thanks in advance for any suggestions.
    Aleksander.

    I�m currently using a custom JPanel with a complete override of the paint(Graphic g) method. Althought this isn't your problem, you should be overriding the paintComponent(..) method, not the paint(..) method.
    But now I want to implement a JScrollPane to be able to scroll a large model.When you create a custom component to do custom painting then you are responsible for determining the preferredSize of the component. So, you need to override the getPreferredSize(...) method to return the preferredSize of your component. Then scrolling will happen automatically when the component is added to a scrollPane.

  • Painting graphics on JPanel

    hi all,
    below is my code,
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.Graphics2D;
    import java.awt.Graphics.*;
    public class Testing extends JFrame implements ActionListener
    String x[] = { " ", "Material A", "Material B", "Material C"};
    String y[] = { "                       ", "+5", "+4", "+3", "+2", "+1", " 0",
         "-1", "-2", "-3", "-2", "-5" };
    private JButton Plot, End;
    private Container c;
    private JPanel centerPanel, northPanel, southPanel;
    private JComboBox designMaterialx, materialRatingy;
    String desMaterial = "";
    public Testing()
    super( "Welcome" );
         Container c = getContentPane();
         centerPanel = new JPanel()
              protected void paintComponent(Graphics g)
              super.paintComponent(g);
              Graphics2D g2d = (Graphics2D)g;
              g.setColor(Color.blue);
    g.drawRect(120, 120, 20, 200);
    g.drawString ("Material", 30, 220);
    g.drawString ("Ratings", 30, 240);
    g.drawString ("+5", 102, 130);
    g.drawString ("0", 107, 220);
    g.drawString ("-5", 102, 315);
              g.setColor(Color.red);
              g.drawRect(120, 321, 20, 200);
              g.drawString ("Design", 30, 410);
              g.drawString ("Materials", 30, 430);
              g2d.rotate(-Math.PI/2.0,250.0,250.0);
              g.setColor(Color.black);
              g.drawString(desMaterial, -15, 135);
              centerPanel.setBackground(Color.white);
         c.add( centerPanel, BorderLayout.CENTER);
         setVisible(true);
              northPanel = new JPanel();
              northPanel.add(new Label( "Please choose accordingly:" ));
         northPanel.setLayout (new FlowLayout(FlowLayout.CENTER, 20, 0));
    designMaterialx = new JComboBox( x );
    designMaterialx.setMaximumRowCount( 2 );
    designMaterialx.setBorder(BorderFactory.createTitledBorder("Design Materials"));
    northPanel.add( designMaterialx );
    designMaterialx.setEditable(true);
    materialRatingy = new JComboBox( y );
    materialRatingy.setMaximumRowCount( 2 );
    materialRatingy.setBorder(BorderFactory.createTitledBorder("Material Ratings"));
    northPanel.add( materialRatingy );
    c.add( northPanel, BorderLayout.NORTH );
    setVisible( true );
    southPanel = new JPanel();
    Plot = new JButton( "Plot" );
    End = new JButton( "End" );
    southPanel.add( Plot );
    southPanel.add( End );
    c.add( southPanel, BorderLayout.SOUTH );
    setVisible( true );
    Plot.addActionListener(this);
    End.addActionListener(this);
    Plot.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent e)
    desMaterial = designMaterialx.getSelectedItem().toString();
    centerPanel.repaint();
    System.out.println(desMaterial);
    pack();
    public static void main( String args[] )
    Testing app = new Testing();
    app.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
    public void actionPerformed(ActionEvent e)
         if(e.getSource()==Plot)
              System.out.println("Plot");
         else if(e.getSource()==End)
              System.exit(0);
    at the moment when the plot jButton is pressed, the selected values of the design materials jComboBox will be painted on the centerPanel inside the red rectangle. upon subsequent selection of the design materials & pressing of the plot jbutton, i wish to add them next to the existing ones but i'm not sure how to do this. could anyone out there help me on this? any kind of help would be appreciated.
    thanks in advance.
    rolf

    Here's a bunch of ideasimport java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.ArrayList;
    public class Test3 extends JFrame {
      MyGraph mg = new MyGraph();
      JTextField nameField = new JTextField("Sample2");
      JTextField valueField = new JTextField("100");
      public Test3() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Container content = getContentPane();
        mg.addData(new MyData("Sample",50));
        content.add(mg, BorderLayout.CENTER);
        JPanel dataPanel = new JPanel();
        dataPanel.add(new JLabel("Name:"));
        dataPanel.add(nameField);
        dataPanel.add(new JLabel("Value:"));
        dataPanel.add(valueField);
        JButton jb = new JButton("Add");
        dataPanel.add(jb);
        jb.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent ae) {
            mg.addData(new MyData(nameField.getText(),Integer.parseInt(valueField.getText())));
            mg.repaint();
        content.add(dataPanel, BorderLayout.NORTH);
        setSize(300,300);
      public static void main(String[] args) { new Test3().setVisible(true); }
    class MyGraph extends JPanel {
      ArrayList al = new ArrayList();
      public void addData(MyData data) { al.add(data); }
      public void paintComponent(Graphics g) {
        Graphics2D g2d = (Graphics2D)g;
        super.paintComponent(g2d);
        g2d.setColor(Color.red);
        int height = getHeight(), width=getWidth();
        for (int i=0; i<al.size(); i++) {
          MyData md = (MyData)al.get(i);
          g2d.drawRect(i*20,height-md.getNum(),17,md.getNum());
        g2d.rotate(-Math.PI/2.0,width/2,height/2);
        g2d.setColor(Color.blue);
        for (int i=0; i<al.size(); i++) {
          MyData md = (MyData)al.get(i);
          g2d.drawString(md.getName(),30,i*20-15);
    class MyData {
      String name;
      int num;
      public MyData(String name, int num) {
        this.name=name;
        this.num=num;
      public String getName() { return name; }
      public int getNum() { return num; }
    }

  • Painting Graphics from an Array

    I have a GUI that displays the Towers of Hanoi solution in a JPanel. Everything actually works except for a slight repainting issue.
    Currently I am overriding the paint() function, I know that for my purpose using paintComponent() would probably be the better route, however that's not my issue...
    The images (disks) in my JPanel are not redrawing properly, and I have no idea why...
    Basically:
    - I call setup() to set the number of disks and the co ordinates they should be drawn. (store them in an array)
    - I call moveDisk() to change the co ordinates of each disk as they are being moved.
    - then drawDisk() is called to go through the array of disks and print them.
    currently paint() calls drawDisk() in order to display the current position of all the disks.
    It seems to work fine for the first 2 moves, then disks start disappearing until there is one (the last disk) left...BUT if I print the co ordinates of the disks they seem to be correct, just not drawing.
    could someone take a look at my code and see what is wrong?
    below is the meat of the code, minus the GUI:
        public class HanoiFrame extends javax.swing.JFrame {
        private static final int STATE_SETUP = 0;
        private static final int STATE_ANIMATE = 1;
        private static final int POLE_AREA_HEIGHT = 356;
        private static final int POLE_AREA_WIDTH = 205;
        private static final int DISK_ARC_HEIGHT = 15;
        private static final int DISK_ARC_WIDTH = 15;
        private static final int DISK_HEIGHT = 23;
        private static final int MAX_DISKS = 10;
        private static final int MAX_ANIMATION_DELAY = 30000;
        private static final int MAX_PHYSICAL_DELAY = 100000;
        private static final int MIN_DISKS = 1;
        private static final int MIN_ANIMATION_DELAY = 1;
        private static final int MIN_PHYSICAL_DELAY = 1;
        private static final int EMPTY_CELL_VALUE = -1;
        private static final int CELL_HEIGHT = 25;
        private static final int COLUMNS = 3;
        private static final int ROW = 11;
        private  static final int MILLISECONDS_PER_SECOND = 1000;
        private final static String newline = "\n";
        private static Disk[] disks;
        private static Disk newDisk;
        private static int[][] diskCells;
        public static  int startX = 2;
        public static  int startY = 340;
        public static int setDiskAmount = 0;
        public static int setAnimationDelay = 0;
        public static int  setPhysicalDelay = 0;
        public static int  moveNumber = 0;
        public static int intMovesLeft = 0;
        private boolean  buttonPressed = false;
        private double movesLeft = 0;
        private int windowState = 0;
        /** Creates new form HanoiFrame */
        public HanoiFrame() {
            initComponents();
            /* initialize the "poles" to hold a certain number of "cells */
            this.diskCells = new int[ROW][COLUMNS];
            for (int row = ROW - 1;row >= 0; row--) {
                for (int col = 0;col < COLUMNS ; col++) {
                    diskCells[row][col] = EMPTY_CELL_VALUE;
        private void resetButtonActionPerformed(java.awt.event.ActionEvent evt) {                                           
            /* reset all the variable to original state */
            setDiskAmount = 0;
            setAnimationDelay = 0;
            setPhysicalDelay = 0;
            moveNumber = 0;
            movesLeft = 0;
            intMovesLeft = 0;
            buttonPressed = false;
            windowState = 0;
            this.startButton.setEnabled(true);
            this.diskAmount.setEditable(true);
            this.animationDelay.setEditable(true);
            this.physicalDelay.setEditable(true);
            /* reset all the cell vales to empty (this could be its own function) */
            for (int row = ROW - 1;row >= 0; row--) {
                for (int col = 0;col < COLUMNS ; col++) {
                    diskCells[row][col] = EMPTY_CELL_VALUE;
            /* reset the content of the TextFields and Area */
            this.diskAmount.setText("");
            this.animationDelay.setText("");
            this.physicalDelay.setText("");
            this.outTextArea.setText("");
            /* repaint the display panel */
            this.hanoiPanel.repaint();
        /* i have no idea why this is here...It was generated by Netbeans when I
         *made the reset button.  As you can see it made 2.  The one above it the same
         *except it contains code.  Since it was automatically generated
         *I cannot delete it.
        private void resetButtonMouseReleased(java.awt.event.MouseEvent evt) {                                         
        /* is executed when the start button is pressed.
         *also executes a field check and intializes key variables. Finally,
         *it executes the solution and generates the solve time
        private void startButtonMouseReleased(java.awt.event.MouseEvent evt) {                                         
            /* check if the program has already been run (without being reset) */
            if (!buttonPressed){
                /* check the fields to ensure the input is correct and useable */
                if (checkFields()){
                    /* give button a pressed status if all info valid */
                    buttonPressed = true;
                    windowState = 1;
                    /* disable the button */
                    this.startButton.setEnabled(false);
                    /* disable the fields */
                    this.diskAmount.setEditable(false);
                    this.animationDelay.setEditable(false);
                    this.physicalDelay.setEditable(false);
                    /* setup the disks on the starting pole */
                    setup();
                    /* initialize the number of moves required. 2 to the power of n minus 1 */
                    movesLeft = Math.pow(2, setDiskAmount) - 1;
                    /* convert the number to an integer */
                    intMovesLeft = (int)movesLeft;
                    /* set the physical delay */
                    setPhysicalDelay = Integer.parseInt(this.physicalDelay.getText());
                    /* create and start a new thread.  This is EXTREMELY important
                     *as it allows for GUI to be repainted while the soulution
                     *is animated */
                    SolveEngine s = new SolveEngine();
                    s.start();               
         * @param args the command line arguments
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new HanoiFrame().setVisible(true);
        /*returns the Animation panel area graphics
         *@return Animation area graphics
        public static Graphics getAnimationArea(){
            /* get the usable area of poleA */
            Container clientArea = hanoiPanel;
            //Container clientArea = this.getContentPane();
            /* get the graphics to the display panel*/
            Graphics gfx = clientArea.getGraphics();
            return gfx;
         *set up the requested amount of disks on the first pole
         *@param diskAmount the amount of disks entered by the user
        public void setup(){
            int numberOfDisks = setDiskAmount;
            this.disks = new Disk[numberOfDisks];
            int diskNumber = 0;
            int diskWidth = POLE_AREA_WIDTH - 4;
            int arcH = DISK_ARC_HEIGHT;
            int arcW = DISK_ARC_WIDTH;
            int x = startX;
            int y = startY;
            int row = 0;
            int col = 0;
            /* get the graphics to the display panel*/
            //Graphics gfx = getAnimationArea();
            /* set the color of the disks */
            //gfx.setColor(Color.MAGENTA);
            /* draw the specified number of disks */
            while (diskNumber < numberOfDisks){
                /* reduce the y position */
                y = startY - diskNumber * CELL_HEIGHT;
                /* draw the disk */
                //gfx.fillRoundRect(x, y, diskWidth, DISK_HEIGHT, arcH, arcW);
                /* create a new instance of disk */
                newDisk = new Disk(x, y, diskWidth);
                /* give the new disk an id */
                this.disks[diskNumber] = newDisk;
                /* add the id to the cell array of poleA */
                this.diskCells[row][col] = diskNumber;
                /* make the disk smaller and center */
                x = x + 8;
                diskWidth = diskWidth - 16;
                /* increase disk number */
                diskNumber++;
                /* move to the next row */
                row++;
            repaint();
         *move the disk from a source pole to the destination pole.
         *this should take the source col and destination col to determine where to draw the
         *disk.  It will also need to know to draw the disk in the first available cell
         *in a col
         *@param source the starting pole of the next move
         *@param destination the end pole of the next move
        public void moveDisk(int src, int dest){
            /* the lines below would not be necessary if I were to pass the Graphics
             *gfx object as a parameter.  I may have to use this option in order
             *to work around the current repainting issue */
            /* get the graphics to the display panel*/
            Graphics gfx = getAnimationArea();
            /* get the id of the disk to be moved */
            int disk = getDiskId(src);
            /* get the to and from rows */
            int sourceRow = getRow(src);
            int destinationRow = getRow(dest);
            /* set the co ordintates of the destination */
            int col = dest * POLE_AREA_WIDTH;
            int x = disks[disk].getStartX() + col;
            int y = startY - (destinationRow * CELL_HEIGHT);
            int width = disks[disk].getDiskWidth();
            disks[disk].setStartX(x);
            disks[disk].setStartY(y);
            disks[disk].setDiskWidth(width);
            //System.out.println("startX " + x);
            //System.out.println("startY " + y);
            //System.out.println("destination row " + destinationRow);
            //System.out.println("disk " + disk);
            //System.out.println("Width " + width);
            diskCells[sourceRow - 1][src] = EMPTY_CELL_VALUE;
            /* set the destination row to the disk id */
            diskCells[destinationRow][dest] = disk;
            drawDisk();
            repaint();
        public void drawDisk(){
            int diskNum = setDiskAmount -1;
            int i = 0;
            Graphics gfx = getAnimationArea();
            gfx.setColor(Color.MAGENTA);
            while(diskNum >= 0){
                //System.out.println("here is the disk IDs " + diskNum);
                //System.out.println("the startY during draw " + disks[diskNum].getStartY());
                gfx.fillRoundRect(disks[diskNum].getStartX(), disks[diskNum].getStartY(), disks[diskNum].getDiskWidth(), DISK_HEIGHT, DISK_ARC_WIDTH, DISK_ARC_HEIGHT);
                diskNum--;
        public void paint(Graphics gfx){
            if(windowState == 0){
                super.paint(gfx);
                setup();
            } else if (windowState == 1){
                super.paint(gfx);
                drawDisk();
         *returns the id of the disk
         *@param col the the designated column
         *@return the disk identification number
        public static int getDiskId(int col){
            int diskIdent = 0;
            /* initialize the row number to max -1, because the array start at 0 */
            int row = MAX_DISKS - 1;
            /* do a cell check while row is greater than 0
             *this is done so that is starts at the top row
             *and moves down
            while (row > EMPTY_CELL_VALUE){
                /* when the first cell that is not -1 is reached get the disk number
                 *that disk will be the smallest in the stack */
                if(diskCells[row][col] != -1){
                    //diskIdent = this.diskCells[row][col];
                    diskIdent =diskCells[row][col];
                    break;
                row--;
            return diskIdent;
         *returns the first available row
         *@param col the designated col
         *@return the first available row number
        public static int getRow(int col){
            int rowNumber = 0;
            /* cycle through the cells until it finds an empty one */
            while (diskCells[rowNumber][col] != -1){
                rowNumber++;
            return rowNumber;
         *calculate the total time it takes for the tower of hanoi game to be
         *solved, given the amount of disk and the amount of time it takes
         *to physically move a disk from one pole to the other.
        public static void totalTime(){
            int timeInSeconds = setPhysicalDelay * intMovesLeft;
            int i = 0;
            int seconds = 0;
            int minute = 0;
            int hour = 0;
            int day = 0;
            int month = 0;
            int year = 0;
            while (i < timeInSeconds){
                if(seconds > 60){
                    minute++;
                    seconds = 0;
                if(minute > 60){
                    hour++;
                    minute = 0;
                if(hour > 24){
                    day++;
                    hour = 0;
                if(day > 30){
                    month++;
                    day = 0;
                if(month > 12){
                    year++;
                    month = 0;
                seconds++;
                i++;
            updateMessageCenter("It would take:" + year + " years " + month + " months " + day +
                    " days " + hour + " hours " + minute + " minutes and " + seconds + " seconds, to move " + setDiskAmount +
                    " disks at " + setPhysicalDelay + " seconds per move");
       

    Sorry if my post was a little too cryptic...
    "How do you know? You have a problem you can't solve. Anything could be your issue." Agreed. However, using the process of elimination and debug statments I have been able to narrow the scope of the issue.
    "If you can't solve it by executing the code and adding debug statements how to you expect us to help."If I could solve but "executing code and adding debug statements" there would be no need to post the problem here.
    "We don't know exactly what you are attempting to do."Trying to paint my graphics to a JPanel based on a set of co ordinates.
    "We don't know why you are passing the Graphics object around."Why not? is it impossible to do it this way?
    "The big problem is in the alogorithm you use to determine the location of each component."Who said you couldn't read minds?
    "If you are using some kind of animation then I would use a Timer to schedule the moving of components. I don't even see how you are doing this in your code."Sorry I guess stating that I didn't post my entire code may have threw things off...I do use a timer in a seperate class. I will include it in the next post.
    "I can't tell if you are using Threads of not."guess you overlooked these lines of code:
                    /* create and start a new thread.  This is EXTREMELY important
                     *as it allows for GUI to be repainted while the soulution
                     *is animated */
                    SolveEngine s = new SolveEngine();
                    s.start();   Here is the code once again:
    public class HanoiFrame extends javax.swing.JFrame {
        private static final int STATE_SETUP = 0;
        private static final int STATE_ANIMATE = 1;
        private static final int POLE_AREA_HEIGHT = 356;
        private static final int POLE_AREA_WIDTH = 205;
        private static final int DISK_ARC_HEIGHT = 15;
        private static final int DISK_ARC_WIDTH = 15;
        private static final int DISK_HEIGHT = 23;
        private static final int MAX_DISKS = 10;
        private static final int MAX_ANIMATION_DELAY = 30000;
        private static final int MAX_PHYSICAL_DELAY = 100000;
        private static final int MIN_DISKS = 1;
        private static final int MIN_ANIMATION_DELAY = 1;
        private static final int MIN_PHYSICAL_DELAY = 1;
        private static final int EMPTY_CELL_VALUE = -1;
        private static final int CELL_HEIGHT = 25;
        private static final int COLUMNS = 3;
        private static final int ROW = 11;
        private  static final int MILLISECONDS_PER_SECOND = 1000;
        private final static String newline = "\n";
        private static Disk[] disks;
        private static Disk newDisk;
        private static int[][] diskCells;
        public static  int startX = 2;
        public static  int startY = 340;
        public static int setDiskAmount = 0;
        public static int setAnimationDelay = 0;
        public static int  setPhysicalDelay = 0;
        public static int  moveNumber = 0;
        public static int intMovesLeft = 0;
        private boolean  buttonPressed = false;
        private double movesLeft = 0;
        private int windowState = 0;
        /** Creates new form HanoiFrame */
        public HanoiFrame() {
            initComponents();
            /* initialize the "poles" to hold a certain number of "cells */
            this.diskCells = new int[ROW][COLUMNS];
            for (int row = ROW - 1;row >= 0; row--) {
                for (int col = 0;col < COLUMNS ; col++) {
                    diskCells[row][col] = EMPTY_CELL_VALUE;
        private void resetButtonActionPerformed(java.awt.event.ActionEvent evt) {                                           
            /* reset all the variable to original state */
            setDiskAmount = 0;
            setAnimationDelay = 0;
            setPhysicalDelay = 0;
            moveNumber = 0;
            movesLeft = 0;
            intMovesLeft = 0;
            buttonPressed = false;
            windowState = 0;
            this.startButton.setEnabled(true);
            this.diskAmount.setEditable(true);
            this.animationDelay.setEditable(true);
            this.physicalDelay.setEditable(true);
            /* reset all the cell vales to empty (this could be its own function) */
            for (int row = ROW - 1;row >= 0; row--) {
                for (int col = 0;col < COLUMNS ; col++) {
                    diskCells[row][col] = EMPTY_CELL_VALUE;
            /* reset the content of the TextFields and Area */
            this.diskAmount.setText("");
            this.animationDelay.setText("");
            this.physicalDelay.setText("");
            this.outTextArea.setText("");
            /* repaint the display panel */
            this.hanoiPanel.repaint();
        /* i have no idea why this is here...It was generated by Netbeans when I
         *made the reset button.  As you can see it made 2.  The one above it the same
         *except it contains code.  Since it was automatically generated
         *I cannot delete it.
        private void resetButtonMouseReleased(java.awt.event.MouseEvent evt) {                                         
        /* is executed when the start button is pressed.
         *also executes a field check and intializes key variables. Finally,
         *it executes the solution and generates the solve time
        private void startButtonMouseReleased(java.awt.event.MouseEvent evt) {                                         
            /* check if the program has already been run (without being reset) */
            if (!buttonPressed){
                /* check the fields to ensure the input is correct and useable */
                if (checkFields()){
                    /* give button a pressed status if all info valid */
                    buttonPressed = true;
                    windowState = 1;
                    /* disable the button */
                    this.startButton.setEnabled(false);
                    /* disable the fields */
                    this.diskAmount.setEditable(false);
                    this.animationDelay.setEditable(false);
                    this.physicalDelay.setEditable(false);
                    /* setup the disks on the starting pole */
                    setup();
                    /* initialize the number of moves required. 2 to the power of n minus 1 */
                    movesLeft = Math.pow(2, setDiskAmount) - 1;
                    /* convert the number to an integer */
                    intMovesLeft = (int)movesLeft;
                    /* set the physical delay */
                    setPhysicalDelay = Integer.parseInt(this.physicalDelay.getText());
                    /* create and start a new thread.  This is EXTREMELY important
                     *as it allows for GUI to be repainted while the soulution
                     *is animated */
                    SolveEngine s = new SolveEngine();
                    s.start();
         *Check all the fields at once to ensure that they are valid
        private boolean checkFields(){
            String numberOfDisks = null;
            String animationDelay = null;
            String physicalDelay = null;
            numberOfDisks = this.diskAmount.getText();
            animationDelay = this.animationDelay.getText();
            physicalDelay = this.physicalDelay.getText();
            /* initiate my array of error messages */
            ArrayList errMsg = new ArrayList(0);
            /* check if the number of disks was left blank */
            if (numberOfDisks.equals("")){
                errMsg.add("Please enter the Number of Disks (MAX " + MAX_DISKS + ")");
            }else{
                /* check if the input given is valid */
                try {
                    /* parse the disk amount entered into an integer */
                    setDiskAmount = Integer.parseInt(numberOfDisks);
                    /* check the # of disks entered is greater than 0 and less than 10 */
                    if (setDiskAmount < MIN_DISKS){
                        errMsg.add("Number of Disks must be greater than " + MIN_DISKS);
                    } else if (setDiskAmount > MAX_DISKS){
                        errMsg.add("Number of Disks must be less than" + MAX_DISKS);
                } catch (NumberFormatException ex) {
                    errMsg.add("Number of Disks must be a Number");
            /* check if animation delay was left blank */
            if (animationDelay.equals("")){
                errMsg.add("Please enter disk Animation Delay");
            } else {
                /* check if the input given is valid */
                try {
                    /* parse the animation delay entered into an integer */
                    setAnimationDelay = Integer.parseInt(animationDelay);
                    /* check range of animation delay */
                    if (setAnimationDelay < MIN_ANIMATION_DELAY){
                        errMsg.add("Animation Delay must be greater than 0");
                    } else if (setAnimationDelay > MAX_ANIMATION_DELAY){
                        errMsg.add("Animation Delay must be less than " + MAX_ANIMATION_DELAY);
                } catch (NumberFormatException ex) {
                    errMsg.add("Animation Delay must be a Number");
            /* check if physical delay was left blank */
            if (physicalDelay.equals("")){
                errMsg.add("Please enter the Physical disk delay");
            } else {
                /* check if the input given is valid */
                try {
                    /* parse the physical delay entered into an integer */
                    setPhysicalDelay = Integer.parseInt(physicalDelay);
                    /* check check the range of the physical delay */
                    if (setPhysicalDelay < MIN_PHYSICAL_DELAY){
                        errMsg.add("Physical Delay must be greater than 0");
                    } else if (setPhysicalDelay > MAX_PHYSICAL_DELAY){
                        errMsg.add("Physical Delay must be less than " + MAX_PHYSICAL_DELAY);
                } catch (NumberFormatException ex) {
                    errMsg.add("Physical Delay must be a Number");
            /* if there is any problem, add the message to the popup and display */
            if (!errMsg.isEmpty()){
                JOptionPane.showMessageDialog(this, errMsg.toArray());
                return false;
            return true;
         * @param args the command line arguments
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new HanoiFrame().setVisible(true);
        /*returns the Animation panel area graphics
         *@return Animation area graphics
        public static Graphics getAnimationArea(){
            /* get the usable area of poleA */
            Container clientArea = hanoiPanel;
            //Container clientArea = this.getContentPane();
            /* get the graphics to the display panel*/
            Graphics gfx = clientArea.getGraphics();
            return gfx;
         *set up the requested amount of disks on the first pole
         *@param diskAmount the amount of disks entered by the user
        public void setup(){
            int numberOfDisks = setDiskAmount;
            this.disks = new Disk[numberOfDisks];
            int diskNumber = 0;
            int diskWidth = POLE_AREA_WIDTH - 4;
            int arcH = DISK_ARC_HEIGHT;
            int arcW = DISK_ARC_WIDTH;
            int x = startX;
            int y = startY;
            int row = 0;
            int col = 0;
            /* get the graphics to the display panel*/
            //Graphics gfx = getAnimationArea();
            /* set the color of the disks */
            //gfx.setColor(Color.MAGENTA);
            /* draw the specified number of disks */
            while (diskNumber < numberOfDisks){
                /* reduce the y position */
                y = startY - diskNumber * CELL_HEIGHT;
                /* draw the disk */
                //gfx.fillRoundRect(x, y, diskWidth, DISK_HEIGHT, arcH, arcW);
                /* create a new instance of disk */
                newDisk = new Disk(x, y, diskWidth);
                /* give the new disk an id */
                this.disks[diskNumber] = newDisk;
                /* add the id to the cell array of poleA */
                this.diskCells[row][col] = diskNumber;
                /* make the disk smaller and center */
                x = x + 8;
                diskWidth = diskWidth - 16;
                /* increase disk number */
                diskNumber++;
                /* move to the next row */
                row++;
            repaint();
         *move the disk from a source pole to the destination pole.
         *this should take the source col and destination col to determine where to draw the
         *disk.  It will also need to know to draw the disk in the first available cell
         *in a col
         *@param source the starting pole of the next move
         *@param destination the end pole of the next move
        public void moveDisk(int src, int dest){
            /* the lines below would not be necessary if I were to pass the Graphics
             *gfx object as a parameter.  I may have to use this option in order
             *to work around the current repainting issue */
            /* get the graphics to the display panel*/
            Graphics gfx = getAnimationArea();
            /* get the id of the disk to be moved */
            int disk = getDiskId(src);
            /* get the to and from rows */
            int sourceRow = getRow(src);
            int destinationRow = getRow(dest);
            /* set the co ordintates of the destination */
            int col = dest * POLE_AREA_WIDTH;
            int x = disks[disk].getStartX() + col;
            int y = startY - (destinationRow * CELL_HEIGHT);
            int width = disks[disk].getDiskWidth();
            disks[disk].setStartX(x);
            disks[disk].setStartY(y);
            disks[disk].setDiskWidth(width);
            //System.out.println("startX " + x);
            //System.out.println("startY " + y);
            //System.out.println("destination row " + destinationRow);
            //System.out.println("disk " + disk);
            //System.out.println("Width " + width);
            diskCells[sourceRow - 1][src] = EMPTY_CELL_VALUE;
            /* set the destination row to the disk id */
            diskCells[destinationRow][dest] = disk;
            drawDisk();
            repaint();
            String output = "";
            //must initialize row to max - 1 and increment 'til = 0
            //since the array position starts at 0
            //this will print the array from the top down
            for (int row = ROW - 1;row >= 0; row--) {
                for (int colm = 0;colm < COLUMNS ; colm++) {
                    output = output + diskCells[row][colm];
                output = output + "\n";
            System.out.println(output);
            System.out.println(newline);
        public void drawDisk(){
            int diskNum = setDiskAmount -1;
            int i = 0;
            Graphics gfx = getAnimationArea();
            gfx.setColor(Color.MAGENTA);
            while(diskNum >= 0){
                //System.out.println("here is the disk IDs " + diskNum);
                //System.out.println("the startY during draw " + disks[diskNum].getStartY());
                gfx.fillRoundRect(disks[diskNum].getStartX(), disks[diskNum].getStartY(), disks[diskNum].getDiskWidth(), DISK_HEIGHT, DISK_ARC_WIDTH, DISK_ARC_HEIGHT);
                diskNum--;
        public void paint(Graphics gfx){
            if(windowState == 0){
                super.paint(gfx);
                setup();
            } else if (windowState == 1){
                super.paint(gfx);
                drawDisk();
         *returns the id of the disk
         *@param col the the designated column
         *@return the disk identification number
        public static int getDiskId(int col){
            int diskIdent = 0;
            /* initialize the row number to max -1, because the array start at 0 */
            int row = MAX_DISKS - 1;
            /* do a cell check while row is greater than 0
             *this is done so that is starts at the top row
             *and moves down
            while (row > EMPTY_CELL_VALUE){
                /* when the first cell that is not -1 is reached get the disk number
                 *that disk will be the smallest in the stack */
                if(diskCells[row][col] != -1){
                    //diskIdent = this.diskCells[row][col];
                    diskIdent =diskCells[row][col];
                    break;
                row--;
            return diskIdent;
         *returns the first available row
         *@param col the designated col
         *@return the first available row number
        public static int getRow(int col){
            int rowNumber = 0;
            /* cycle through the cells until it finds an empty one */
            while (diskCells[rowNumber][col] != -1){
                rowNumber++;
            return rowNumber;
         *calculate the total time it takes for the tower of hanoi game to be
         *solved, given the amount of disk and the amount of time it takes
         *to physically move a disk from one pole to the other.
        public static void totalTime(){
            int timeInSeconds = setPhysicalDelay * intMovesLeft;
            int i = 0;
            int seconds = 0;
            int minute = 0;
            int hour = 0;
            int day = 0;
            int month = 0;
            int year = 0;
            while (i < timeInSeconds){
                if(seconds > 60){
                    minute++;
                    seconds = 0;
                if(minute > 60){
                    hour++;
                    minute = 0;
                if(hour > 24){
                    day++;
                    hour = 0;
                if(day > 30){
                    month++;
                    day = 0;
                if(month > 12){
                    year++;
                    month = 0;
                seconds++;
                i++;
            updateMessageCenter("It would take:" + year + " years " + month + " months " + day +
                    " days " + hour + " hours " + minute + " minutes and " + seconds + " seconds, to move " + setDiskAmount +
                    " disks at " + setPhysicalDelay + " seconds per move");
         *add the message to the diplay window
         *currently this is not necessary, but may be required to
         *dynamically display the contents of message into the text area
         *@param message the message to be added/appended the the text area
        public static void updateMessageCenter(String message){
            /* append text to the message */
            outTextArea.append(message + newline);
            /* ensure the the most recent line is viewable - auto scroll */
            outTextArea.setCaretPosition(outTextArea.getDocument().getLength());
        public class SolveEngine extends Thread {
            /** Creates a new instance of SolveEngine */
            public SolveEngine() {
            public void run(){
                /* start the engine/animation */
                solutionEngine(HanoiFrame.setDiskAmount,0, 2, 1);
                /* calculate and print the total time after the solution is complete */
                HanoiFrame.totalTime();
         *the recursive solution to the Towers of Hanoi problem
         *@param diskAmount the number of disks that need to be moved
         *@param start the identity of the starting column
         *@param end the identity of the ending column
         *@param temp the identity of the temporary column
            public void solutionEngine(int diskAmount,int start, int end, int temp){
                int disks = diskAmount;
                int startPole = start;
                int endPole = end;
                int tempPole = temp;
                try {
                    if ( disks == 1 ) {
                        HanoiFrame.moveNumber++;
                        HanoiFrame.updateMessageCenter("Moving disk from  "+ startPole + " to "+ endPole + " Move #: " + HanoiFrame.moveNumber + " of " + HanoiFrame.intMovesLeft);
                        /* delay the movement of the disk */
                        Thread.sleep(HanoiFrame.setAnimationDelay);
                        /* move the disk */
                        moveDisk(startPole, endPole);
                    } else {
                        solutionEngine( disks - 1, startPole, tempPole, endPole);
                        HanoiFrame.moveNumber++;
                        HanoiFrame.updateMessageCenter("Moving disk from  "+ startPole + " to "+ endPole + " Move #: " + HanoiFrame.moveNumber + " of " + HanoiFrame.intMovesLeft);
                        /* delay the movement of the disk */
                        Thread.sleep(HanoiFrame.setAnimationDelay);
                        moveDisk(startPole, endPole);
                        solutionEngine( disks - 1, tempPole, endPole, startPole);
                } catch (InterruptedException ex) {
                    ex.printStackTrace();
        }

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

  • What component Should I use?, Jpanel doesn't work

    Hi
    I need a program that has a window that can go fullscreen and windowed (I did that with a Jframe in fullscreen mode with a jpnale and a 800x600 Jpanel and destroying them with an object that maneges them), I did it with a jframe that contained a Jpanel, I used a Jpanel to avoid the flickering on the screen but I also need to change the font type and the font size, but the setFont on the Jpanel doesn't change the font (as I have realized and also read here [http://forum.java.sun.com/thread.jspa?forumID=257&threadID=150588] ), so I'm lost, I might have to redo the whole thing, but I just wanted to know what component should I use for a window that is going to have custom graphics and need diffrent fonts and diffrent font sizes and work in fullscreen without flickering
    Thank you for your attention, I would aprecciate any help given

    for example:
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.Font;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.RenderingHints;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JSlider;
    import javax.swing.event.ChangeEvent;
    import javax.swing.event.ChangeListener;
    public class JPanelFont extends JPanel
      private Font font = getFont();
      private String myString = "Fubars Rule";
      private int fontSize = font.getSize();
      private JSlider slider = new JSlider(0, 100, fontSize);
      public JPanelFont()
        setPreferredSize(new Dimension(620, 250));
        setLayout(new BorderLayout());
        JPanel inputPanel = createInputPanel();
        add(inputPanel, BorderLayout.SOUTH);
      private JPanel createInputPanel()
        JPanel ip = new JPanel();
        slider.setMajorTickSpacing(20);
        slider.setMinorTickSpacing(5);
        slider.setPaintTicks(true);
        slider.setPaintLabels(true);
        ip.add(slider);
        slider.addChangeListener(new ChangeListener()
          public void stateChanged(ChangeEvent evt)
            fontSize = (Integer)slider.getValue();
            repaint();
        return ip;
      @Override
      protected void paintComponent(Graphics g)
        Graphics2D g2 = (Graphics2D)g;
        Object originalHint = g2.getRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING);
        g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        super.paintComponent(g2);
        myPaint(g2);
        g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, originalHint);
      private void myPaint(Graphics2D g2)
        font = font.deriveFont(Font.BOLD, fontSize);
        g2.setFont(font);
        g2.drawString(myString, 20, 100);
      private static void createAndShowUI()
        JFrame frame = new JFrame("Dynamic JPanel Font");
        frame.getContentPane().add(new JPanelFont());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
      public static void main(String[] args)
        java.awt.EventQueue.invokeLater(new Runnable()
          public void run()
            createAndShowUI();
    }Edited by: Encephalopathic on May 21, 2008 9:18 PM

  • Bug: IconUIResource doesn't paint an animated ImageIcon

    I was recently playing with Icons and found that javax.swing.plaf.IconUIResource doesn't paint an ImageIcon that contains an animated GIF. Found the reason in these bug fixes.
    [http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4215118]
    [http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4215118]
    From that, I could arrive at a workaround: extend ImageIcon to implement the UIResource marker interface and use this class instead of wrapping an ImageIcon in a IconUIResource. Interestingly, NetBeans autocomplete revealed the existance of sun.swing.ImageIconUIResource which I determined to be a direct subclass of ImageIcon, with two constructors that take an Image and byte[] respectively.
    Test SSCCE: import java.io.ByteArrayOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.net.MalformedURLException;
    import java.net.URL;
    import javax.swing.Icon;
    import javax.swing.ImageIcon;
    import javax.swing.JOptionPane;
    import javax.swing.UIManager;
    import javax.swing.plaf.IconUIResource;
    import javax.swing.plaf.UIResource;
    public class IconUIResourceBug {
      public static void main(String[] args) {
        try {
          URL imageURL = new URL("http://www.smiley-faces.org/smiley-faces/smiley-face-rabbit.gif");
          InputStream is = imageURL.openStream();
          ByteArrayOutputStream baos = new ByteArrayOutputStream();
          int n;
          byte[] data = new byte[1024];
          while ((n = is.read(data, 0, data.length)) != -1) {
            baos.write(data, 0, n);
          baos.flush();
          byte[] bytes = baos.toByteArray();
          ImageIcon imageIcon = new ImageIcon(bytes);
          Icon icon = new IconUIResource(imageIcon);
          UIManager.put("OptionPane.errorIcon", icon);
          JOptionPane.showMessageDialog(null, "javax.swing.plaf.IconUIResource", "Icon not shown",
                  JOptionPane.ERROR_MESSAGE);
          icon = new ImageIconUIResource(bytes);
          UIManager.put("OptionPane.errorIcon", icon);
          JOptionPane.showMessageDialog(null, "ImageIconUIResource", "Icon shown",
                  JOptionPane.ERROR_MESSAGE);
          icon = new sun.swing.ImageIconUIResource(bytes);
          UIManager.put("OptionPane.errorIcon", icon);
          JOptionPane.showMessageDialog(null, "sun.swing.ImageIconUIResource", "Icon shown",
                  JOptionPane.ERROR_MESSAGE);
        } catch (MalformedURLException ex) {
          ex.printStackTrace();
        } catch (IOException ex) {
          ex.printStackTrace();
    class ImageIconUIResource extends ImageIcon implements UIResource {
      public ImageIconUIResource(byte[] bytes) {
        super(bytes);
    }I can't see any alternative fix for the one carried out in response to the quoted bug reports, so have held off on making a bug report. Any ideas?
    Thanks for reading, Darryl
    I'm also posting this to JavaRanch for wider discussion, and shall post the link here as soon as possible. I'll also keep both threads updated with all significant suggestions received.
    edit [http://www.coderanch.com/t/498351/GUI/java/Bug-IconUIResource-doesn-paint-animated]
    Edited by: DarrylBurke

    Animated gif is working fine for me.
    You can check the delay time between the images in the gif, to see that it's not too short.
    Here's a simple example:import java.net.URL;
    import javax.imageio.ImageIO;
    import javax.imageio.stream.ImageInputStream;
    import javax.swing.ImageIcon;
    import javax.swing.JDialog;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import com.sun.imageio.plugins.gif.GIFImageMetadata;
    import com.sun.imageio.plugins.gif.GIFImageReader;
    public class AnimatedGifTest {
        public static void main(String[] args) {
            try {
                JFrame frame = new JFrame();
                frame.setDefaultCloseOperation(JDialog.EXIT_ON_CLOSE);
                URL url = new URL("http://www.gifanimations.com/action/SaveImage?path=/Image/Animations/Cartoons/~TS1176984655857/Bart_Simpson_2.gif");
                frame.add(new JLabel(new ImageIcon(url)));
                frame.pack();
                frame.setVisible(true);
                // Read the delay time for the first frame in the animated gif
                GIFImageReader reader = (GIFImageReader) ImageIO.getImageReadersByFormatName("GIF").next();
                ImageInputStream iis = ImageIO.createImageInputStream(url.openStream());
                reader.setInput(iis);
                GIFImageMetadata md = (GIFImageMetadata) reader.getImageMetadata(0);           
                System.out.println("Time Delay = " + md.delayTime);
                reader.dispose();
                iis.close();
            } catch (Exception e) {e.printStackTrace();}
    }

  • How can i call the public void paint(Graphics g) method on click of button?

    Hello,
    I have done this before i know its got to do something with the repaint() method but can someone show me with and example and call the paint method using AWT in a frame not in an applet....
    Thank you very much.

    Thank You very Much.... You have cleared all my doubts.
    But my main objective is to display an image in an AWT Frame !!
    here is the code that i have been trying..
    import java.awt.*;
    import java.awt.event.*;
    public class check6 extends Panel
         Frame f;
         Image i;
         public check6()
              f = new Frame("Heading");
              f.addWindowListener(new WindowAdapter(){
                   public void windowClosing(WindowEvent e){
                        System.exit(0);
              final Button b1 = new Button("Submit");
              b1.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e){
                        repaint();
              i = getImage(getCodeBase(), "titanic.jpg");
              add(b1);
              setLayout(new FlowLayout(FlowLayout.LEFT));
              f.add(this);
              f.setSize(500,500);
              f.setVisible(true);
         public void paint(Graphics g)
              g.drawImage(i,10,10,this);
         public static void main(String args[])
              new check6();
    }

  • (How) can I turn off dithering in paint(Graphics g)?

    Is there a way to turn on/off dithering?

    public void paint(Graphics g) {
       Graphics2D g2 = (Graphics2D)g;
       g2.setRenderingHint(RenderingHints.KEY_DITHERING,
          RenderingHints.VALUE_DITHER_DISABLE);
    }VALUE_DITHER_DEFAULT or VALUE_DITHER_ENABLE

  • Why paint(Graphics) is invoked?

    I see paint (Graphics g) method in many awt.* codes. In most cases the method is not explicitly called in, anyhow it invokes. In the code below - main() calls constructor Why_Paint() which has no reference to paint(Graphics g)?
    import java.awt.*;
    import java.awt.event.*;
    class Why_Paint extends Frame
         Why_Paint()
              setTitle("Why paint() is invoked? ");
              setSize(270, 160);
              setBackground(Color.cyan);
              addWindowListener(new WindowAdapter()
                   public void windowClosing(WindowEvent e)
                        System.exit(0);
              setVisible (true);
         public void paint (Graphics g)
             g.setColor(Color.pink);
              g.fillRect(45, 40, 180, 90);     
         public static void main (String args[])
              new Why_Paint();
    }

    Thanx for your response.
    Thus the automatic paint() method invocation is the cause of blinking screen in many java programs?
    I couldn't find any hints/tutorials of customizing automatic invocations (I guess many other methods are called automaticly - main() or init() for example) in my JavaDocs. Can anybody give me an idea of where to look for a link?

  • AWT/Swing difference Component.paint(Graphics g)

    In the following code, I try to paint some component into a VolatileImage, also tried with BufferedImage, and draw the Image on some other component. Anyways it works with java.awt.Panel doesn't with JPanel, does anyone have a clue why?
    Differences between Graphics and Graphics2D maybe?
    package sqltest;
    import java.awt.*;
    import java.awt.image.*;
    import javax.swing.*;
    public class AWTVC extends java.awt.Panel {
        public AWTVC(Component c) {
            this.c = c;
            //initComponents();
            Thread t = new Thread(){
                public void run(){
                    try{
                    Thread.sleep(2000);
                    bu=createVolatileImage(500,500);
                    while(true){
                        AWTVC.this.c.paint(bu.createGraphics());
                        getComponent(0).paint(bu.createGraphics());
                        AWTVC.this.repaint();
                        Thread.sleep(80);
                    }catch(Exception e){
                        e.printStackTrace();
            t.start();
            initComponents();
        private void initComponents() {
            setLayout(new java.awt.BorderLayout());
            addComponentListener(new java.awt.event.ComponentAdapter() {
                public void componentResized(java.awt.event.ComponentEvent evt) {
                    formComponentResized(evt);
        private void formComponentResized(java.awt.event.ComponentEvent evt) {
            bu=createVolatileImage(getWidth(), getHeight());
        final Component c;
        VolatileImage bu=null;
        public void update(Graphics g){
            g.drawImage(bu,0,0,getWidth(),getHeight(),null);
    }Any help would be greatly appreciated!
    Cheers

    Well thanx alot,
    Well I just asked out of curiosity, it works perfectly with the LIGHTWEIGHT_RENDERER, I was just curious to know why AWT components won't draw into Graphics2D (That seemed to be the problem). Well It works now so it doesn't really matter. Well I think the HeavyWeight Renderer is hardware accelerated, maybe that's the reason. Also since I'm using jdk 1.5 do you think setting the -Dsun.java2d.opengl=true property will improve performance. I have cpu cycles to spare, so I can't see the difference ;-)

  • Who knows why a JPanel is automatically painted twice? Please look at my co

    // "Raw Problem": Start this as Application or in Appletviewer
    // <applet code= ZaehlePaintAufrufe width=400 height=250>
    // </applet>
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    class Zeichnung extends JPanel
    private int calls = 0;
    public void paintComponent(Graphics g)
    super.paintComponent(g);
    calls++;
    int breite = getWidth();
    int hoehe = getHeight();
    g.drawString("Width: " + breite + " Height: " + hoehe + " Resize Me!", breite/4, hoehe/2);
    g.drawString("Paint-Calls: " + calls, breite/4, hoehe/2+30);
    public class ZaehlePaintAufrufe extends JApplet
    Zeichnung z = new Zeichnung();
    public void init()
    Container cp = getContentPane();
    cp.add(z);
    public static void main(String[] args)
    JApplet applet = new ZaehlePaintAufrufe();
    JFrame frame = new JFrame("ZaehlePaintAufrufe");
    frame.addWindowListener(new WindowAdapter()
    { public void windowClosing(WindowEvent e) {  System.exit(0);  } } );
    frame.getContentPane().add(applet);
    frame.setSize(400,250);
    applet.init();
    applet.start();
    frame.setVisible(true);

    Hello and sorry for that long time passed,
    thank you for your answer!
    If you are still interested at all:
    I found that with 1.4 the "redundant" repainting of the panel's whole contents
    takes place only when diagonally shrinking the application- or browser-window.
    All other cases are drawn just once.
    Frank

  • Custom painting/ graphics in a panel

    Ten Duke Dollars for whoever gives the best high level solution for my problem.
    I'm writing a small application that displays music notation on screen and lets the user move the notes vertically to the desired locations on the staves. The user can then do various kinds of analysis on each example. The analysis stuff is done, but I'm having trouble finding an approach that will work for the graphics.
    My basic approach so far is to subclass JPanel and use it to handle all the custom painting. I'm planning to add all needed JPEG's to JLabels. Some of the images (e.g. treble and bass clef images) will always be in a fixed location, while others (note images) will move vertically when the user drags them. For the lines on the staves and the measure lines, I'm planning to use g.drawLine.
    The following questions occur to me:
    1. How will I prevent the note images from hiding the lines? Will I need to make the images transparent GIFs or something? Or can I set some layering property in the JPanel to build up a layered drawing?
    2. to detect mouse events, should I attach mouse listeners to my panel, or to each label that contains a note image? (I considered using Ellipse objects for the note heads and lines for the stems, but this will not give me a high enough quality of image.)
    3. I will probably need to use absolute positioning in the panel class rather than FlowLayout or whatever, but I'm having trouble getting rid of the layout manager. Can you give me a few lines of code to do this?
    4. Is my overall approach correct? Is there a better, easier way to accomplish what I'm trying to do?
    thanks,
    Eric

    >
    The following questions occur to me:
    1. How will I prevent the note images from hiding the
    lines? Will I need to make the images transparent GIFs
    or something? Or can I set some layering property in
    the JPanel to build up a layered drawing?If you are going to use images (probably BufferedImages), their Transparency will probably be BITMASK or TRANSLUSCENT.
    2. to detect mouse events, should I attach mouse
    listeners to my panel, or to each label that contains
    a note image? (I considered using Ellipse objects for
    the note heads and lines for the stems, but this will
    not give me a high enough quality of image.)I don't think using JLabel objects is a good idea. Instead of add labels to a panel, I would define a custom JComponent that did its own painting in paintComponent.
    >
    3. I will probably need to use absolute positioning in
    the panel class rather than FlowLayout or whatever,
    but I'm having trouble getting rid of the layout
    manager. Can you give me a few lines of code to do
    this?If you follow my last comment, your component isn't being used as a container, so this is not relevant.
    >
    4. Is my overall approach correct? Is there a better,
    easier way to accomplish what I'm trying to do?
    thanks,
    EricCheck out forum Java 2D. That's where this topic belongs. You also need to learn the 2D API. Search for some text book references in that forum.
    From the Imipolex G keyboard of...
    Lazlo Jamf

  • DVDStudioPro doesn't show graphic subtitles any more

    My DVD Studio Pro 4.2.2 has shown graphic subtitles (tifs) until kind of recently.
    Even earlier created projects doesn't show them any more.
    What happend. Has anybody else noticed this thing?
    How can I make them visible again?
    I'm on OSX 10.6.8

    There shouldn't be a need to mouse over the tab to see what the title is. The space is wasted otherwise, so why not display the title there whether or not the menu bar is also displayed?
    I attached a picture showing exactly what I'm talking about, excuse the quick ms paint job.

  • How do I paint graphics in a JFrame created by netbeans GUI builder?

    I hope it's ok to ask netbeans questions here. Frustrated with Eclipse I'm trying netbeans. I went through the tutorial for the UI builder and I have no trouble laying out the usual swing widgets like JPanels, JButtons, etc. What I haven't figured out is how to mix ordinary graphics like Graphics.draw() with these components.
    Crude example: 2 JPanels in a JFrame. The one on the left has a JSlider bar. The one on the right has a line or something that gets bigger or smaller according to the slider bar.
    If I weren't using the UI builder I'd create a new class that is an extension of JPanel, and override paintComponent() with my draw commands. If I did that to a JPanel I layed out with the UI builder it would get lumped in with the protected code that's created on the fly and probably erased.
    So how do I mix swing components with ordinary graphics without breaking the netbeans UI builder form?
    Thanks,
    Apchar

    This forum is a Java language forum. The NetBeans site has a mailing list. Nabble forums also has NB forums. The contents of both are crossposted. So, you really should post NB use questions to one of them. Post only Java language questions here.
    You can add custom code to the guarded (blue) code blocks. Open a component's property window and select the code button at the top. This allows you to insert code in numerous locations within the guarded blocks and retain the code.
    You can also click a component's property's ellipsis (...) button to bring up the Property Editor dialog box, then select "Custom Code" from the dropdown list at the top of the dialog.
    Note: the above instructions are for NB 6

Maybe you are looking for

  • Using iPad 2 w/ ios 5.1.1.

    I'm using an iPad 2 with ios 5.1.1. Works great. but I'd like to upgrade to a newer version of ios(7.1.1) to get newer versions of apps. Current version of ios is 8.x but don't want to go that direction due to performance concerns. Can anyone provide

  • Payment terms linkage with Sales order

    Hi experts, Validation required on SO/DO of customer in case of overdue payment exist.   ex - Overdue days limit in customer master is defined as 60 days and if any sales invoice is pending for payment more than 61 days , in that  case , system shoul

  • Urgent Query please give me the solution ASAP

    Hi , i want to know a simple thing,and my question is "How we can retrive data from a database table using BPEL ,e.g emp" if possible plesae tell me the step by step process. Thanks , Prakash

  • Query AD from a UCCX script

    Does anyone know how to query Active Directory from a UCCX script?  Looking to pull the caller's email field from the ANI.

  • My camera has a black screen and I can't see the picture, what's wrong.

    Just went to use the camera and it comes on with a black screen.  How do Ifix something that I am not sure what's wrong.... PLEASE HELP !!!!! This is a brand new gift to me