Is "isOptimizedDrawingEnabled" if false effect to repaint(x,y,w,h)?

i override isOptimizedDrawingEnabled to false, does it efect to repaint(x,y,w,h)?
if isOptimizedDrawingEnabled set true repaint(x,y,w,h) work properly

Returns true if this component tiles its children -- that is, if it can guarantee that the children will not overlap. The repainting system is substantially more efficient in this common case. JComponent subclasses that can't make this guarantee, such as JLayeredPane, should override this method to return false.So painting won't be as efficient as when the children are guaranteed to not overlap, but it will still work correctly.

Similar Messages

  • Call repaint() from any class?

    I have a class where I have put a JButton. When I press the button I want to
    call repaint() to update an Image object on a JPanel in a totally different class.
    Unfortunately the Image object has to reside in the JPanel class and therefore I thought
    I cound call an static method from the class with the JButton. Doesn't work.
    Hence, how do I call repaint() for a JPanel from another class?

    You can try comething like this ... quick and dirty (All caveats apply; use code at your own risk):
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    class BJCan  extends Canvas {
      private int width, height;
      private Color color;
      public BJCan() {
        setBackground(Color.black);
        color = Color.red;
      public void repaintCan(Color c) {
        color = c;
        repaint();
      public void paint(Graphics g) {
        width  = (int) getSize().getWidth();
        height = (int) getSize().getHeight();
        g.setColor(color);
        g.drawRect(10,10,width-20,height-20);
    class BJPaintCan  extends JFrame {
      private int width, height;
      private JPanel bjp;
      private BJCan bjc;
      public BJPaintCan() {
        super("BJPaintCan");
        bjp = new JPanel();
        bjc = new BJCan();
        bjp.add(bjc);
        getContentPane().add(bjp);
        setBounds(50,50,300,300);
        width  = (int) getSize().getWidth();
        height = (int) getSize().getHeight();
        bjc.setSize(width-75, height-75);
        setVisible(true);
      public void repaint(Color c) {
        bjc.repaintCan(c);
    public class BJPaint  extends JFrame {
      private boolean boo;
      private BJPaintCan bjpp;
      public BJPaint() {
        super("BJPaint");
        bjpp = new BJPaintCan();
        JButton hitIt = new JButton("Hit It!");
        hitIt.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent ae) {
            if ( boo ) {
              bjpp.repaint(Color.blue);
              boo = false;
            else {
              bjpp.repaint(Color.yellow);
              boo = true;
        JPanel jp = new JPanel();
        jp.setLayout(new FlowLayout(FlowLayout.CENTER));
        jp.add(hitIt);
        getContentPane().add(jp);
        setBounds(375,255,300,200);
        setVisible(true);
      public static void main(String[] argv) {
        new BJPaint();
    }~Bill

  • How to change the co-ordinayte system?

    Hello to all,
    I am working on a java project in which i want to display Earth's longitudes and latitudes. Right now my program giving me cartesian means the applet's own co-ordinate but i want the co-ordinates in degrees to solve some communication equations .
    please help me to solve this problem.
    I will be very thankfull to you all...
    My code is given as:
    import java.awt.*;
    import java.applet.*;
    import javax.swing.JApplet;
    import javax.swing.JPanel;
    import java.awt.event.*;
    public class DrawEarth extends JApplet implements MouseListener
         public void mouseClicked (MouseEvent me) {
              xpos = me.getX();
                ypos = me.getY();
                // Check if the click was inside the Earth area.
                if ((xpos >50 && xpos < 450 && ypos >50 &&  ypos < 450)||(xpos >450 && xpos < 850 && ypos >50 &&  ypos < 450)) {
                     mouseClicked = true;
                // if it was not then mouseClicked is false;
                else
                     return ;
                repaint();
          public void mouseEntered (MouseEvent me) {}
          public void mousePressed (MouseEvent me) {}
          public void mouseReleased (MouseEvent me) {} 
          public void mouseExited (MouseEvent me) {}
         boolean mouseClicked;
         int  xpos,ypos;
         String msg;
        public void init() {
             //addMouseListener(this);
             super.init();
             addMouseListener(this);
            setContentPane(new JPanel() {
                final Dimension size = new Dimension(1000, 1000);
                final GradientPaint backgradient = new GradientPaint(0, 0, Color.WHITE, 0, 350, Color.BLACK);
                final GradientPaint earthgradient = new GradientPaint(0, 50, Color.CYAN, 0, 450, Color.GREEN);
                protected void paintComponent(Graphics g) {
                    super.paintComponent(g);
                    Graphics2D g2 = (Graphics2D) g;
                    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                    g2.setPaint(backgradient);
                    g2.fillRect(0, 0, 1000, 1000);
                    g2.setPaint(backgradient);
                    g2.setPaint(earthgradient);
                    g2.fillOval(50, 50, 400, 400);
                    g2.fillOval(450, 50, 400, 400);
                    g2.setColor(Color.BLUE);
                    g2.setColor(Color.BLUE);
                    g.drawString("270",35,250);
                    g.drawString("300",70,250);
                    g.drawString("330",145,250);
                      g.drawString("(0,0)",245,250);
                      g.drawString("30",345,250);
                      g.drawString("60",415,250);
                      g.drawString("90",445,250);
                      g.drawString("120",470,250);
                      g.drawString("150",545,250);
                         g.drawString("(180,0)",645,250);
                         g.drawString("210",745,250);
                         g.drawString("240",815,250);
                         g.drawString("270",850,250);
                         g.drawString("90",255,48);
                         g.drawString("60",255,77);
                         g.drawString("30",255,150);
                         g.drawString("-30",255,350);
                         g.drawString("-60",255,425);
                         g.drawString("-90",255,460);
                         g.drawString("90",650,48);
                         g.drawString("60",650,77);
                         g.drawString("30",650,150);
                         g.drawString("-30",650,350);
                         g.drawString("-60",650,425);
                         g.drawString("-90",650,460);
                    for (int i = 0; i <= 180; i += 10) {
                        int widthlong = (int) (200 * Math.cos(Math.toRadians(i)));
                        g2.drawOval(250 - widthlong, 50, 2 * widthlong, 400);
                        g2.drawOval(650 - widthlong, 50, 2 * widthlong, 400);
                        int widthlat = (int) (200 * Math.sin(Math.toRadians(i)));
                        g2.drawLine(250 - widthlat, 250 - widthlong, 250 + widthlat, 250 - widthlong);
                        g2.drawLine(650 - widthlat, 250 - widthlong, 650 + widthlat, 250 - widthlong);
                    double xco = xpos/22.22;
                    double yco = ypos/22.22;
                        if(xpos >50 && xpos < 450 && ypos >50 && ypos < 250){
                             g.drawString("("+xpos+","+ypos+")",xpos,ypos);
                        if(xpos >450 && xpos < 850 && ypos >50 && ypos < 250){
                             g.drawString("("+xpos+","+ypos+")",xpos,ypos);
                        if(xpos >50 && xpos < 450 && ypos >250 && ypos < 450){
                             g.drawString("("+xpos+","+ypos+")",xpos,ypos);
                        if(xpos >450 && xpos < 850 && ypos >250 && ypos < 450){
                             g.drawString("("+xpos+","+ypos+")",xpos,ypos);
                        if((xpos==250&&ypos==50)  || (xpos== 650 && ypos==450 )){
                             g.drawString("("+xpos+","+ypos+")",xpos,ypos);
                        if(xpos >=50 && xpos <= 850 && ypos ==250 ){
                             g.drawString("("+xpos+","+ypos+")",xpos,ypos);
               /* public Dimension getPreferredSize()
                    return size;
       

    =)
    For the boundaries of the globe you can test if the click was outside the globes by comparing the radius and the calculated distance from the center of each globe for each globe separately. The transform of the drawing the OP made is not a standard one so I'm having to comprehend the calculus of transformations I picked up last year and combine it with the linear algebra I learned this year ( might take until next week =( ). I tried implementing it by using weighted average procedures
    i.e.
    >
    delta = ( 1 - t )*P + tQ>
    where t is time in fraction of the total time and P and Q are two different points on a line. But there is also the effect of moving away from the equator for the longitude where the effect on the rate of change is increased when moving sideways ( longitude measures degrees around the earth from the prime meridian ) and when I tried to implement those two effects together, they seem to work for some parts but fail as I go diagonally (simply put) from 0deg,0deg which give false results in that the lat or lon (can remember which) is greater than the possible amount allowed ( i.e. abs_value > 180 for longitude or > 90 for latitude ).
    Here's the code so far if you want to take a look at it:
    I wasn't trying to worried too much about anything else but the algorithm for transforming the coords. I added the JLabel on the north side so I wouldn't have to look at the command prompt.
    import java.awt.Dimension;
    import javax.swing.JPanel;
    import javax.swing.JFrame;
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.GradientPaint;
    import java.awt.RenderingHints;
    import java.awt.Point;
    import java.awt.event.MouseListener;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.awt.BorderLayout;
    import javax.swing.JLabel;
    public class DrawEarthPanel extends JPanel
         public static final long serialVersionUID = 1L;
         private static final Dimension size = new Dimension(900, 500); // width, height
         private static final GradientPaint backgradient = new GradientPaint(0, 0, Color.WHITE, 0, 350, Color.BLACK);
         private static final GradientPaint earthgradient = new GradientPaint(0, 50, Color.CYAN, 0, 450, Color.GREEN);
         private boolean mouseClicked;
         private int xpos = 0;
         private int ypos = 0;
         public DrawEarthPanel()
              addMouseListener( new MouseEvents() );
         public Dimension getPreferredSize()
              return DrawEarthPanel.size;
         public void paintComponent( Graphics g )
              super.paintComponent(g);
              Graphics2D g2 = (Graphics2D) g;
              g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
              g2.setPaint(backgradient);
              g2.fillRect(0, 0, 1000, 1000);
              g2.setPaint(earthgradient);
              g2.fillOval(50, 50, 400, 400);
              g2.fillOval(450, 50, 400, 400);
              g2.setColor(Color.BLUE);
              g.drawString("270",35,250);
              g.drawString("300",70,250);
              g.drawString("330",145,250);
              g.drawString("(0,0)",245,250);
              g.drawString("30",345,250);
              g.drawString("60",415,250);
              g.drawString("90",445,250);
              g.drawString("120",470,250);
              g.drawString("150",545,250);
              g.drawString("(180,0)",645,250);
              g.drawString("210",745,250);
              g.drawString("240",815,250);
              g.drawString("270",850,250);
              labelLatitudes( g, 255 );
              labelLatitudes( g, 650 );
              for ( int i=0; i<=180; i+=10 )
                   int wLon = (int) (200 * Math.cos(Math.toRadians(i)));
                   g2.drawOval(250-wLon, 50, 2*wLon, 400);
                   g2.drawOval(650-wLon, 50, 2*wLon, 400);
                   int wLat = (int) (200 * Math.sin(Math.toRadians(i)));
                   g2.drawLine(250-wLat, 250-wLon, 250+wLat, 250-wLon);
                   g2.drawLine(650-wLat, 250-wLon, 650+wLat, 250-wLon);
         private static final Point left_globe_origin = new Point( 250, 250 );
         private static final Point right_globe_origin = new Point( 650, 250 );
         private static final int globe_radius = 200;
         private void labelLatitudes(Graphics g, int x)
              g.drawString("90",x,48);
              g.drawString("60",x,77);
              g.drawString("30",x,150);
              g.drawString("-30",x,350);
              g.drawString("-60",x,425);
              g.drawString("-90",x,460);
         class MouseEvents extends MouseAdapter implements MouseListener
              public void mouseClicked( MouseEvent evt )
                   xpos = evt.getX();
                   ypos = evt.getY();
                   System.err.println("DEBUG: xpos="+xpos+", ypos="+ypos);
                   double lat = 0.0;
                   double lon = 0.0;
                   if ( xpos>50 && xpos<450 && distance(left_globe_origin,xpos,ypos) <= globe_radius ) // left globe
                        Point origin = left_globe_origin;
                        double radius = globe_radius;
                        double dx = xpos-origin.x;
                        double dy = -ypos+origin.y;
                        lat = (dy/(radius-dx))*90;
                        lon = (dx/(radius-dy))*90;
                   //     lat = ypos - 250;
                   //     lon = xpos - 250;
                        setLabel( String.format( "longitude >>> %.3f, latitude >> %.3f", lon, lat ) );
                        System.err.println( "DEBUG: lat=" + lat + ", lon=" + lon );
                   else if ( xpos>450 && xpos<850 && distance( right_globe_origin,xpos,ypos) <= globe_radius ) // right globe
                        Point origin = right_globe_origin;
                        int radius = globe_radius;
                        int dx = xpos-origin.x;
                        int dy = ypos-origin.y;
                        lat = (1d*dx/radius+1d*dy/radius)*90;
                        lon = (1d*dx/radius+1d*dy/radius)*90;
                   //     lat = ypos - 250;
                   //     lon = xpos - 650;
                        setLabel( String.format( "longitude >>> %3.3f, latitude >> %3.3f", lon, lat ) );
                        System.err.println( "DEBUG: lat=" + lat + ", lon=" + lon );
                   repaint();
         private static JLabel output = new JLabel( "Output of Longitude and Latitude" );
         public static void setLabel( String text )
              output.setText( text );
         public static double distance( Point origin, int x, int y )
              return Math.pow( Math.pow((x-origin.x),2)+Math.pow((y-origin.y),2), 0.5 );
         private static void createAndShowGUI()
              JFrame frame = new JFrame( "DrawEarthPanel" );
              frame.setLayout( new BorderLayout() );
              frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
              frame.setLocation(10, 10);
              frame.setContentPane(new DrawEarthPanel());
              frame.add( output, BorderLayout.NORTH );
              frame.pack();
              frame.setVisible(true);
         public static void main( String[] args )
              javax.swing.SwingUtilities.invokeLater(
                   new Runnable()
                        public void run()
                             createAndShowGUI();
    }The transform isn't a regular one since the OP kept his lat. lines straight so it's kind of weird to me right now.
    Happy coding

  • Trouble with threads and awt

    Hello everyone I have some code that I'll like to thread, I'll like to draw two lines that prints alternatively one after the other in a blinking effect usig thrreads but the code is not functioning the way I'll like it too, please can someone take a look at it for me?
    import java.applet.*;
    import java.awt.*;
    public class ArgueRunnable extends Applet implements Runnable{
      Thread myThread;
        int width, height;
    boolean running= true;
       public void init() {
          width = getSize().width;
          height = getSize().height;
          setBackground(Color.white);
          myThread = new Thread(this);
          myThread.start();
      public void run() {
        try {
          for(;;) {
            repaint();
            myThread.sleep(33);
            repaint();
        catch (InterruptedException e) {
          return;
    public void paint(Graphics g){
      update1(g);
      update2(g);
    public void update1( Graphics g ) {
           g.drawLine(0, 15, 200, 15);
    public void update2( Graphics g ) {
           g.drawLine(100, 15, 200, 15);
       

    Hello again, thanks for sending the code, however there were a couple syntax errors, which was easy to fix, but the code still did not work the way I expected I'm still not getting the blinking effect I'm trying to accomplish, can you look at it again for me?{import java.applet.*;
    import java.awt.*;
    public class ArgueRunnable2 extends Applet implements Runnable{
           Thread myThread;
             int width, height;
         boolean running= true;
         boolean up1 = true;
         int x=200;
         int y=200;
       public void init() {
          width = getSize().width;
          height = getSize().height;
          setBackground(Color.white);
          myThread = new Thread(this);
          myThread.start();
      public void run() {
            while (true)
              try {
                   myThread.sleep(500);
              catch(Exception e){
              if (up1==true){
                   up1=false;
                   if(up1==false){
                   up1=true;
              repaint();
         public void paint(Graphics g){
              if (up1 == true){
                     update1(g);
                   x=0;
                   y=200;
              else{
                   update2(g);
                   x=200;
                   y=0;
    public void update1( Graphics g ) {
         g.setColor(Color.red);
           g.drawLine(0, 15,y, 15);
    public void update2( Graphics g ) {
         g.setColor(Color.blue);
           g.drawLine(100, 15, x, 15);

  • Avoid resize of JList with setFixedCellWidth

    I have functionality in my application such that when I select an item in one list, information that is associated with the item appears in a second list. I notice however that the width of this second list box is changing according to the contents of the list. The result is that each time I select an item in the first list, the second list changes size.
    I have tried using two methods, setFixedCellWidth(int value) and setPrototypeCellValue(" ") to control this behaviour. But the consequence is that although the second list does not change size, it also does not update with the information that is associated with the selected item in the first list.
    So my question is how do these methods effect the repaint and revalidation of the panel when the listmodel of the list is updated?
    Thanks so much.

    Excuse dupe post if there is one. You have other problems if you are not seeing updates in second list when using setProto. . . method. See Below:
    public class ListTest extends JFrame {
        Label label;
        DefaultListModel model;
        DefaultListModel targetModel;
        JList testList;
        JList targetList;
        public static void main( String[] args){
            new ListTest();
        public ListTest(){
            //super("Closing Test");
            getContentPane().setLayout(new BorderLayout());
            model = new DefaultListModel();
            for (int i = 0 ; i < 10 ;i++){
                model.addElement("test "+i);
            testList = new JList(model);
            testList.setDragEnabled(true);
            testList.setPrototypeCellValue("                                 ");
            testList.setTransferHandler(new ListTransferHandler());
            targetModel = new DefaultListModel();
            targetModel.addElement("test 6");
            testList.addListSelectionListener(new ListSelectionListener(){
                public void valueChanged(ListSelectionEvent lse){
                    System.out.println(((String)testList.getSelectedValue()));
             JPanel centerPanel = new JPanel(new GridLayout(0,2,5,5));
            targetList = new JList(targetModel);
            targetList.setPrototypeCellValue("                                 ");
            targetList.setDragEnabled(true);
            targetList.setTransferHandler(new ListTransferHandler());
            JScrollPane targetJsp = new JScrollPane(targetList);
            JScrollPane jsp = new JScrollPane(testList);
            centerPanel.add(jsp);
            centerPanel.add(targetJsp);
            getContentPane().add(centerPanel);
            //setSize(200,300);
            addWindowListener(new WindowAdapter(){
                public void windowClosing(WindowEvent we){
                    setVisible(false);
                    dispose();
                    System.exit(0);
            JPanel buttonPanel = new JPanel();
            JButton addButton = new JButton("add");
            addButton.addActionListener(new ActionListener(){
                public void actionPerformed(ActionEvent e){
                    Object[] selections = testList.getSelectedValues();
                    for (int counter = 0 ; counter < selections.length; counter++){
                        String tester = (String)selections[counter];
                        targetModel.addElement(selections[counter]);
            JButton subButton = new JButton("subtract");
            subButton.addActionListener(new ActionListener(){
                public void actionPerformed(ActionEvent e){
                    if ( targetList.getSelectedIndex() >= 0){
                        targetModel.removeElementAt(targetList.getSelectedIndex());
            buttonPanel.add(addButton);
            buttonPanel.add(subButton);
            getContentPane().add(buttonPanel, BorderLayout.SOUTH);
                    setVisible(true);
            pack();
    }Cheers
    DB

  • Convert applet to swing

    Hi;
    Could anyone help me to convert my example code from applet to swing,please, thank
    import java.awt.*;
    import java.applet.*;
    import java.lang.Math;
    import java.awt.Font;
    import java.lang.Integer;
    /*** Main class == Applet  ***/
    public class Suffix extends Applet implements Runnable {
       private Thread main;
       public s_tree _tree=null;
       public node nd=null;
       public boolean userPause=false,resumed=false;
       private String str[]={"GOOGOL$","Paused","Resumed","Compacting","Done"};
       public Color bl=Color.blue,rd=Color.red;
       public Font fnt;
       public int mode=3,delay=3000;
       private char alph[]={'$','Q','W','E','R','T','Y','U','I','O',
                        'P','A','S','D','F','G','H','J','K','L',
                        'Z','X','C','V','B','N','M'};
    /*** initialisation function. It is the first Funct to be called ***/
       public void init() {
    // Temp data
          int temp=0,nxx=30;
    // Ini. of fnt , the font size + style used by this applet.
          fnt=new Font("Denis",1,25);
    /*** parsing command parameters ***/
    //      try {
    //DELAY VALUE PARAM
             String param=getParameter("DELAY");
             if (param!=null) {
                temp=Integer.parseInt(param);
                if ((temp>500)&&(temp<6000)) delay=temp;
    //x LEFTMOST coordinate
             param=getParameter("X");
             if (param!=null) {
                temp=Integer.parseInt(param);
                nxx=temp;
    //Base String parameter
             param=getParameter("STRING");
             if ((param!=null)&&(param.length()<15)) {
                str[0]=param;
    //      } catch (ParseException e) { showParseError(e); }
    // Allocating mem for _tree + initialize it .
          _tree=new s_tree(str[0],fnt);
    // Override xx (left_bound) by the caller's or the default value
          _tree.xx=nxx;
    /*** "animation loop is controled here" ***/
       public void run() {
         while(true) {
             try {
    //delay the process for time==delay
                Thread.sleep(delay);
             } catch (InterruptedException e) {}
    //controls animation loop
          repaint();
    /*** override APPLET's paint function ***/
       public void paint (Graphics g) {
    //Output graphics
          update(g);
    /*** Updates the graphics ***/
       public void update (Graphics g) {
    // Set font
          if (g.getFont()!=fnt) g.setFont(fnt);
          if ((userPause==false)&&(resumed==false)) // Is the applet paused ?
             g.clearRect(0,0,1024,768); //clears the screen
             if (_tree==null) {     // if tree is not initialised
                init();
                //_tree.show(g);
             } else {
                if (mode==3) {      // if graphics output mode is 3
                   if (nd!=null) nd._to_rd(false);
                   nd=_tree.step_compact(nd);  //compacts the tree one step further
                   if (nd==null)  // if tree is totally compacted ...
                      mode=4;   //change the ani. mode to 4 (don't call compact)
                   else
                      nd._to_rd(true);  //colors the next node to compact in red
    // Draw the "titleviewport's" comment
             g.setColor(bl);
             g.drawString(str[mode],10,15);
             _tree.show(g);     //show tree
          } else {
             g.clearRect(0,0,200,25);  //clears the "titleviewport to update it"
             g.setColor(rd);
             if (resumed==true){
                resumed=false;
                g.drawString(str[2],10,15);
             else g.drawString(str[1],10,15);
    /*** restart the animation process ***/
       public void start() {
          main=new Thread(this);
          main.start();
    /*** stops the animation ***/
       public void stop() {
          main.stop();
          main=null;
    /*** Handles the user's events (mouse , kbd , ... ***/
       public boolean handleEvent(Event evt) {
          if (evt.id==Event.MOUSE_DOWN) { //if mouse button have been pushed ...
                if (main!=null && main.isAlive()) {
                   if (userPause) {
                      main.start();
                      resumed=true;
                   } else {
                      main.stop();
                   userPause= !userPause;
                } else {
                   main= new Thread(this);
                   main.start();
                   userPause=false;
                   resumed=true;
                repaint();
             return true;
          } else {
             return super.handleEvent(evt);
    /*** Linked List of node(s) ***/
    class nodelist{
       nodelist next=null;
       node ptr=null;
       public void nodelist(){};
    /*** node of a structure tree ***/
    class node {
    // Relatives
       public nodelist children=null;
       public node parent=null;
    // variables
       public int maxchild=12,childnum=0,level=0;
       public int center[]={0,0};
       public int xlen=20,ylen=10,vspace=15,hspace=8;
       public int x[]={0,0};
       public boolean _ishidden=false;
       private Color bk=Color.black,wh=Color.white,rd=Color.red;
    // Node==red toggle variable
       public boolean to_rd=false;
    // node's text
       public String label=null;
    /*** initialisation of the node ***/
       public node(int nx,int ny,int nxl,int nyl,node nparent,int nlevel,String nstr){
          x[0]=nx; x[1]=ny;
          xlen=nxl; ylen=nyl;
          parent=nparent;
          level=nlevel;
          label=new String(nstr);
          children=new nodelist();
    /*** destroys the node ***/
       public void destruct() {
    // NOTE : not like C++ destructors . Do not confuse .
          delete_subtree();
          children=null;
          parent=null;
          bk=wh=rd=null;
          label=null;
    /*** Node to red toggle switch ***/
       public void _to_rd(boolean b) {to_rd=b;};
    /*** Adds a child to this node ***/
       public void add_child(int nx,int ny,int nxl,int nyl,node nparent,int nlevel,
                                String nstr) {
          if (childnum<maxchild) {    // if 'legal' space left ...
             if (children==null) {    // if no nodelist attached ...
                children=new nodelist(); //init. children
                children.ptr=new node(nx,ny,nxl,nyl,nparent,nlevel,nstr); //create node
                childnum++;
             } else {
                nodelist dummy=children;
    // search for the last nodelist
                while (dummy.next!=null) dummy=dummy.next;
                dummy.next=new nodelist(); //adds a nodelist
                dummy=dummy.next;
                dummy.ptr=new node(nx,ny,nxl,nyl,nparent,nlevel,nstr); //create child
                childnum++;
    // Tree needs to be realigned
    /*** adds a child and returns its address ***/
       public node add_child_ret(int nx,int ny,int nxl,int nyl,node nparent,int nlevel,
                                String nstr) {
          if (childnum<maxchild) {
             if (children==null) {
                children=new nodelist();
                children.ptr=new node(nx,ny,nxl,nyl,nparent,nlevel,nstr);
                childnum++;
                return(children.ptr);
             } else {
                nodelist dummy=children;
    // search for the last child
                while (dummy.next!=null) dummy=dummy.next;
                dummy.next=new nodelist();
                dummy=dummy.next;
                dummy.ptr=new node(nx,ny,nxl,nyl,nparent,nlevel,nstr);
                childnum++;
                return(dummy.ptr);
        return(null);
    // Tree needs to be realigned
    /*** adds the node nchild as a new children ***/
       public void add_child(node nchild) {
          nodelist dummy=null;
          dummy=children;
          if (childnum<maxchild) {
             if (children==null) {
                children=new nodelist();
                children.ptr=nchild;
                childnum++;
             } else {
                while (dummy.next!=null) dummy=dummy.next;
                dummy.next=new nodelist();
                dummy=dummy.next;
                dummy.ptr=nchild;
                childnum++;
    //Tree needs to restructured.
    /*** deletes all childrens ***/
       public void delete_subtree() {
          while (childnum>0 && children!=null) { //while child exists , kill it
             if (children.ptr!=null) {
                children.ptr.destruct();
                children.ptr=null;
                children=children.next;
             } else children=null;
             childnum--;
    /*** moves this node and its children horizontally ***/
       public void move_tree(int nx) {
          nodelist dummy=children;
          x[0]+=nx;
          while (childnum>0 && dummy!=null) {
             if (dummy.ptr!=null) {
                dummy.ptr.move_tree(nx);
                dummy=dummy.next;
    /*** removes the node from the tree (do not preserve order of ordered tree ) ***/
       public void remove_node() {
          nodelist dummy=children;
          while(dummy!=null) {
             if (dummy.ptr!=null){
                parent.add_child(dummy.ptr);
             dummy=dummy.next;
          children=null;
    //could call restructure tree here .
    //don't forget to change the node's levels !!!
    /*** show all nodes ***/
       public void show_all(Graphics g) {
          if (_ishidden==false) { //if not hidden
             if (children!=null) {  //if child exist
                nodelist dummy=children; //temp var.
                while(dummy!=null) { //while there is a child...
                   if (dummy.ptr!=null)
                      dummy.ptr.show_all(g);
                   dummy=dummy.next;
             show_node(g);
    /*** show nodes in preorder ***/
       public int preorder_show(Graphics g,int label){
          if (_ishidden==false) {
             show_node(g/*,label++*/);
             if (children!=null) {
                nodelist dummy=children;
                while(dummy!=null) {
                   if (dummy.ptr!=null) label=dummy.ptr.preorder_show(g,label);
                   dummy=dummy.next;
          return(label);
    /** show nodes in postorder ***/
       public int postorder_show(Graphics g,int label){
          if (_ishidden==false) {
             if (children!=null) {
                nodelist dummy=children;
                while(dummy!=null) {
                   if (dummy.ptr!=null) label=dummy.ptr.postorder_show(g,label);
                   dummy=dummy.next;
             show_node(g/*,label++*/);
          return(label);
    /*** show nodes in inorder ***/
       public int inorder_show(Graphics g,int label){
          if (_ishidden==false) {
             if (children!=null) {
                nodelist dummy=children;
                if (dummy.ptr!=null) label=dummy.ptr.inorder_show(g,label);
                dummy=dummy.next;
                show_node(g/*,label++*/);
                while(dummy!=null) {
                   if (dummy.ptr!=null) label=dummy.ptr.inorder_show(g,label);
                   dummy=dummy.next;
             } else show_node(g/*,label++*/);
          return(label);
    /*** Restructure the coordinates of all nodes ***/
       public int align(int min,Font fnt,int lev,Graphics g){
          int i=min; //left bound
          FontMetrics fntm=g.getFontMetrics(fnt); //used to know the text size
          level=lev;
    // node x and y radius are computed here
          xlen=4+(int)(fntm.stringWidth(label)/2);
          ylen=4+(int)(fntm.getHeight()/2);
          if (children!=null) {      //if child present ...
             nodelist dummy=children;
             while(dummy!=null) {
                if (dummy.ptr!=null) i=dummy.ptr.align(i,fnt,lev+1,g); //align them
                   dummy=dummy.next;
          x[0]=min+(int)((i-min)/2); //could be underflow so will be checked
          x[1]=lev*(vspace+(ylen*2))+26;
    // overflow should happen only when the parent node is larger than its children
          if ((x[0]-xlen)<min) { //check uf underflow occurs.
             move_tree(min+xlen-x[0]+1);
             i=x[0]+xlen+5;
          if (childnum==0) x[0]+=2;
        return(i);
    /*** returns the child following nd ***/
    /*** if nd==null -> return 1st child ***/
    /***  if nd==last children -> return null***/
       public node next_child(node nd) {
          nodelist dummy=null;
          if (children==null) return(null);
          if (nd==null) return(children.ptr);
          dummy=children;
          while (dummy.ptr!=nd) {
             if (dummy.next!=null)
                dummy=dummy.next;
             else
                return(null);
          dummy=dummy.next;
          if (dummy!=null) return(dummy.ptr);
             else return(null);
    /*** returns child with first letter==nh ***/
       public node get_childd(char ch) {
          nodelist dummy=null;
          dummy=children;
          while (dummy!=null) {
             if (dummy.ptr!=null) {
                if (dummy.ptr.label.charAt(0)==ch)
                   return(dummy.ptr);
             dummy=dummy.next;
        return(null);
    /*** returns the nodelist containing nd ***/
       public nodelist get_child(node nd) {
          nodelist dummy=children;
          while (dummy!=null) {
             if (dummy.ptr==nd) return(dummy);
             dummy=dummy.next;
        return(null);
    /*** outputs the node to Screen ***/
       public void show_node(Graphics g) {
          if (_ishidden==false) {
             if (level>0) {  //if it is not a root then draw link-line
                g.setColor(bk);
                g.drawLine(x[0],x[1]-ylen,parent.x[0],parent.x[1]+parent.ylen); //from this node to parent node
             if (to_rd==false)
                g.setColor(wh);
             else
                g.setColor(rd);
             g.fillOval(x[0]-xlen,x[1]-ylen,xlen*2,ylen*2); //draws an oval
             g.setColor(bk);
             g.drawString(label,x[0]-xlen+4,x[1]+ylen-12);  //output the text
    /*** class which uses nodes to create a SUFFIX TREE ***/
    class s_tree {
       node root=null;    // root node.
       String str=null;   // 'search' string
       Font fnt=null;     // font type
       int xx=30;         // left limit for graphics
    /*** initialize a SUFFIX TREE with string==nstr and Font==nfnt ***/
       public s_tree(String nstr,Font nfnt) {
          str=new String(nstr);
          fnt=nfnt;
          create();
    /*** uninitialize the structure **/
       public void destruct() {
          root.destruct();
          str=null;
          fnt=null;
    /*** show the tree ***/
       public void show(Graphics g) {
          root.align(xx,fnt,0,g);   // restructure node's coordinates
          root.show_all(g); //show tree
    /*** creates a tree structure from String=str ***/
       public void create() {
          node dummy=null;
          root=new node(0,0,0,0,dummy,0," "); //create root
          root.parent=null; //just to make sure ...
          for (int i=0;i<str.length();i++) {
    // Create subtree of root in the following way :
    //    create subtree ("ASDF$");
    //        "     "    ("aSDF$");
    //       "    "      ("asDF$"); ...
    // where : the UPPERCASE letters is the part of the string sent to insert_string
             insert_string(str.substring(i));
          //root.align(0,fnt,0); //align root now ?
    /*** creates a subtree of ROOT with String=nstr ***/
       public void insert_string(String nstr) {
          node dummy2=null,dummy=null;
          int i=0;
          dummy=root;
          dummy2=root;
    // As long as a children of dummy2 have the letter nstr[i] , dummy==thischildren
    // It is used to make sure that a node does not have two children with the
    // same letter
          while (dummy2!=null) {
             dummy2=dummy2.get_childd(nstr.charAt(i));
             if (dummy2!=null) {
                i++;
                dummy=dummy2;
    //create the nodes for the rest of the string
          for(;i<nstr.length();i++) {
             if (dummy!=null) dummy=dummy.add_child_ret(0,0,0,0,dummy,1,nstr.substring(i,i+1));
    // Compacts the tree node by node and returns the next node to compact
    // if node==null , compacts the first node ...
    //Works in POST-ORDER
       public node step_compact(node nd) {
          node dummy=nd,dummy2=null;
          nodelist ndlst=null;
    // GOES TO THE LOWER LEFT CHILDREN
          if (nd==null) { //first call !
             dummy=root;
             while(dummy.children!=null) {
                if (dummy.children.ptr==null)
                   dummy.children=dummy.children.next;
                else
                   dummy=dummy.children.ptr;
    //*** tries to find a 'compactable' node ***
    //*** It uses the POST-ORDER method      ***
    // if this node is not the last children then try to find next compactable node
    // in the next children.
          if (dummy.parent.childnum!=1) dummy=next_chain(dummy);
          if (dummy==null) return(null); //fully optimized
    //remove parent node.
    /*** THIS IS WHERE COMPACTING TAKES PLACE  **/
          dummy2=dummy.parent.parent;
          ndlst=dummy2.get_child(dummy.parent);
          if (ndlst==null) return(null); //we've got a beeeeg problem if this happens ...
    //*** merges the parent string with this one and delete parent .
          dummy.label=dummy.parent.label.concat(dummy.label);
          ndlst.ptr=dummy;
          //delete parent .
          dummy.parent=null;
          dummy.parent=dummy2;
    //      root.align(0,fnt,0);
        return(dummy);
    /*** finds the next chain in the tree (i.e. the next compactable node) ***/
       public node next_chain(node nd){
          node dummy=null;
          if (nd.parent==null) return(null); //finished ! This is the root
          if (nd.parent.childnum==1) return(nd); //can be optimized
    // finds the nd.parent's child following nd
          dummy=nd.parent.next_child(nd);
          if (dummy==null)  // if OLD_nd==last child
             return(next_chain(nd.parent));      //tries to find a chain upwards
          else {
                 // OLD_nd was not the last child . nd==OLD_nd's next brother
    // GOES TO THE LOWER LEFT most child of nd's subtree.
             while(dummy.children!=null) {
                if (dummy.children.ptr==null)
                   dummy.children=dummy.children.next;
                else
                   dummy=dummy.children.ptr;
             return(next_chain(dummy)); // returns the next compactable node
    };

    First, show me the rupees! Show me the rupees!

  • How can I get  the part image from a rectangle region?

    hi,
    I'm trying to draw a rectagle region on a picture with mouse and crop it. but the rectangle is not vertical along x-axis.that is to say, there is a angle between x-axis and the base of the rectangle. I don't know , how can I do it. Can someone give me some tip or some java-code. Thank you very much in advance.

    I completely misunderstood your question. As I read it again it seems clear and straight-forward. I'm sorry. Let's see if this is closer.
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.awt.image.BufferedImage;
    import java.io.*;
    import java.net.*;
    import javax.imageio.ImageIO;
    import javax.swing.*;
    import javax.swing.event.MouseInputAdapter;
    public class CropImage
        BufferedImage original;
        CropPanel cropPanel;
        CropSelector selector;
        public CropImage()
            original = getImage();
            cropPanel = new CropPanel(original);
            selector = new CropSelector(cropPanel);
            cropPanel.addMouseListener(selector);
            cropPanel.addMouseMotionListener(selector);
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(getUIPanel(), "North");
            f.getContentPane().add(new JScrollPane(cropPanel));
            f.setSize(400,400);
            f.setLocation(200,200);
            f.setVisible(true);
        private BufferedImage getImage()
            String fileName = "images/coyote.jpg";
            BufferedImage image = null;
            try
                URL url = getClass().getResource(fileName);
                image = ImageIO.read(url);
            catch(MalformedURLException mue)
                System.err.println("url: " + mue.getMessage());
            catch(IOException ioe)
                System.err.println("read: " + ioe.getMessage());
            return image;
        private JPanel getUIPanel()
            final JButton
                mask    = new JButton("mask"),
                crop    = new JButton("crop"),
                restore = new JButton("restore");
            ActionListener l = new ActionListener()
                public void actionPerformed(ActionEvent e)
                    JButton button = (JButton)e.getSource();
                    if(button == mask)
                        selector.mask();
                    if(button == crop)
                        selector.crop();
                    if(button == restore)
                        cropPanel.restore(original);
            mask.addActionListener(l);
            crop.addActionListener(l);
            restore.addActionListener(l);
            JPanel panel = new JPanel();
            panel.add(mask);
            panel.add(crop);
            panel.add(restore);
            return panel;
        public static void main(String[] args)
            new CropImage();
    class CropPanel extends JPanel
        BufferedImage image;
        Dimension size;
        GeneralPath clip;
        Point[] corners;
        Area mask;
        boolean showMask;
        Color bgColor;
        public CropPanel(BufferedImage bi)
            image = bi;
            setSize();
            clip = new GeneralPath();
            showMask = false;
            bgColor = getBackground();
        protected void paintComponent(Graphics g)
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            int w = getWidth();
            int h = getHeight();
            int x = (w - size.width)/2;
            int y = (h - size.height)/2;
            g2.drawImage(image, x, y, this);
            if(showMask)
                g2.setPaint(getBackground());
                g2.fill(mask);
            else
                g2.setPaint(Color.red);
                g2.draw(clip);
        public Dimension getPreferredSize()
            return size;
        public void setClip(Point[] p)
            corners = p;
            clip.reset();
            clip.moveTo(p[0].x, p[0].y);
            clip.lineTo(p[1].x, p[1].y);
            clip.lineTo(p[2].x, p[2].y);
            clip.lineTo(p[3].x, p[3].y);
            clip.closePath();
            repaint();
        public void clearClip()
            clip.reset();
            repaint();
        public void setMask(Area area)
            mask = area;
            showMask = true;
            repaint();
        public void setImage(BufferedImage image)
            this.image = image;
            setSize();
            showMask = false;
            clip.reset();
            repaint();
            revalidate();
        public void restore(BufferedImage image)
            setBackground(bgColor);
            setImage(image);
        private void setSize()
            size = new Dimension(image.getWidth(), image.getHeight());
    class CropSelector extends MouseInputAdapter
        CropPanel cropPanel;
        Point start, end;
        public CropSelector(CropPanel cp)
            cropPanel = cp;
        public void mask()
            Dimension d = cropPanel.getSize();
            Rectangle r = new Rectangle(0, 0, d.width, d.height);
            Area mask = new Area(r);
            Area port = new Area(cropPanel.clip);
            mask.subtract(port);
            cropPanel.setMask(mask);
        public void crop()
            Point[] p = cropPanel.corners;
            int w = p[2].x - p[0].x;
            int h = p[1].y - p[3].y;
            BufferedImage cropped = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
            Graphics2D g2 = cropped.createGraphics();
            g2.translate(-p[0].x, -p[3].y);
            cropPanel.paint(g2);
            g2.dispose();
            cropPanel.setBackground(Color.pink);
            cropPanel.setImage(cropped);
        public void mousePressed(MouseEvent e)
            if(e.getClickCount() == 2)
                cropPanel.clearClip();
            start = e.getPoint();
        public void mouseDragged(MouseEvent e)
            end = e.getPoint();
            // locate high and low points of rectangle from start
            int dy = end.y - start.y;
            int dx = end.x - start.x;
            double theta = Math.atan2(dy, dx);
            double spoke = start.distance(end)/2;
            double side = Math.sqrt(spoke*spoke + spoke*spoke);
            Point[] corners = new Point[4];           // counter-clockwise
            corners[0] = start;                       // left
            int x = (int)(start.x + side * Math.cos(theta + Math.PI/4));
            int y = (int)(start.y + side * Math.sin(theta + Math.PI/4));
            corners[1] = new Point(x, y);             // bottom
            corners[2] = end;                         // right
            x = (int)(start.x + side * Math.cos(theta - Math.PI/4));
            y = (int)(start.y + side * Math.sin(theta - Math.PI/4));
            corners[3] = new Point(x, y);             // top
            cropPanel.setClip(corners);
    }

  • Can't undo last move

    I am trying to add an undo function to this program. Here is what I have so far. I can't get the undo function to work for some reason. Any help is appreciated.
    // Five.java - main program for Five-In-A-Row Program
    import javax.swing.JFrame;
    ////////////////////////////////////////////////////// class Five
    /** Five.java - Winner is able to put 5 pieces in a row.
       The Five program consists of three files:
       Five.java      - this file with main to create window.
       FiveGUI.java   - implements the GUI interface.
       FiveLogic.java - the logical functioning.
       @author Fred Swartz
       @version 2004-05-02
    class Five {
        //================================================ method main
        public static void main(String[] args) {
            JFrame window = new JFrame("Five In A Row");
            window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            window.setContentPane(new FiveGUI());
            window.pack();  // finalize layout
            window.setResizable(false);
            window.show();  // make window visible
        }//end main
    }//endclass Five
    //===========================================
    // FiveGUI.java
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    /////////////////////////////////////////////////// class FiveGUI
    /** A Graphical User Interface for a Five-In-A-Row game.
        This implements the user interface (view and controller),
        but the logic (model) is implemented in a separate class that
        knows nothing about the user interface.
        <p>This subclasses JPanel and puts the some buttons in the north,
        a graphical display of the board in the center, and
        a status field in the south.
        </p>
        <p>Exercise: This game probably originated on a Go board where
           the pieces are placed on the intersections, not in the
           empty spaces.  Change the program to put all pieces on the
           intersections.
        </p>
        <p>Exercise: The Undo button doesn't do anything.  Fix it here
           in the GUI and in the logic.
        </p>
        <p>Exercise: Create a machine player.</p>
        @author Fred Swartz
        @version 2004-05-02 Rodenbach
    class FiveGUI extends JPanel {
        //=============================================== instance variables
        private GraphicsPanel boardDisplay_;
        private JTextField    statusField_ = new JTextField();
        private FiveLogic     gameLogic_ = new FiveLogic(9, 9);
        private boolean       gameOver_ = false;
        private static final Color[]  PLAYER_COLOR = {null, Color.black, Color.white};
        private static final String[] PLAYER_NAME  = {null, "BLACK", "WHITE"};
        //====================================================== constructor
        public FiveGUI() {
            //--- Create some buttons
            JButton newGameButton = new JButton("New Game");
            JButton undoButton = new JButton("Undo");
            //--- Create control panel
            JPanel controlPanel = new JPanel();
            controlPanel.setLayout(new FlowLayout());
            controlPanel.add(newGameButton);
            controlPanel.add(undoButton);
            //--- Create graphics panel
            boardDisplay_ = new GraphicsPanel();
            //--- Set the layout and add the components
            this.setLayout(new BorderLayout());
            this.add(controlPanel , BorderLayout.NORTH);
            this.add(boardDisplay_, BorderLayout.CENTER);
            this.add(statusField_ , BorderLayout.SOUTH);
            //-- Add action listeners
            newGameButton.addActionListener(new NewGameAction());
                undoButton.addActionListener(new UndoAction());
        }//end constructor
        //////////////////////////////////////////////// class GraphicsPanel
        // This is defined inside the outer class so that
        // it can use the game logic variable.
        class GraphicsPanel extends JPanel implements MouseListener {
            private static final int ROWS = 9;
            private static final int COLS = 9;
            private static final int CELL_SIZE = 30; // Pixels
            private static final int WIDTH  = COLS * CELL_SIZE;
            private static final int HEIGHT = ROWS * CELL_SIZE;
            //================================================== constructor
            public GraphicsPanel() {
                this.setPreferredSize(new Dimension(WIDTH, HEIGHT));
                this.setBackground(Color.gray);
                this.addMouseListener(this);  // Listen own mouse events.
            }//end constructor
            //============================================== paintComponent
            public void paintComponent(Graphics g) {
                super.paintComponent(g);
                //-- Paint grid (could be done once and saved).
                for (int r=1; r<ROWS; r++) {  // Horizontal lines
                    g.drawLine(0, r*CELL_SIZE, WIDTH, r*CELL_SIZE);
                for (int c=1; c<COLS; c++) {
                    g.drawLine(c*CELL_SIZE, 0, c*CELL_SIZE, HEIGHT);
                //-- Draw players pieces.
                for (int r=0; r<ROWS; r++) {
                    for (int c=0; c<COLS; c++) {
                        int x = c * CELL_SIZE;
                        int y = r * CELL_SIZE;
                        int who = gameLogic_.getPlayerAt(r, c);
                        if (who != gameLogic_.EMPTY) {
                            g.setColor(PLAYER_COLOR[who]);
                            g.fillOval(x+2, y+2, CELL_SIZE-4, CELL_SIZE-4);
            }//end paintComponent
            //======================================== listener mousePressed
            public void mousePressed(MouseEvent e) {
                //--- map x,y coordinates into a row and col.
                int col = e.getX()/CELL_SIZE;
                int row = e.getY()/CELL_SIZE;
                int currentOccupant = gameLogic_.getPlayerAt(row, col);
                if (!gameOver_ && currentOccupant == gameLogic_.EMPTY) {
                    gameLogic_.move(row, col);
                    switch (gameLogic_.getGameStatus()) {
                        case 1: // Player one wins.  Game over.
                                gameOver_ = true;
                                statusField_.setText("BLACK WINS");
                                break;
                        case 2: // Player two wins.  Game over.
                                gameOver_ = true;
                                statusField_.setText("WHITE WINS");
                                break;
                        case FiveLogic.TIE:  // Tie game.  Game over.
                                gameOver_ = true;
                                statusField_.setText("TIE GAME");
                                break;
                        default: showNextPlayer();
                } else {  // Not legal
                    Toolkit.getDefaultToolkit().beep();
                this.repaint();  // Show any updates to game.
            }//end mousePressed
            //========================================== ignore these events
            public void mouseClicked (MouseEvent e) {}
            public void mouseReleased(MouseEvent e) {}
            public void mouseEntered (MouseEvent e) {}
            public void mouseExited  (MouseEvent e) {}
        }//end inner class GraphicsPanel
        //======================================= untility method showNextPlayer
        private void showNextPlayer() {
           statusField_.setText(PLAYER_NAME[gameLogic_.getNextPlayer()] + " to play");
        }//end showNextPlayer
        ///////////////////////////////////////// inner class NewGameAction
        private class NewGameAction implements ActionListener {
            public void actionPerformed(ActionEvent e) {
                gameLogic_.reset();
                gameOver_ = false;
                showNextPlayer();
                boardDisplay_.repaint();
        }//end inner class NewGameAction
         ///////////////////////////////////////// inner class NewGameAction
        private class UndoAction implements ActionListener {
            public void actionPerformed(ActionEvent e) {
                gameLogic_.undo();
                gameOver_ = false;
                showNextPlayer();
                boardDisplay_.repaint();
        }//end inner class NewGameAction
    }//end class FiveGUI
    //================================================
    // FiveLogic.java - Game to get 5 pieces in a row.
    ///////////////////////////////////////////////// class FiveLogic
    /** This class implements the logic (model) for the game of
        Five-In-A-Row.
        <br/>Exercise: The undo function doesn't do anything.  Fix it.
        @author Fred Swartz
        @version 2004-05-02
    class FiveLogic {
        /** Number of board rows. */
        private int maxRows_;
        /** Number of board columns. */
        private int maxCols_;
        /** The board. */
        private int[][] board_;
          /**The undo array. */
          private int[][] undoArray_;
        /** The player who moves next. */
        private int     nextPlayer_;
        /** Number of moves in the game. */
        private int     moves_ = 0;
        //-- Constants
        public  static final int EMPTY   = 0;  // The cell is empty.
        private static final int PLAYER1 = 1;
        public  static final int TIE     = -1; // Game is a tie (draw).
        //================================================== constructor
        public FiveLogic(int rows, int cols) {
            maxRows_ = rows;
            maxCols_ = cols;
            board_ = new int[maxRows_][maxCols_];
                undoArray_ = new int[maxRows_][maxCols_];
            reset();
        }//end constructor
        //================================================= getNextPlayer
        /** Returns the next player. */
        public int getNextPlayer() {
            return nextPlayer_;
        }//end getFace
        //=================================================== getPlayerAt
        /** Returns player who has played at particular row and column. */
        public int getPlayerAt(int r, int c) {
            return board_[r][c];
        }//end getPlayerAt
        //========================================================== reset
        /** Clears board to initial state. Makes first move in center. */
        public void reset() {
            for (int r=0; r<maxRows_; r++) {
                for (int c=0; c<maxCols_; c++) {
                    board_[r][c] = EMPTY;
            moves_ = 0;  // No moves so far.
            nextPlayer_ = PLAYER1; 
            //-- Make first move in center.
            move(maxCols_/2, maxRows_/2);  // First player moves to center
        }//end reset
        //=========================================================== move
        /** Play a marker on the board, record it, flip players. */
        public void move(int r, int c) {
            //assert board_[r][c] == EMPTY;
                undoArray_[r][c] = board_[r][c];
            board_[r][c] = nextPlayer_;  // Record this move.
            nextPlayer_ = 3-nextPlayer_; // Flip players
            moves_++;                    // Increment number of moves.
        }//end move
        //=========================================================== undo
        /** Undo the last move made.  Don't go beyond beginning. */
        public void undo() {
                    board_ = undoArray_;
                   moves_--;      
        }//end undo
        //========================================== utility method count5_
        /** The count5_ utility function returns true if there are five in
            a row starting at the specified r,c position and
            continuing in the dr direcection (+1, -1) and
            similarly for the column c.
        private boolean count5_(int r, int dr, int c, int dc) {
            int player = board_[r][c];  // remember the player.
            for (int i=1; i<5; i++) {
                if (board_[r+dr*i][c+dc*i] != player) return false;
            return true;  // There were 5 in a row!
        } // count5_
        //=================================================== getGameStatus
        /** -1 = game is tie, 0 = more to play,
             1 = player1 wins, 2 = player2 wins */
        public int getGameStatus() {
            int row;
            int col;
            int n_up, n_right, n_up_right, n_up_left;
            boolean at_least_one_move;   // true if game isn't a tie
            for (row = 0; row < maxRows_; row++) {
                for (col = 0; col < maxCols_; col++) {
                    int p = board_[row][col];
                    if (p != EMPTY) {
                        // look at 4 kinds of rows of 5
                        //  1. a column going up
                        //  2. a row going to the right
                        //  3. a diagonal up and to the right
                        //  4. a diagonal up and to the left
                        if (row < maxRows_-4) // Look up
                            if (count5_(row, 1, col, 0)) return p;
                        if (col < maxCols_-4) { // row to right
                            if (count5_(row, 0, col, 1))  return p;
                            if (row < maxRows_-4) { // diagonal up to right
                                if (count5_(row, 1, col, 1)) return p;
                        if (col > 3 && row < maxRows_-4) { // diagonal up left
                            if (count5_(row, 1, col, -1)) return p;
                    }//endif position wasn't empty
                }//endfor row
            }//endfor col
            // Neither player has won, it's tie if there are empty positions.
            // Game is finished if total moves equals number of positions.
            if (moves_ == maxRows_*maxCols_) {
                return TIE; // Game tied.  No more possible moves.
            } else {
                return 0;  // More to play.
        }//end getGameStatus
    }//end class FiveLogic

    Oh, oh, oh. I know why it clears the whole board. You are only saving the previous state of each square as a player moves to it. A player can only move to a square if it's empty. So you are only storing empty squares.
    Change the move method to do this:
    public void move(int r, int c) {
        //assert board_[r][c] == EMPTY;
        undoArray_ = (int[][]) board_.clone();
        board_[r][c] = nextPlayer_; // Record this move.
        nextPlayer_ = 3-nextPlayer_; // Flip players
        moves_++;  // Increment number of moves.
    }

  • Struggling with the Submit Form

    My incomplete site has three links which don't seem to work at all. Unsurprisingly they are all the same file type and I don't have the slightest clue on how to fix it!
    http://www.expertpcguides.com/contact-us.html
    I have supplied the coding for one of my pages 'Site Feedback'. My goal is to create a send-able form where the user can contact us at [email protected]. You guys supplied me with this script, but for some reason (probably due to my own fault) it isn't working! Thanks for the help.
    Technical Support Page:
    <!DOCTYPE HTML>
    <html>
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>technical-support</title>
            <link rel="stylesheet" href="css/common-reset.css" type="text/css" media="screen" />
            <link rel="stylesheet" href="css/common-style.css" type="text/css" media="screen" />
            <link href="lightbox/css/lightbox.css" rel="stylesheet" />
            <link href='http://fonts.googleapis.com/css?family=Open+Sans%7CBaumans%7CArvo%7CRoboto' rel='stylesheet' type='text/css' />
            <script src="js/modernizr.js"></script>
            <script src="js/respond.min.js"></script>
            <!-- include extern jQuery file but fall back to local file if extern one fails to load !-->
            <script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
            <script type="text/javascript">window.jQuery || document.write('<script type="text/javascript" src="js\/1.7.2.jquery.min"><\/script>')</script>
            <script src="lightbox/js/lightbox.js"></script>
            <script src="js/prefixfree.min.js"></script>
            <script src="js/jquery.slides.min.js"></script>
            <!--[if lt IE 9]>
                <style>
                    header
                        margin: 0 auto 20px auto;
                    #four_columns .img-item figure span.thumb-screen
                        display:none;
                </style>
            <![endif]-->
            <script>
            $(function() {
              $('#slides').slidesjs({
                height: 235,
                navigation: false,
                pagination: false,
                effect: {
                  fade: {
                    speed: 2600
                callback: {
                    start: function(number)
                        $("#slider_content1,#slider_content2,#slider_content3").fadeOut(500);
                    complete: function(number)
                        $("#slider_content" + number).delay(200).fadeIn(1000);
                play: {
                    active: false,
                    auto: true,
                    interval: 28000,
                    pauseOnHover: false
            </script>
         <style type="text/css">
    <!--
    .style4 {
      font-size: 20px
    .style5 {color: #0000FF}
    .style6 {
      color: #0099CC;
      font-weight: bold;
    .style9 {
      color: #CCCCCC;
      font-size: 90%;
    .style12 {font-family: Georgia, "Times New Roman", Times, serif; color: #000000; font-size: 120%; }
    .style16 {color: #000099}
    .style45 {font-family: Georgia, "Times New Roman", Times, serif; color: #0000FF; font-size: 120%; }
    .style46 {color: #000000}
    -->
            </style>
    </head>
      <body>
            <header>           
                <h1 class="style5">Expertpcguides.com</h1>
              <p class="style6">Technology Explained.</p>
    <select id="alternative_menu" size="1">
                    <option>Home</option>
                    <option>About</option>
                    <option>Contact us</option>
                    <option>Login/Register</option>
                    <option>Forums</option>
    <option>Privacy Policy</option>
                    <option>Disclaimer</option>
                    <option>Legal Notice</option>
                </select>
                <nav>
                <h2 class="hidden">Our navigation</h2>
                    <ul>
                        <li><a href="index.html" class="style46">Home</a></li>
                      <li><a href="about-us.html" class="style46">About</a></li>
                      <li><a href="javascript:void(0)" class="style46">Contact us</a></li>
                      <li><a href="javascript:void(0)" class="style46">Login/Register</a></li>
                      <li><a href="javascript:void(0)" class="style46">Forums</a></li>
                  </ul>
                </nav>
            </header>
            <section id="spacer"> 
            <h2 class="hidden">Dolor sit amet</h2>         
                <p><span style="color:#5cb3ff;">D</span><span style="color:#6cbafe;">i</span><span style="color:#7cc1fe;">c</span><span style="color:#8cc9fd;">t</span><span style="color:#9cd0fd;">i</span><span style="color:#abd7fc;">o</span><span style="color:#bbdefc;">n</span><span style="color:#cbe6fb;">a</span><span style="color:#dbedfb;">r</span><span style="color:#ebf4fa;">y</span> | <span style="color:#ffffff;">A</span><span style="color:#dcf1ff;">r</span><span style="color:#b9e3ff;">t</span><span style="color:#96d5ff;">i</span><span style="color:#74c8ff;">c</span><span style="color:#51baff;">l</span><span style="color:#2eacff;">e</span><span style="color:#0b9eff;">s</span> | <span style="color:#1c95ff;">C</span><span style="color:#299bff;">o</span><span style="color:#35a0ff;">m</span><span style="color:#42a6ff;">p</span><span style="color:#4facff;">u</span><span style="color:#5bb2ff;">t</span><span style="color:#68b7ff;">e</span><span style="color:#75bdff;">r</span><span style="color:#81c3ff;"> </span><span style="color:#8ec9ff;">H</span><span style="color:#9bceff;">i</span><span style="color:#a7d4ff;">s</span><span style="color:#b4daff;">t</span><span style="color:#c1e0ff;">o</span><span style="color:#cde5ff;">r</span><span style="color:#daebff;">y</span> | <span style="color:#1c95ff;">F</span><span style="color:#2d9dff;">r</span><span style="color:#3fa5ff;">e</span><span style="color:#50adff;">e</span><span style="color:#62b6ff;"> </span><span style="color:#73beff;">D</span><span style="color:#85c6ff;">o</span><span style="color:#96ceff;">w</span><span style="color:#a8d6ff;">n</span><span style="color:#b9deff;">l</span><span style="color:#cbe7ff;">o</span><span style="color:#dcefff;">a</span><span style="color:#eef7ff;">d</span><span style="color:#ffffff;">s</span></p>
    <div class="search">
    <form id="searchbox_000429658622879505763:gczdzyghogq" action="https://www.google.com/cse/publicurl?cx=000429658622879505763:gczdzyghogq">
    <input value="000429658622879505763:gczdzyghogq" name="cx" type="hidden"/>
    <input value="FORID:11" name="cof" type="hidden"/>
    <input id="q" style="width:150px;" name="q" size="70" type="text" />
    <input value="Search" name="sa" type="submit"/>
    </form>
    </div>
        </section>
    <section id="boxcontent">
    <section id="four_columns">
                <h2 class="style16">
                    Support</h2>   
                <p class="style45">
                    <?phpif(isset($sent)) {
        echo "<h3>$sent</h3>";
    if(isset($error)) {
    echo "<h3>$error</h3>";
    ?>
    <form id="form1" name="form1" method="post" action="">
    <p><span class="style46"><strong>Name:</strong></span></p>
    <form name="form1" method="post" action="">
      <label>
      <input type="text" name="Namefield" id="Namefield">
      </label>
    </form>
    <p><span class="style46"><br />
    </span></p>
    <p><span class="style46"><strong>Email:</strong></span></p>
    <form name="form2" method="post" action="">
      <label>
      <input type="text" name="emailfield" id="emailfield">
      </label>
      <span class="style46"><br />
      </span>
    </form>
    <p><span class="style46"><strong>Computer Brand:</strong></span></p>
    <form name="form3" method="post" action="">
      <label>
      <select name="computerbrandfield" size="5" id="computerbrandfield">
        <option>Atari</option>
        <option>Compaq</option>
        <option>CTX</option>
        <option>Custom Built</option>
        <option>Cyber Max</option>
        <option>Dell</option>
        <option>Digital</option>
        <option>DTK</option>
        <option>E-machine</option>
        <option>Gateway</option>
        <option>Hand Held</option>
        <option>Hewlett Packard</option>
        <option>IBM</option>
        <option>Lenevo</option>
        <option>Macintosh</option>
        <option>Micron</option>
        <option>Midwest Micro</option>
        <option>NEC</option>
        <option>Packard Bell</option>
        <option>Quantex</option>
        <option>Sharp</option>
        <option>Sony</option>
        <option>Sun</option>
        <option>Systemax</option>
        <option>Tiger Direct</option>
        <option>Toshiba</option>
        <option>Twinhead</option>
        <option>Winbook</option>
        <option>Xi Computer</option>
        <option>Zenith</option>
        <option>Other Computer Brand</option>
        <option>Other Device</option>
      </select>
      </label>
    </form>
    <p><span class="style46"><br />
    </span></p>
    <p><span class="style46"><strong>Operating System:</strong></span></p>
    <form name="form4" method="post" action="">
      <label>
      <select name="computerbrandfield3" size="5" id="computerbrandfield3">
        <option>Windows 8</option>
        <option>Windows 7</option>
        <option>Windows Vista</option>
        <option>Windows XP</option>
        <option>Windows 2000</option>
        <option>Windows 2003</option>
        <option>Mac OS</option>
        <option>Linux Variant</option>
        <option>BSD</option>
        <option>DOS / PC-DOS</option>
        <option>OS/2 Warp</option>
        <option>Windows 98</option>
        <option>Windows 95</option>
        <option>Windows CE</option>
        <option>Windows ME</option>
        <option>Windows NT</option>
        <option>Windows 3.x</option>
        <option>Other</option>
        <option>Unknown</option>
        </select>
      </label>
    </form>
    <p><span class="style46"><br />
    </span></p>
    <p><span class="style46"><strong>Amount of RAM:</strong></span></p>
    <p><span class="style46">
      <select name="computerbrandfield2" size="5" id="computerbrandfield2">
        <option>0mb-1GB</option>
        <option>1GB-2GB</option>
        <option>2GB-4GB</option>
        <option>More than 4GB</option>
        </select>
      </span></p>
    <p><span class="style46"><br />
    </span></p>
    <p><span class="style46"><strong>CPU Type:</strong></span></p>
    <p>
      <select name="computerbrandfield4" size="5" id="computerbrandfield4">
        <option>Power PC</option>
        <option>Rise mP6</option>
        <option>Transmeta Crusoe</option>
        <option>Other</option>
        <option>Unknown</option>
        </select>
    </p>
    <p> </p>
    <p><span class="style46"><strong>Computer Type:</strong></span><span class="style46"><br />
    </span></p>
    <p><span class="style46">
      <select name="computerbrandfield5" size="5" id="computerbrandfield5">
        <option>Desktop/Workstation</option>
        <option>Gaming System</option>
        <option>Laptop</option>
        <option>PDA / Mobile</option>
        <option>Server</option>
        <option>Other</option>
        </select>
      <br />
    </span></p>
    <label><span class="style46"><strong>Question:</strong><br />
    </span><br />
    <textarea name="textarea" id="textarea" cols="45" rows="5"></textarea>
    </label>
    <p> </p>
    <p>
    <label>
    <input type="submit" name="Submit" id="Submit" value="Submit" />
    </label>
    </p>
        <p class="style12"><br class="clear"/>
        </p>
      </section><br class="clear"/>
        </section>
    <section id="text_columns">
    <section class="column2"></section>
            </section>
    <footer>
          <h2 class="hidden">Our footer</h2>
          <section id="copyright">
            <h3 class="hidden">Copyright notice</h3>
            <div class="wrapper">
              <div class="social"> <a href="index.html"><img src="img/G.png" alt="G" width="25"/></a> <a href="index.html"><img src="img/U.png" alt="U" width="25"/></a> <a href="index.html"><img src="img/I.png" alt="I" width="25"/></a> <a href="index.html"><img src="img/D.png" alt="D" width="25"/></a> <a href="index.html"><img src="img/E.png" alt="E" width="25"/></a> <a href="index.html"><img src="img/S.png" alt="S" width="25"/></a> </div>
              &copy; Copyright 2014 by Expertpcguides.com. All Rights Reserved. </div>
    </section>
          <section class="wrapper">
            <h3 class="hidden">Footer content</h3>
            <article class="column hide">
              <h4>Site Links</h4>
                <div class="class1">
                  <p class="footer-text"><a href="web-contributors.html" >Developers/Contributors</a></p>
                </div>
              <div class="class1">
                  <p><a href="create-a-page.html" class="style10">Create a page</a></p>
              </div>
              <div class="class1">
                <p><a href="point-system.html" class="style10">Rewards System</a></p>
              </div>
              <div class="class1">
                <p><a href="privacy.html" class="style10">Privacy</a></p>
              </div>
            </article>
    <article class="column midlist2">
              <h4 class="style4">Follow Us</h4>
              <ul class="style4">
                <li><div class="class1">
                    <p class="footer-text"><img src="img/Facebook-logo.png" alt="Facebook Image" width="32" height="34"/> <a href="https://www.facebook.com/expertpcguides" class="style23">Facebook</a></p></div></li>
    <li><div class="class1">
                  <p class="footer-text"><img src="img/Twitter-Logo.jpg" alt="Twitter Image" width="30" height="33"/><a href="https://twitter.com/ExpertPcGuides" class="style23" > Twitter</a></p></div></li>
      <li><div class="class1">
        <p class="footer-text"><img src="img/Google+Logo.jpg" alt="Google + Image" width="31" height="35"/><a href="https://plus.google.com/115474035983654843441" class="style23"> Google Plus</a></p></div></li>
      <li><div class="class1">
        <p class="footer-text"><img src="img/Pininterest-Logo.png" alt="Pininterest Image" width="33" height="34" ><a href="http://www.pinterest.com/expertpcguides/" class="style23"> Pininterest</a></p></div></li>
              </ul>
            </article>
            <article class="column rightlist">
              <h4>Interested in Exclusive Articles?</h4>
                <div class="class2">
                  <p><a href="login.html" class="style10">All you need to do is login/register</a></p>
                </div>
            </article>
          </section>
    <section class="wrapper"><h3 class="hidden">If you are seeing this, then the site is losing stability</h3></section>
            </footer>
                                    </body>
    </html>

    Also, what's this about? There's no form at all!
      <body>
            <header>          
                <h1 class="style5">Expertpcguides.com</h1>
              <p class="style6">Technology Explained.</p>
    <select id="alternative_menu" size="1">
                    <option>Home</option>
                    <option>About</option>
                    <option>Contact us</option>
                    <option>Login/Register</option>
                    <option>Forums</option>
    <option>Privacy Policy</option>
                    <option>Disclaimer</option>
                    <option>Legal Notice</option>
                </select>
    By the way, you are going to drive yourself crazy if you don't stop using the Property inspector to style your content -
         <style type="text/css">
    <!--
    .style4 {
      font-size: 20px
    .style5 {color: #0000FF}
    .style6 {
      color: #0099CC;
      font-weight: bold;
    .style9 {
      color: #CCCCCC;
      font-size: 90%;
    .style12 {font-family: Georgia, "Times New Roman", Times, serif; color: #000000; font-size: 120%; }
    .style16 {color: #000099}
    .style45 {font-family: Georgia, "Times New Roman", Times, serif; color: #0000FF; font-size: 120%; }
    .style46 {color: #000000}
    -->
            </style>

  • Why is this an error???  I don't understand why it is... Help Please

    Hi,
    Ok, I'll preface this by saying there's a lotta code pasted in here but it really quite an easy question, I just need to post all the code so you understand where what came from.
    Now.............the question I'm trying to do is to create an applet that has 2 buttons -- each button when clicked opens an application (one is a simple calculator, the other a Mortgage calculation app). When you click one of the buttons (calc or mortgage), that app opens infront of the 2 button menu so its in "focus". The button on the 2 button menu then switches to a "hide app X" button (ie: "Mortgage", changes to "Hide Mortgage"). Thus if you click the hide button, the app that was opened is hidden, and then that "hide" button switches back to the original "app X" button. Pretty simple.
    Now, I have from my text book an example that does exactly this, with the simple calculator already in it, and with another app (a traffic light thing) where the Mortgage should be in my final product. I also already have the Mortgage applet I need to insert from another book example in place of that Traffic Light portion.
    Now, common sense would dictate that I should be able to just copy my code for the Mortgage applet into the example that has the 2 button menu structure, and overwrite the code I want to get rid of (the traffic light) with the mortgage code & rename the menu buttons. Right?? A simple switch of one thing for another... but therein lies my problem.
    I copied all the Mortgage code in correctly over the traffic lights, switched the button names, tried to compile it but I get one error....
    Exercise12_17.java:52: cannot resolve symbol
    symbol  : method pack ()
    location: class MortgageApplet
            mortgageAppletFrame.pack();I don't understand why..... mortgageAppletFrame.pack(); was a simple rewrite from lightsFrame.pack(); like every other line...... it should work. I've gone over it for 2 days......... Anyone know why it comes up as an error???
    Below, in order going down is (1)my code with the 1 error I can't solve, (2)the original menu example I tried to edit, and (3)the Mortgage app code...........
    Does anyone know what my error is?? Help or a hint would be greatly appreciated........ Thanks.
    My erroring app.......
    // Exercise12_17.java: Create multiple windows
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.TitledBorder;
    public class Exercise12_17 extends JFrame implements ActionListener {
      // Declare and create a frame: an instance of MenuDemo
      MenuDemo calcFrame = new MenuDemo();
      // Declare and create a frame: an instance of RadioButtonDemo
      MortgageApplet mortgageAppletFrame = new MortgageApplet();
      // Declare two buttons for displaying frames
      private JButton jbtCalc;
      private JButton jbtMortgage;
      public static void main(String[] args) {
        Exercise12_17 frame = new Exercise12_17();
        frame.setSize( 400, 70 );
        frame.setTitle("Exercise 11.8: Multiple Windows Demo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
      public Exercise12_17() {
        // Add buttons to the main frame
        getContentPane().setLayout(new FlowLayout());
        getContentPane().add(jbtCalc = new JButton("Simple Calculator"));
         getContentPane().add(jbtMortgage = new JButton("Mortgage"));
        // Register the main frame as listener for the buttons
        jbtCalc.addActionListener(this);
         jbtMortgage.addActionListener(this);
      public void actionPerformed(ActionEvent e) {
        String arg = e.getActionCommand();
        if (e.getSource() instanceof JButton)
          if ("Simple Calculator".equals(arg)) {
            //show the MenuDemo frame
            jbtCalc.setText("Hide Simple Calculator");
            calcFrame.pack();
            calcFrame.setVisible(true);
          else if ("Hide Simple Calculator".equals(arg)) {
            calcFrame.setVisible(false);
            jbtCalc.setText("Simple Calculator");
          else if ("Mortgage".equals(arg)) {
            //show the CheckboxGroup frame
            mortgageAppletFrame.pack();
            jbtMortgage.setText("Hide Mortgage");
            mortgageAppletFrame.setVisible(true);
          else if ("Hide Mortgage".equals(arg)) {
            mortgageAppletFrame.setVisible(false);
            jbtMortgage.setText("Mortgage");
      class MortgageApplet extends JApplet
      implements ActionListener {
      // Declare and create text fields for interest rate
      // year, loan amount, monthly payment, and total payment
      private JTextField jtfAnnualInterestRate = new JTextField();
      private JTextField jtfNumOfYears = new JTextField();
      private JTextField jtfLoanAmount = new JTextField();
      private JTextField jtfMonthlyPayment = new JTextField();
      private JTextField jtfTotalPayment = new JTextField();
      // Declare and create a Compute Mortgage button
      private JButton jbtComputeMortgage = new JButton("Compute Mortgage");
      /** Initialize user interface */
      public void init() {
        // Set properties on the text fields
        jtfMonthlyPayment.setEditable(false);
        jtfTotalPayment.setEditable(false);
        // Right align text fields
        jtfAnnualInterestRate.setHorizontalAlignment(JTextField.RIGHT);
        jtfNumOfYears.setHorizontalAlignment(JTextField.RIGHT);
        jtfLoanAmount.setHorizontalAlignment(JTextField.RIGHT);
        jtfMonthlyPayment.setHorizontalAlignment(JTextField.RIGHT);
        jtfTotalPayment.setHorizontalAlignment(JTextField.RIGHT);
        // Panel p1 to hold labels and text fields
        JPanel p1 = new JPanel();
        p1.setLayout(new GridLayout(5, 2));
        p1.add(new Label("Annual Interest Rate"));
        p1.add(jtfAnnualInterestRate);
        p1.add(new Label("Number of Years"));
        p1.add(jtfNumOfYears);
        p1.add(new Label("Loan Amount"));
        p1.add(jtfLoanAmount);
        p1.add(new Label("Monthly Payment"));
        p1.add(jtfMonthlyPayment);
        p1.add(new Label("Total Payment"));
        p1.add(jtfTotalPayment);
        p1.setBorder(new
          TitledBorder("Enter interest rate, year and loan amount"));
        // Panel p2 to hold the button
        JPanel p2 = new JPanel();
        p2.setLayout(new FlowLayout(FlowLayout.RIGHT));
        p2.add(jbtComputeMortgage);
        // Add the components to the applet
        getContentPane().add(p1, BorderLayout.CENTER);
        getContentPane().add(p2, BorderLayout.SOUTH);
        // Register listener
        jbtComputeMortgage.addActionListener(this);
      /** Handle the "Compute Mortgage" button */
      public void actionPerformed(ActionEvent e) {
        if (e.getSource() == jbtComputeMortgage) {
          // Get values from text fields
          double interest = (Double.valueOf(
            jtfAnnualInterestRate.getText())).doubleValue();
          int year =
            (Integer.valueOf(jtfNumOfYears.getText())).intValue();
          double loan =
            (Double.valueOf(jtfLoanAmount.getText())).doubleValue();
          // Create a mortgage object
          Mortgage m = new Mortgage(interest, year, loan);
          // Display monthly payment and total payment
          jtfMonthlyPayment.setText(String.valueOf(m.monthlyPayment()));
          jtfTotalPayment.setText(String.valueOf(m.totalPayment()));
    class MenuDemo extends JFrame implements ActionListener {
      // Text fields for Number 1, Number 2, and Result
      private JTextField jtfNum1, jtfNum2, jtfResult;
      // Buttons "Add", "Subtract", "Multiply" and "Divide"
      private JButton jbtAdd, jbtSub, jbtMul, jbtDiv;
      // Menu items "Add", "Subtract", "Multiply","Divide" and "Close"
      private JMenuItem jmiAdd, jmiSub, jmiMul, jmiDiv, jmiClose;
      /** Main method */
      public static void main(String[] args) {
        MenuDemo frame = new MenuDemo();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
      /** Default constructor */
      public MenuDemo() {
        setTitle("Menu Demo");
        // Create menu bar
        JMenuBar jmb = new JMenuBar();
        // Set menu bar to the frame
        setJMenuBar(jmb);
        // Add menu "Operation" to menu bar
        JMenu operationMenu = new JMenu("Operation");
        operationMenu.setMnemonic('O');
        jmb.add(operationMenu);
        // Add menu "Exit" in menu bar
        JMenu exitMenu = new JMenu("Exit");
        exitMenu.setMnemonic('E');
        jmb.add(exitMenu);
        // Add menu items with mnemonics to menu "Operation"
        operationMenu.add(jmiAdd= new JMenuItem("Add", 'A'));
        operationMenu.add(jmiSub = new JMenuItem("Subtract", 'S'));
        operationMenu.add(jmiMul = new JMenuItem("Multiply", 'M'));
        operationMenu.add(jmiDiv = new JMenuItem("Divide", 'D'));
        exitMenu.add(jmiClose = new JMenuItem("Close", 'C'));
        // Set keyboard accelerators
        jmiAdd.setAccelerator(
          KeyStroke.getKeyStroke(KeyEvent.VK_A, ActionEvent.CTRL_MASK));
        jmiSub.setAccelerator(
          KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK));
        jmiMul.setAccelerator(
          KeyStroke.getKeyStroke(KeyEvent.VK_M, ActionEvent.CTRL_MASK));
        jmiDiv.setAccelerator(
          KeyStroke.getKeyStroke(KeyEvent.VK_D, ActionEvent.CTRL_MASK));
        // Panel p1 to hold text fields and labels
        JPanel p1 = new JPanel();
        p1.setLayout(new FlowLayout());
        p1.add(new JLabel("Number 1"));
        p1.add(jtfNum1 = new JTextField(3));
        p1.add(new JLabel("Number 2"));
        p1.add(jtfNum2 = new JTextField(3));
        p1.add(new JLabel("Result"));
        p1.add(jtfResult = new JTextField(4));
        jtfResult.setEditable(false);
        // Panel p2 to hold buttons
        JPanel p2 = new JPanel();
        p2.setLayout(new FlowLayout());
        p2.add(jbtAdd = new JButton("Add"));
        p2.add(jbtSub = new JButton("Subtract"));
        p2.add(jbtMul = new JButton("Multiply"));
        p2.add(jbtDiv = new JButton("Divide"));
        // Add panels to the frame
        getContentPane().setLayout(new BorderLayout());
        getContentPane().add(p1, BorderLayout.CENTER);
        getContentPane().add(p2, BorderLayout.SOUTH);
        // Register listeners
        jbtAdd.addActionListener(this);
        jbtSub.addActionListener(this);
        jbtMul.addActionListener(this);
        jbtDiv.addActionListener(this);
        jmiAdd.addActionListener(this);
        jmiSub.addActionListener(this);
        jmiMul.addActionListener(this);
        jmiDiv.addActionListener(this);
        jmiClose.addActionListener(this);
      /** Handle ActionEvent from buttons and menu items */
      public void actionPerformed(ActionEvent e) {
        String actionCommand = e.getActionCommand();
        // Handle button events
        if (e.getSource() instanceof JButton) {
          if ("Add".equals(actionCommand))
            calculate('+');
          else if ("Subtract".equals(actionCommand))
            calculate('-');
          else if ("Multiply".equals(actionCommand))
            calculate('*');
          else if ("Divide".equals(actionCommand))
            calculate('/');
        else if (e.getSource() instanceof JMenuItem) {
          // Handle menu item events
          if ("Add".equals(actionCommand))
            calculate('+');
          else if ("Subtract".equals(actionCommand))
            calculate('-');
          else if ("Multiply".equals(actionCommand))
            calculate('*');
          else if ("Divide".equals(actionCommand))
            calculate('/');
          else if ("Close".equals(actionCommand))
            System.exit(0);
      /** Calculate and show the result in jtfResult */
      private void calculate(char operator) {
        // Obtain Number 1 and Number 2
        int num1 = (Integer.parseInt(jtfNum1.getText().trim()));
        int num2 = (Integer.parseInt(jtfNum2.getText().trim()));
        int result = 0;
        // Perform selected operation
        switch (operator) {
          case '+': result = num1 + num2;
                    break;
          case '-': result = num1 - num2;
                    break;
          case '*': result = num1 * num2;
                    break;
          case '/': result = num1 / num2;
        // Set result in jtfResult
        jtfResult.setText(String.valueOf(result));
    Original 2 button menu example....
    // Exercise11_8.java: Create multiple windows
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Exercise11_8 extends JFrame implements ActionListener {
      // Declare and create a frame: an instance of MenuDemo
      MenuDemo calcFrame = new MenuDemo();
      // Declare and create a frame: an instance of RadioButtonDemo
      RadioButtonDemo lightsFrame = new RadioButtonDemo();
      // Declare two buttons for displaying frames
      private JButton jbtCalc;
      private JButton jbtLights;
      public static void main(String[] args) {
        Exercise11_8 frame = new Exercise11_8();
        frame.setSize( 400, 70 );
        frame.setTitle("Exercise 11.8: Multiple Windows Demo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
      public Exercise11_8() {
        // Add buttons to the main frame
        getContentPane().setLayout(new FlowLayout());
        getContentPane().add(jbtCalc = new JButton("Simple Calculator"));
        getContentPane().add(jbtLights = new JButton("Traffic Lights"));
        // Register the main frame as listener for the buttons
        jbtCalc.addActionListener(this);
        jbtLights.addActionListener(this);
      public void actionPerformed(ActionEvent e) {
        String arg = e.getActionCommand();
        if (e.getSource() instanceof JButton)
          if ("Simple Calculator".equals(arg)) {
            //show the MenuDemo frame
            jbtCalc.setText("Hide Simple Calculator");
            calcFrame.pack();
            calcFrame.setVisible(true);
          else if ("Hide Simple Calculator".equals(arg)) {
            calcFrame.setVisible(false);
            jbtCalc.setText("Simple Calculator");
          else if ("Traffic Lights".equals(arg)) {
            //show the CheckboxGroup frame
            lightsFrame.pack();
            jbtLights.setText("Hide Traffic Lights");
            lightsFrame.setVisible(true);
          else if ("Hide Traffic Lights".equals(arg)) {
            lightsFrame.setVisible(false);
            jbtLights.setText("Traffic Lights");
         class RadioButtonDemo extends JFrame
      implements ItemListener {
      // Declare radio buttons
      private JRadioButton jrbRed, jrbYellow, jrbGreen;
      // Declare a radio button group
      private ButtonGroup btg = new ButtonGroup();
      // Declare a traffic light display panel
      private Light light;
      /** Main method */
      public static void main(String[] args) {
        RadioButtonDemo frame = new RadioButtonDemo();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(250, 170);
        frame.setVisible(true);
      /** Default constructor */
      public RadioButtonDemo() {
        setTitle("RadioButton Demo");
        // Add traffic light panel to panel p1
        JPanel p1 = new JPanel();
        p1.setSize(200, 200);
        p1.setLayout(new FlowLayout(FlowLayout.CENTER));
        light = new Light();
        light.setSize(40, 90);
        p1.add(light);
        // Put the radio button in Panel p2
        JPanel p2 = new JPanel();
        p2.setLayout(new FlowLayout());
        p2.add(jrbRed = new JRadioButton("Red", true));
        p2.add(jrbYellow = new JRadioButton("Yellow", false));
        p2.add(jrbGreen = new JRadioButton("Green", false));
        // Set keyboard mnemonics
        jrbRed.setMnemonic('R');
        jrbYellow.setMnemonic('Y');
        jrbGreen.setMnemonic('G');
        // Group radio buttons
        btg.add(jrbRed);
        btg.add(jrbYellow);
        btg.add(jrbGreen);
        // Place p1 and p2 in the frame
        getContentPane().setLayout(new BorderLayout());
        getContentPane().add(p1, BorderLayout.CENTER);
        getContentPane().add(p2, BorderLayout.SOUTH);
        // Register listeners for check boxes
        jrbRed.addItemListener(this);
        jrbYellow.addItemListener(this);
        jrbGreen.addItemListener(this);
      /** Handle checkbox events */
      public void itemStateChanged(ItemEvent e) {
        if (jrbRed.isSelected())
          light.turnOnRed(); // Set red light
        if (jrbYellow.isSelected())
          light.turnOnYellow(); // Set yellow light
        if (jrbGreen.isSelected())
          light.turnOnGreen(); // Set green light
    // Three traffic lights shown in a panel
    class Light extends JPanel {
      private boolean red;
      private boolean yellow;
      private boolean green;
      /** Default constructor */
      public Light() {
        turnOnGreen();
      /** Set red light on */
      public void turnOnRed() {
        red = true;
        yellow = false;
        green = false;
        repaint();
      /** Set yellow light on */
      public void turnOnYellow() {
        red = false;
        yellow = true;
        green = false;
        repaint();
      /** Set green light on */
      public void turnOnGreen() {
        red = false;
        yellow = false;
        green = true;
        repaint();
      /** Display lights */
      public void paintComponent(Graphics g) {
        super.paintComponent(g);
        if (red) {
          g.setColor(Color.red);
          g.fillOval(10, 10, 20, 20);
          g.setColor(Color.black);
          g.drawOval(10, 35, 20, 20);
          g.drawOval(10, 60, 20, 20);
          g.drawRect(5, 5, 30, 80);
        else if (yellow) {
          g.setColor(Color.yellow);
          g.fillOval(10, 35, 20, 20);
          g.setColor(Color.black);
          g.drawRect(5, 5, 30, 80);
          g.drawOval(10, 10, 20, 20);
          g.drawOval(10, 60, 20, 20);
        else if (green) {
          g.setColor(Color.green);
          g.fillOval(10, 60, 20, 20);
          g.setColor(Color.black);
          g.drawRect(5, 5, 30, 80);
          g.drawOval(10, 10, 20, 20);
          g.drawOval(10, 35, 20, 20);
        else {
          g.setColor(Color.black);
          g.drawRect(5, 5, 30, 80);
          g.drawOval(10, 10, 20, 20);
          g.drawOval(10, 35, 20, 20);
          g.drawOval(10, 60, 20, 20);
      /** Set preferred size */
      public Dimension getPreferredSize() {
        return new Dimension(40, 90);
    class MenuDemo extends JFrame implements ActionListener {
      // Text fields for Number 1, Number 2, and Result
      private JTextField jtfNum1, jtfNum2, jtfResult;
      // Buttons "Add", "Subtract", "Multiply" and "Divide"
      private JButton jbtAdd, jbtSub, jbtMul, jbtDiv;
      // Menu items "Add", "Subtract", "Multiply","Divide" and "Close"
      private JMenuItem jmiAdd, jmiSub, jmiMul, jmiDiv, jmiClose;
      /** Main method */
      public static void main(String[] args) {
        MenuDemo frame = new MenuDemo();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
      /** Default constructor */
      public MenuDemo() {
        setTitle("Menu Demo");
        // Create menu bar
        JMenuBar jmb = new JMenuBar();
        // Set menu bar to the frame
        setJMenuBar(jmb);
        // Add menu "Operation" to menu bar
        JMenu operationMenu = new JMenu("Operation");
        operationMenu.setMnemonic('O');
        jmb.add(operationMenu);
        // Add menu "Exit" in menu bar
        JMenu exitMenu = new JMenu("Exit");
        exitMenu.setMnemonic('E');
        jmb.add(exitMenu);
        // Add menu items with mnemonics to menu "Operation"
        operationMenu.add(jmiAdd= new JMenuItem("Add", 'A'));
        operationMenu.add(jmiSub = new JMenuItem("Subtract", 'S'));
        operationMenu.add(jmiMul = new JMenuItem("Multiply", 'M'));
        operationMenu.add(jmiDiv = new JMenuItem("Divide", 'D'));
        exitMenu.add(jmiClose = new JMenuItem("Close", 'C'));
        // Set keyboard accelerators
        jmiAdd.setAccelerator(
          KeyStroke.getKeyStroke(KeyEvent.VK_A, ActionEvent.CTRL_MASK));
        jmiSub.setAccelerator(
          KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK));
        jmiMul.setAccelerator(
          KeyStroke.getKeyStroke(KeyEvent.VK_M, ActionEvent.CTRL_MASK));
        jmiDiv.setAccelerator(
          KeyStroke.getKeyStroke(KeyEvent.VK_D, ActionEvent.CTRL_MASK));
        // Panel p1 to hold text fields and labels
        JPanel p1 = new JPanel();
        p1.setLayout(new FlowLayout());
        p1.add(new JLabel("Number 1"));
        p1.add(jtfNum1 = new JTextField(3));
        p1.add(new JLabel("Number 2"));
        p1.add(jtfNum2 = new JTextField(3));
        p1.add(new JLabel("Result"));
        p1.add(jtfResult = new JTextField(4));
        jtfResult.setEditable(false);
        // Panel p2 to hold buttons
        JPanel p2 = new JPanel();
        p2.setLayout(new FlowLayout());
        p2.add(jbtAdd = new JButton("Add"));
        p2.add(jbtSub = new JButton("Subtract"));
        p2.add(jbtMul = new JButton("Multiply"));
        p2.add(jbtDiv = new JButton("Divide"));
        // Add panels to the frame
        getContentPane().setLayout(new BorderLayout());
        getContentPane().add(p1, BorderLayout.CENTER);
        getContentPane().add(p2, BorderLayout.SOUTH);
        // Register listeners
        jbtAdd.addActionListener(this);
        jbtSub.addActionListener(this);
        jbtMul.addActionListener(this);
        jbtDiv.addActionListener(this);
        jmiAdd.addActionListener(this);
        jmiSub.addActionListener(this);
        jmiMul.addActionListener(this);
        jmiDiv.addActionListener(this);
        jmiClose.addActionListener(this);
      /** Handle ActionEvent from buttons and menu items */
      public void actionPerformed(ActionEvent e) {
        String actionCommand = e.getActionCommand();
        // Handle button events
        if (e.getSource() instanceof JButton) {
          if ("Add".equals(actionCommand))
            calculate('+');
          else if ("Subtract".equals(actionCommand))
            calculate('-');
          else if ("Multiply".equals(actionCommand))
            calculate('*');
          else if ("Divide".equals(actionCommand))
            calculate('/');
        else if (e.getSource() instanceof JMenuItem) {
          // Handle menu item events
          if ("Add".equals(actionCommand))
            calculate('+');
          else if ("Subtract".equals(actionCommand))
            calculate('-');
          else if ("Multiply".equals(actionCommand))
            calculate('*');
          else if ("Divide".equals(actionCommand))
            calculate('/');
          else if ("Close".equals(actionCommand))
            System.exit(0);
      /** Calculate and show the result in jtfResult */
      private void calculate(char operator) {
        // Obtain Number 1 and Number 2
        int num1 = (Integer.parseInt(jtfNum1.getText().trim()));
        int num2 = (Integer.parseInt(jtfNum2.getText().trim()));
        int result = 0;
        // Perform selected operation
        switch (operator) {
          case '+': result = num1 + num2;
                    break;
          case '-': result = num1 - num2;
                    break;
          case '*': result = num1 * num2;
                    break;
          case '/': result = num1 / num2;
        // Set result in jtfResult
        jtfResult.setText(String.valueOf(result));
    Mortgage applet code....
    // MortgageApplet.java: Applet for computing mortgage payments
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.TitledBorder;
    public class MortgageApplet extends JApplet
      implements ActionListener {
      // Declare and create text fields for interest rate
      // year, loan amount, monthly payment, and total payment
      private JTextField jtfAnnualInterestRate = new JTextField();
      private JTextField jtfNumOfYears = new JTextField();
      private JTextField jtfLoanAmount = new JTextField();
      private JTextField jtfMonthlyPayment = new JTextField();
      private JTextField jtfTotalPayment = new JTextField();
      // Declare and create a Compute Mortgage button
      private JButton jbtComputeMortgage = new JButton("Compute Mortgage");
      /** Initialize user interface */
      public void init() {
        // Set properties on the text fields
        jtfMonthlyPayment.setEditable(false);
        jtfTotalPayment.setEditable(false);
        // Right align text fields
        jtfAnnualInterestRate.setHorizontalAlignment(JTextField.RIGHT);
        jtfNumOfYears.setHorizontalAlignment(JTextField.RIGHT);
        jtfLoanAmount.setHorizontalAlignment(JTextField.RIGHT);
        jtfMonthlyPayment.setHorizontalAlignment(JTextField.RIGHT);
        jtfTotalPayment.setHorizontalAlignment(JTextField.RIGHT);
        // Panel p1 to hold labels and text fields
        JPanel p1 = new JPanel();
        p1.setLayout(new GridLayout(5, 2));
        p1.add(new Label("Annual Interest Rate"));
        p1.add(jtfAnnualInterestRate);
        p1.add(new Label("Number of Years"));
        p1.add(jtfNumOfYears);
        p1.add(new Label("Loan Amount"));
        p1.add(jtfLoanAmount);
        p1.add(new Label("Monthly Payment"));
        p1.add(jtfMonthlyPayment);
        p1.add(new Label("Total Payment"));
        p1.add(jtfTotalPayment);
        p1.setBorder(new
          TitledBorder("Enter interest rate, year and loan amount"));
        // Panel p2 to hold the button
        JPanel p2 = new JPanel();
        p2.setLayout(new FlowLayout(FlowLayout.RIGHT));
        p2.add(jbtComputeMortgage);
        // Add the components to the applet
        getContentPane().add(p1, BorderLayout.CENTER);
        getContentPane().add(p2, BorderLayout.SOUTH);
        // Register listener
        jbtComputeMortgage.addActionListener(this);
      /** Handle the "Compute Mortgage" button */
      public void actionPerformed(ActionEvent e) {
        if (e.getSource() == jbtComputeMortgage) {
          // Get values from text fields
          double interest = (Double.valueOf(
            jtfAnnualInterestRate.getText())).doubleValue();
          int year =
            (Integer.valueOf(jtfNumOfYears.getText())).intValue();
          double loan =
            (Double.valueOf(jtfLoanAmount.getText())).doubleValue();
          // Create a mortgage object
          Mortgage m = new Mortgage(interest, year, loan);
          // Display monthly payment and total payment
          jtfMonthlyPayment.setText(String.valueOf(m.monthlyPayment()));
          jtfTotalPayment.setText(String.valueOf(m.totalPayment()));
    }

    Does it have to be an applet?
    If you want the same behaviour as in the code with traffic lights, change
    class MortgageApplet extends JApplet implements ActionListener {
    to
    class MortgageApplet extends JFrame implements ActionListener {
    and change
    public void init() {
    to
    public MortgageApplet() {                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Moving a label in a panel using keyboard

    Hello,
    I have a component in a panel. The panel has got vertical and horizontal scroll bars. I need to move the label using the arrow keys on the key board. It only works for VK_LEFT AND VK_UP and when I try to move the label DOWN or RIGHT, the scroll bars move. I need to hold the CTRL+ARROW KEY to get the functionality.
    How do I over come this type of error? i.e I dont want to hold the CTRL key and I want only the arrow keys to do the work.
    Thanks

    Hi,
    Can you please correct this code? I can move the label UP and LEFT but when I move down or right, the scroll pane is moving. Just Click on the label and then try to move the label. Any ideas would help.
    Thanks
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    public class MoveLabel extends JFrame
         JLabel label;
         public MoveLabel()
              label = new JLabel(new ImageIcon("copy.gif"));
              label.setBounds(20,30,16,19);
              label.addKeyListener(new KeyAdapter()
                   public void keyPressed(KeyEvent ke)
                        if(ke.getKeyCode() == KeyEvent.VK_DOWN)
                             label.setLocation(label.getX(),label.getY()+1);
                             repaint();
                        if(ke.getKeyCode() == KeyEvent.VK_UP)
                             label.setLocation(label.getX(),label.getY()-1);
                             repaint();
                        if(ke.getKeyCode() == KeyEvent.VK_LEFT)
                             label.setLocation(label.getX()-1,label.getY());
                             repaint();
                        if(ke.getKeyCode() == KeyEvent.VK_RIGHT)
                             label.setLocation(label.getX()+1,label.getY());
                             repaint();
              label.addMouseListener(new MouseAdapter()
                   public void mouseClicked(MouseEvent me)
                         if(me.getClickCount() == 1)
                              boolean dd = label.isOptimizedDrawingEnabled();
                              boolean ff = label.requestFocusInWindow();
                              repaint();
              JPanel p = new JPanel();
              p.setPreferredSize(new Dimension(2000,1000));
              p.setLayout(null);
              p.add(label);
              JScrollPane js = new JScrollPane(p);
              getContentPane().add(js);
         public static void main(String args[])
              MoveLabel frame = new MoveLabel();
              frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
              frame.setSize(300,300);
              frame.setVisible(true);
    }

  • Want to show a "Please Wait" message while processing

    Hi,
    I'm developing an image-processing tutorial applet where the user selects an image and then sets some parameters before pressing an update button which will run a JPEG compression on the image and show the compressed image.
    The compression takes a few seconds, so I want the program to show an image saying "Please wait" in the position that the compressed image will appear while the compression is done.
    Here is the relevant code:
    public void paint (Graphics g) {
      if (updating) {
        updating = false;
        g.setColor(getBackground ());
        g.fillRect(575, 370, 250, 250); //clear the area where the image will appear
        g.setColor(Color.white);
        g.drawImage(updatingImg, 575, 370, 250, 250, this); //updatingImg just displays a "Please Wait" message
        doImage = true;
      if (doImage) {
        doImage = false;
        //perform the compression to get the new image and then show it
        newImg = imagetest.compressImage(origImg, quantizationMat);          
        g.setColor(getBackground ());
        g.fillRect(575, 370, 250, 250);
        g.setColor(Color.white);
        g.drawImage(newImg, 575, 370, 250, 250, this);
    public void actionPerformed(ActionEvent evt) {
      if (evt.getSource() == update){
        //perform some error checking
        if (errorFound == false){
          updating = true;
          repaint();
    }The problem is that the "Please wait" image never gets shown.. while the compression is carried out that part of the screen remains blank and then the new image is shown.
    Can anyone tell me how to fix this?
    Thanks.

    Never mind, I've figured it out.. needed to put the time consuming code in a new thread.

  • Aminated gifs only showing the last frame on the 2nd time of viewing

    I have 2 animated gifs and on pressing a button i am changing between the 2 on te first click the animated gif runs sucessfully and clicking the button again the 2nd animated gif runs sucessfully. However when i go to run the first animated gif again it only shows the last frame and this continues no matter how many times you press the button. Is there any way of getting it to start from the first frame. By the way just in case it makes a difference both the animated gifs run once they do not continously keep going and that is how i want them to be.

    public void mousePressed(MouseEvent e){
         if(corner.contains(e.getX(),e.getY())){
         if(reversed){
              setImageFile(gui.getFrontImage());
                   gui.setComponents(true);
                   reversed = false;
         else{
              setImageFile(gui.getBackImage());
                   gui.setComponents(false);
                   reversed = true;
         repaint();
    public void setImageFile(java.lang.String imageFile) {
         fieldImageFile = imageFile;
    /* Get and download the image for the new postcard background */
    backgroundImage = Toolkit.getDefaultToolkit().getImage( fieldImageFile );
         MediaTracker mt = new MediaTracker( this );
         mt.addImage( backgroundImage, 0 );
         try{     
              mt.waitForID( 0 );          
         catch( InterruptedException ie )
         repaint();
         mt.removeImage(backgroundImage, 0);
    public void paint(Graphics g)
    {     if( backgroundImage != null )
         g.drawImage( backgroundImage, 0, 0, this );
    so basically i press an srea area on the screen and every time i do it alternates between these 2 animated gifs gui.getBackImage() just returns te string of the animated gif file. I've checked to make sure that a new instance of the media tracker is being created each time and it is so i'm not really sure where the problem is!!

  • Setting Selection of JTree?

    I have a TreeSelectionListener that calls a method for reading in data, when clicking on a treenode (The Method-call is in valueChanged() ).
    I'd like to select the selected node in another part of my program to read in the data again. (Like a reload in an Internet Browser)
    I tried the following but without success:
    tree.setSelectionPath(tree.getSelectionPath()); //this code has no effect
    tree.repaint();
    Thanks for any help!

    The setSelectionPath() method will only call the listener method if there is a change in the path. Since you are passing the same selected path as the new selection path, there is no change in the path, hence no call to the listener method.
    Just as a workaround, you might just do the following and try out:
    Treepath path = tree.getSelectionPath();
    tree.setSelectionpath(null);
    tree.setSelectionPath(path);
    tree.revalidate();
    tree.repaint();
    Hope this helps!!

  • How can I pass variable's from one frame to other

    //This is the first frame where the value in the TextField
    //tf1 and tf2 are to be passed to 2nd Frame
    import java.awt.*;
    import java.awt.event.*;
    public class del extends Frame implements ItemListener,ActionListener
    public Panel p,p1,p2;
    public Button b,n;
    public Label l1,l2;
    public TextField tf1,tf2;
    public del()
    setLayout(new FlowLayout(FlowLayout.LEFT));
    Panel p=new Panel();
    n=new Button("Submit");
    p.add(n);
    add(p);
    l1=new Label(" Enter the Temperature : ");
    tf1=new TextField(5);
    p.add(l1);
    p.add(tf1);
    add("South",p);
    l2=new Label(" Enter the Compund ");
    tf2=new TextField("N-OCTANE",15);
    p1=new Panel();
    p1.add(l2);
    p1.add(tf2);
    add("South",p1);
    setSize(600,700);
    setVisible(true);
    public void itemStateChanged(ItemEvent ie)
    repaint();
    public void actionPerformed(ActionEvent a)
    if(a.getSource()==n)
    this.setVisible(false);
    new Finalput1();
    repaint();
    public static void main(String[]args)
    del d=new del();
    //2nd Frame which will appear on clicking submit button
    import java.awt.*;
    class del1 extends Frame
    public static double T;//value in 1st text field has to be stored in variable T
    String compd=" ";//value in 2nd textField has to be stored in this string
    TextField tf;
    public del1()
    setLayout(new FlowLayout());
    setSize(800,700);
    setVisible(true);
    public void paint(Graphics g)
    g.drawString(" INPUT DATA : - ",30,120);
    g.setColor(Color.black);
    g.drawString(" Component Name ="+compd,20,160);
    g.drawString(" Temperature of the Mixture ="+T,30,250);
    public static void main(String[]args)
    new del1();
    Pls help me.
    I will be happy if anyone help's me!

    Both your classes seem to be independent applications. (they are public, and they have their public static void main)
    Is this your intention? If so, your question is how to pass data from one application to another. That can be done in many ways, and it is a complicated issue. (if one application wants to pass data to another, you first have to find the other one, and if it isnt running you might want to start... - lots of things to think about.)
    If what you want to do is simply to pass data from one Frame to another, the matter is quite more simple.
    Here is a sample:
    import java.awt.event.*;
    import java.awt.*;
    public class F1 extends Frame implements ActionListener
    private F2 theOtherFrame;
    public F1()
    Button b;
    b=new Button("Action");
    b.addActionListener(this);
    add(b);
    setSize(100,100);
    setVisible(true);
    public void actionPerformed(ActionEvent e)
    if (theOtherFrame == null)
         theOtherFrame = new F2();
         theOtherFrame.setSize(100, 100);
    theOtherFrame.setSomeData("Her you have som data");
    theOtherFrame.setVisible(true);
    public static void main(String[] args)
    new F1();
    class F2 extends Frame
    private String strData;
    private Label lab;
    public void setSomeData(String str)
    lab.setText(str);
    repaint();
    public F2()
    lab = new Label();
    add(lab);

Maybe you are looking for

  • People tinted red in photos

    Ever since I have had my Rhyme, the skin on people is tinted red in the photo I've taken.  I've tried adjusting the settings, but I can't seem to make it go away.  It's very frustrating.  Am I the only one having this problem?

  • Different results between DD03L and the same structure in transaction SE11

    Hi Experts, I created a 'Z' structure and when I see this structure using trx se11 are displayed 10 fields but when I see this same structure through the table DD03L are displayed 15 fields. I created again 2 of 5 fields that were missing and the reg

  • Restricting Message type to 1 receiver-ALE

    Dear All We are using ALE scenario  where we ALE idocs from Finance box to HCM box. I am using searlization method for message type and generating idocs from change pointers using program RBDSE01. One of the message type (CREMAS) is being used in mor

  • Compilation error with sun workshop 6u2

    hi, i try to compile a systemc code with sun work shop 6u2 but the compilation generate this error Beginning generate/compile... Compilation may take a few seconds... please wait.......ucbcc: Warning: Option -YP,:/usr/ucblib:/usr/ensta/pack/SunWorkSh

  • Error in web reports

    Hi everyone, I am having problem in running a report in web. In bex it runs fine. i am able to see the selection list for one particular feild but not in web. I cleared my web cache but still it doesnt work. Any help? Thanks.