DrawPanel Draw JFrame

I need little help with thi code i need some feedback please here is the code:
import java.awt.Graphics;
import javax.swing.JPanel;
public class DrawPanel extends JPanel
     PostalAddress drawingAddress = new PostalAddress();//instantiate PostalAddress class to get to drawingAddress method
          public DrawPanel(PostalAddress myAddress)
               super();
               drawingAddress = myAddress;
               } //end of constructor          
          public void paintComponent(Graphics g)//paint method puts the data in drawingAddress on the panel
          super.paintComponent(g);
          drawingAddress.DrawAddress(g,25,35);
} // end paintCompnent
} // end class DrawPanel
// Application to display a DrawPanel.
import javax.swing.JFrame;
public class DrawPanelTest
public static void main( String args[] )
// create a panel that contains our drawing
DrawPanel panel = new DrawPanel();
// create a new frame to hold the panel
JFrame application = new JFrame();
// set the frame to exit when it is closed
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
application.add( panel ); // add the panel to the frame
application.setSize( 250, 250 ); // set the size of the frame
application.setVisible( true ); // make the frame visible
} // end main
} // end class DrawPanelTest
Thanks

Thanks for the reply.
Basically i want the orogrm to disply a postal address lebel in a frame or panel with name,street address ,city,state and zipcode+four digit that follow the zipcode
public class PostalAddress
   private String name;
   private String streetAddress;
   private String city;
   private String state;
   private String zipcode;
   private String plusFour;
  public void DrawAddress (Graphics  g,  int  x,  int  y)
      g.drawString(x,y,25,35);
      g.setClor(Color.black);
      this.name = name;
      this.streetAddress = streetAddress;
      this.city = city;  
      this.state = state;
      this.zipcode = zipcode;
      this.plusFour = plusFour;
}   // end class PostalAddress

Similar Messages

  • Where is the statusBar?

    Dear all,
    I want to show the statusBar at the bottom of the drawPanel,but where is it?
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.*;
    public class Pat extends JFrame {  
    private FlowLayout layout1;
    private DrawShape1 drawPanel;
    private JButton circleButton;
    private int xPos, yPos;
    final static int DrawShape_Circle = 1; // set up GUI
    public Pat() {  
    // create custom drawing area
    drawPanel = new DrawShape1();
    // set up ClearButton
    circleButton = new JButton( "Circle" );
    circleButton.addActionListener(
    new ActionListener() { // anonymous inner class        
    // draw a square
    public void actionPerformed( ActionEvent event ) {         
    System.out.println(xPos + " " + yPos);
    drawPanel.draw( DrawShape_Circle);
    } // end anonymous inner class
    ); // end call to addActionListener
    // set up panel containing parameter
    JPanel parameterPanel = new JPanel();
    layout1 = new FlowLayout();
    parameterPanel.setLayout(layout1);
    layout1.setAlignment( FlowLayout.CENTER);
    parameterPanel.add( circleButton ); // attach button panel & custom drawing area to content pane
    Container container = getContentPane();
    container.add( parameterPanel, BorderLayout.NORTH);
    container.add( drawPanel, BorderLayout.CENTER );
    setSize( 500, 500 );
    setVisible( true );
    } // end constructor CustomPanelTest
    public class DrawShape1 extends JPanel {  
    public final static int Circle = 1;
    private int shape;
    public int xPos,yPos;
    java.util.List originList;
    public int circleCount = 0;
    public DrawShape1() {
    originList = new ArrayList();
    setBackground(Color.white);
    // set up mouse listener
    addMouseListener(
    new MouseAdapter() { // anonymous inner class          
    // handle mouse press event
    public void mousePressed( MouseEvent event ) {           
    xPos = event.getX();
    yPos = event.getY();
    originList.add(circleCount, new String(xPos + "," + yPos));
    circleCount++;
    repaint();
    } // end anonymous inner class
    ); // end call to addMouseListener
    // use shape to draw an oval or rectangle
    public void paintComponent( Graphics g ) {     
    super.paintComponent( g );
    if ( shape == Circle )
    for (int j = 0; j < originList.size();j++){
    String xy = (String)originList.get(j);
    int comma = xy.indexOf(",");
    int x = Integer.parseInt(xy.substring(0, comma));
    int y = Integer.parseInt(xy.substring(comma + 1));
    g.drawOval( x, y, 60, 60 );
    // set shape value and repaint
    public void draw( int shapeToDraw ) {     
    shape = shapeToDraw;
    if(xPos == 0 && yPos == 0);
    return;
    // repaint();
    } // end class
    public static void main ( String args[] ) {   
    Pat app =new Pat();
    app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    Sorry, I had post a old version of the programme, The update one is post again.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.*;
    public class Circle extends JFrame implements MouseListener{  
    private FlowLayout layout1;
    private DrawShape1 drawPanel;
    private JButton circleButton;
    private int xPos, yPos;
    final static int DrawShape_Circle = 1; // set up GUI
    private JLabel statusBar;
    public Circle() {  
    // create custom drawing area
    drawPanel = new DrawShape1();
    // set up ClearButton
    circleButton = new JButton( "Circle" );
    circleButton.addActionListener(
    new ActionListener() { // anonymous inner class        
    // draw a square
    public void actionPerformed( ActionEvent event ) {         
    System.out.println(xPos + " " + yPos);
    drawPanel.draw( DrawShape_Circle);
    } // end anonymous inner class
    ); // end call to addActionListener
    // set up panel containing parameter
    JPanel parameterPanel = new JPanel();
    layout1 = new FlowLayout();
    parameterPanel.setLayout(layout1);
    layout1.setAlignment( FlowLayout.CENTER);
    parameterPanel.add( circleButton ); // attach button panel & custom drawing area to content pane
    JPanel statusPanel = new JPanel();
    statusPanel.setBackground(Color.PINK);
    statusBar = new JLabel("x" + xPos +" y" + yPos);
    statusPanel.add(statusBar);
    Container container = getContentPane();
    container.add( parameterPanel, BorderLayout.NORTH);
    container.add( drawPanel, BorderLayout.CENTER );
    container.add(statusPanel, BorderLayout.SOUTH);
    addMouseListener( this);
    setSize( 500, 500 );
    setVisible( true );
    } // end constructor CustomPanelTest
    public class DrawShape1 extends JPanel {  
    public final static int Circle = 1;
    private int shape;
    public int xPos,yPos;
    java.util.List originList;
    public int circleCount = 0;
    public DrawShape1() {
    originList = new ArrayList();
    setBackground(Color.white);
    // set up mouse listener
    addMouseListener(
    new MouseAdapter() { // anonymous inner class          
    // handle mouse press event
    public void mousePressed( MouseEvent event ) {           
    xPos = event.getX();
    yPos = event.getY();
    originList.add(circleCount, new String(xPos + "," + yPos));
    circleCount++;
    repaint();
    } // end anonymous inner class
    ); // end call to addMouseListener
    // use shape to draw an oval or rectangle
    public void paintComponent( Graphics g ) {     
    super.paintComponent( g );
    if ( shape == Circle )
    for (int j = 0; j < originList.size();j++){
    String xy = (String)originList.get(j);
    int comma = xy.indexOf(",");
    int x = Integer.parseInt(xy.substring(0, comma));
    int y = Integer.parseInt(xy.substring(comma + 1));
    g.drawOval( x, y, 60, 60 );
    // set shape value and repaint
    public void draw( int shapeToDraw ) {     
    shape = shapeToDraw;
    if(xPos == 0 && yPos == 0);
    return;
    // repaint();
    } // end class
    public static void main ( String args[] ) {   
    Pat app =new Pat();
    app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    /** Invoked when the mouse button has been clicked (pressed
    * and released) on a component.*/
    public void mouseClicked(MouseEvent e) {
    statusBar.setText("x" + xPos +" y" + yPos);
    /** Invoked when the mouse enters a component.*/
    public void mouseEntered(MouseEvent e) {
    /** Invoked when the mouse exits a component.*/
    public void mouseExited(MouseEvent e) {
    /** Invoked when a mouse button has been pressed on a component.*/
    public void mousePressed(MouseEvent e) {
    /** Invoked when a mouse button has been released on a component.*/
    public void mouseReleased(MouseEvent e) {
    }

  • The circle is not display

    Dear all
    Why the circle not display on the panel?
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class CustomPanel1 extends JFrame { 
    private final String list[] = { "Circle"};
    private FlowLayout layout1, layout3;
    private DrawShape drawPanel;
    private JComboBox shapeList;
    private JTextField textField1, textField2;
    public static int size;
    public CustomPanel1() {   
    // create custom drawing area
    drawPanel = new DrawShape();
    shapeList = new JComboBox(list);
    shapeList.setMaximumRowCount(3);
    //add ItemListener
    shapeList.addItemListener(
    new ItemListener(){
    // handle item state change event
    public void itemStateChanged (ItemEvent event) {                  
    if(event.getStateChange() == ItemEvent.SELECTED){
    // draw circle
    if( shapeList.getSelectedIndex() == 0){           
    DrawShape.shape = 0;
    drawPanel.draw( DrawShape.Circle);
    } // end if
    JPanel parameterPanel = new JPanel();
    layout1 = new FlowLayout();
    parameterPanel.setLayout(layout1);
    parameterPanel.setBackground( Color.PINK );
    layout1.setAlignment( FlowLayout.CENTER);
    parameterPanel.add( new JScrollPane(shapeList));
    JPanel textPanel = new JPanel();
    layout3 = new FlowLayout();
    parameterPanel.setLayout(layout3);
    textPanel.setBackground( Color.PINK );
    layout3.setAlignment( FlowLayout.CENTER);
    textField1 = new JTextField( "Size");
    textField1.setFont(new Font("Serif",Font.BOLD,14));
    textField1.setEditable (false);
    textField2 = new JTextField( "",6);
    textField2.setFont(new Font("Serif",Font.BOLD,14));
    // add ActionListener
    textField2.addActionListener(
    new ActionListener(){
    // handle action perform event
    public void actionPerformed (ActionEvent event) {         
    JTextField field = (JTextField)event.getSource();
    String entry = field.getText();
    size = Integer.parseInt(entry);
    } // end handle
    } // end anonymous inner class
    ); // end call to addActionListener
    textPanel.add(textField1, BorderLayout.NORTH);
    textPanel.add(textField2, BorderLayout.SOUTH);
    // set up the combine panel of parameterPanel and textPanel
    GridLayout gridLayout = new GridLayout();
    gridLayout.setRows(2);
    gridLayout.setColumns(1);
    JPanel combinPanel = new JPanel();
    combinPanel.setBackground( Color.PINK );
    combinPanel.setLayout(gridLayout);
    combinPanel.add(parameterPanel, BorderLayout.NORTH);
    combinPanel.add(textPanel, BorderLayout.SOUTH);
    Container container = getContentPane();
    container.add( combinPanel, BorderLayout.NORTH);
    container.add( drawPanel, BorderLayout.CENTER );
    // container.add( dataPanel, BorderLayout.SOUTH );
    setSize( 500, 500 );
    setVisible( true );
    } // end constructor CustomPanelTest
    // main
    public static void main ( String args[] ) {   
    CustomPanel1 app = new CustomPanel1();
    app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    } // end main
    } // end class CustomPanelTest
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class DrawShape extends JPanel {
    public final static int Circle = 0, Square = 1, Triangle = 2;
    public static int shape;
    public static int xPos,yPos;
    CustomPanel1 client;
    boolean shapeWasCreated = false;
    public DrawShape(){
    public DrawShape(CustomPanel1 customer){     
    this.client = customer;
    addMouseListener(
    new MouseAdapter() {  // anonymous inner class
    // handle mouse press event
    public void mousePressed( MouseEvent event )
    xPos = event.getX();
    yPos = event.getY();
    shapeWasCreated = true;
    repaint();
    } // end handle
    } // end anonymous inner class
    ); // end call to addMouseListener
    } // end method
    public void draw( int shapeToDraw )
    shape = shapeToDraw;
    repaint();
    } //end method
    } // end class
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class DrawCircle extends DrawShape {
    CustomPanel1 client;
    public static double circleArea, circlePerimeter;
    public DrawCircle(CustomPanel1 circleCustomer){     
    super(circleCustomer);
    this.client = circleCustomer;
    } // end method
    public void paintComponent( Graphics g )
    super.paintComponent( g );
    initializeShapeVariables();
    if ( shape == Circle ) {        
    g.drawOval(xPos ,yPos , CustomPanel1.size, CustomPanel1.size );
    } //end if
    private void initializeShapeVariables(){
    area = 0;
    perimeter = 0;
    circleArea = 0;
    circlePerimeter = 0;
    } // end method
    // set shape value and repaint
    public void draw( int shapeToDraw ) {    
    shape = shapeToDraw;
    repaint();
    } //end method
    } // end class

    First, try a system reset.  It cures many ills and it's quick, easy and harmless...
    Hold down the on/off switch and the Home button simultaneously until you see the Apple logo.  Ignore the "Slide to power off" text if it appears.  You will not lose any apps, data, music, movies, settings, etc.
    If the Reset doesn't work, try a Restore.  Note that it's nowhere near as quick as a Reset.  It could take well over an hour!  Connect via cable to the computer that you use for sync.  From iTunes, select the iPad/iPod and then select the Summary tab.  Follow directions for Restore and be sure to say "yes" to the backup.  You will be warned that all data (apps, music, movies, etc.) will be erased but, as the Restore finishes, you will be asked if you wish the contents of the backup to be copied to the iPad/iPod.  Again, say "yes."
    At the end of the basic Restore, you will be asked if you wish to sync the iPad/iPod.  As before, say "yes."  Note that that sync selection will disappear and the Restore will end if you do not respond within a reasonable time.  If that happens, only the apps that are part of the IOS will appear on your device.  Corrective action is simple -  choose manual "Sync" from the bottom right of iTunes.
    If you're unable to do the Restore, go into Recovery Mode per the instructions here.  Since you have chosen not to maintain a backup, Recovery Mode will result in complete loss of data.  Anything obtained from the iTunes Store can be downloaded again but everything else will be gone forever.

  • Client struggles

    I am working on a client that sents words or numbers to a server. It uses a GUI to enter everything. The problem is that I don't know how, with the way it is writtin right now, to get the words that I enter in the textfileds into the main method where the Output/Input streams are. I have been working on this for days, im sure i jsut need to move some stuff around, but If anyone could help me I would appreciate it thanks in advance
    (Sorry for any sloppyness I am terrible at cleaning up my code but i tried)
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.net.*;
    import java.io.*;
    public class clie extends JFrame implements ActionListener
         private JButton Connect, Quit, Lookup, Add, Remove;
         static String na;
         private JTextField Server, Port, Name, PNumber;
         static JTextArea ta=new JTextArea();
         static boolean tf=false;
         static boolean qu=false;
         static boolean co=false;
         clie()
              setTitle("geee");
              addWindowListener(new WindowAdapter()
              {  public void windowClosing(WindowEvent e){System.exit(0);}});
              JPanel nor=new JPanel();
              JPanel but=new JPanel();
              JPanel sou=new JPanel();
              JPanel mid=new JPanel();
              JPanel draw=new JPanel();
              draw=new DrawPanel();
              draw.setBackground(Color.RED);
              mid.add(draw);
              mid.setLayout(new GridLayout(3,1));
              nor.setBackground(Color.RED);
              but.setBackground(Color.RED);
              sou.setLayout(new GridLayout(2,1));
              //JTextArea ta=new JTextArea();
              sou.add(ta);
              but.setLayout(new GridLayout(2,4,25,50));
              Server=new JTextField(30);
              but.add(Server);
              Port=new JTextField(30);
              but.add(Port);
              Name=new JTextField(30);
              but.add(Name);
              PNumber=new JTextField(30);
              but.add(PNumberServe);
              Connect=new JButton("Connect");but.add(Connect);
              Connect.addActionListener(new ConnBut());
              Quit=new JButton("Quit");sou.add(Quit);
              Quit.addActionListener(new QBut());
              Lookup=new JButton("Lookup");but.add(Lookup);
              Lookup.addActionListener(new LookBut());
              Add=new JButton("Add");but.add(Add);
              Add.addActionListener(new AddBut());
              Remove=new JButton("Remove");but.add(Remove);
              Remove.addActionListener(nwe RemBut());
              mid.add(but);
              mid.add(sou);
              getContentPane().add(mid);
    class DrawPanel extends JPanel
              public void paintComponent(Graphics g)
                   super.paintComponent(g);
                   Font font=new Font("Serif",Font.BOLD,12);
                   g.setFont(font);
                   g.setColor(Color.BLACK);
                   g.drawString("Server",10,90);
                   g.drawString("Port",160,90);
                   g.drawString("Name",310,90);
                   g.drawString("Phone Number",470,90);
         }import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.net.*;
    import java.io.*;
    public class clie extends JFrame implements ActionListener
         private JButton Connect, Quit, Lookup, Add, Remove;
         static String na;
         private JTextField Server, Port, Name, PNumber;
         static JTextArea ta=new JTextArea();
         static boolean tf=false;
         static boolean qu=false;
         static boolean co=false;
         clie()
              setTitle("geee");
              addWindowListener(new WindowAdapter()
              {  public void windowClosing(WindowEvent e){System.exit(0);}});
              JPanel nor=new JPanel();
              JPanel but=new JPanel();
              JPanel sou=new JPanel();
              JPanel mid=new JPanel();
              JPanel draw=new JPanel();
              draw=new DrawPanel();
              draw.setBackground(Color.RED);
              mid.add(draw);
              mid.setLayout(new GridLayout(3,1));
              nor.setBackground(Color.RED);
              but.setBackground(Color.RED);
              sou.setLayout(new GridLayout(2,1));
              //JTextArea ta=new JTextArea();
              sou.add(ta);
              but.setLayout(new GridLayout(2,4,25,50));
              Server=new JTextField(30);
              but.add(Server);
              Port=new JTextField(30);
              but.add(Port);
              Name=new JTextField(30);
              but.add(Name);
              PNumber=new JTextField(30);
              but.add(PNumberServe);
              Connect=new JButton("Connect");but.add(Connect);
              Connect.addActionListener(new ConnBut());
              Quit=new JButton("Quit");sou.add(Quit);
              Quit.addActionListener(new QBut());
              Lookup=new JButton("Lookup");but.add(Lookup);
              Lookup.addActionListener(new LookBut());
              Add=new JButton("Add");but.add(Add);
              Add.addActionListener(new AddBut());
              Remove=new JButton("Remove");but.add(Remove);
              Remove.addActionListener(nwe RemBut());
              mid.add(but);
              mid.add(sou);
              getContentPane().add(mid);
    class DrawPanel extends JPanel
              public void paintComponent(Graphics g)
                   super.paintComponent(g);
                   Font font=new Font("Serif",Font.BOLD,12);
                   g.setFont(font);
                   g.setColor(Color.BLACK);
                   g.drawString("Server",10,90);
                   g.drawString("Port",160,90);
                   g.drawString("Name",310,90);
                   g.drawString("Phone Number",470,90);
    public static void main(String[]args)
              JFrame jf=new clie();
              jf.setSize(600,400);
              jf.setVisible(true);
              String hostname;
              int port=7007;
              if(args.length==1) hostname=args[0];
              else
              {     System.out.println("this is a client");
              return;
              try{
              Socket sock=new Socket(hostname, port);
              String server=sock.getInetAddress().getHostName();
              System.out.println("Conected to server "+server);
              co=true;
              InputStream in=sock.getInputStream();
              OutputStream out=sock.getOutputStream();
              ObjectInputStream inStrm=new ObjectInputStream(in);
              ObjectOutputStream outStrm=new ObjectOutputStream(out);
              BufferedReader userInput=new BufferedReader(new InputStreamReader(System.in));
              String start=inStrm.readUTF();
              String aLine=userInput.readLine();
              sock.close();
              catch(UnknownHostException e)
              {     System.out.println(e);}
              catch(IOException e)
              {     System.out.println(e);}
    public void actionPerformed(ActionEvent e)
              Object source=e.getSource();
         if (source instanceof JButton)
              JButton pushed = (JButton)(e.getSource());}
    class LookBut implements ActionListener
         public void actionPerformed(ActionEvent e)
              if(co==false)
                   ta.setText("No connection in place");
              else
              String na=Name.getText();
    class QBut implements ActionListener
         public void actionPerformed(ActionEvent e)
              Object source=e.getSource();
              if (source instanceof JButton)
              System.exit(0);
              JButton pushed = (JButton)(e.getSource());
                   qu=true;
    class ConnBut implements ActionListener
         public void actionPerformed(ActionEvent e)
              if(co==false)
                   ta.setText("Server Does not Respond");
    class AddBut implements ActionListener
         public void actionPerformed(ActionEvent e)
              if (co==false)
                   ta.setText("No Connection in Place");
    class RemBut implements ActionListener
         public void actionPerformed(ActionEvent e)
              if(co==false)
                   ta.setText("No Connection in Place");
    public static void main(String[]args)
              JFrame jf=new clie();
              jf.setSize(600,400);
              jf.setVisible(true);
              String hostname;
              int port=7007;
              if(args.length==1) hostname=args[0];
              else
              {     System.out.println("this is a client");
              return;
              try{
              Socket sock=new Socket(hostname, port);
              String server=sock.getInetAddress().getHostName();
              System.out.println("Conected to server "+server);
              co=true;
              InputStream in=sock.getInputStream();
              OutputStream out=sock.getOutputStream();
              ObjectInputStream inStrm=new ObjectInputStream(in);
              ObjectOutputStream outStrm=new ObjectOutputStream(out);
              BufferedReader userInput=new BufferedReader(new InputStreamReader(System.in));
              String start=inStrm.readUTF();
              String aLine=userInput.readLine();
              sock.close();
              catch(UnknownHostException e)
              {     System.out.println(e);}
              catch(IOException e)
              {     System.out.println(e);}
    public void actionPerformed(ActionEvent e)
              Object source=e.getSource();
         if (source instanceof JButton)
              JButton pushed = (JButton)(e.getSource());}
    class LookBut implements ActionListener
         public void actionPerformed(ActionEvent e)
              if(co==false)
                   ta.setText("No connection in place");
              else
              String na=Name.getText();
    class QBut implements ActionListener
         public void actionPerformed(ActionEvent e)
              Object source=e.getSource();
              if (source instanceof JButton)
              System.exit(0);
              JButton pushed = (JButton)(e.getSource());
                   qu=true;
    class ConnBut implements ActionListener
         public void actionPerformed(ActionEvent e)
              if(co==false)
                   ta.setText("Server Does not Respond");
    class AddBut implements ActionListener
         public void actionPerformed(ActionEvent e)
              if (co==false)
                   ta.setText("No Connection in Place");
    class RemBut implements ActionListener
         public void actionPerformed(ActionEvent e)
              if(co==false)
                   ta.setText("No Connection in Place");
    }

    sorry that didn't even compile here this does
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.net.*;
    import java.io.*;
    public class clie extends JFrame implements ActionListener
         private JButton Connect, Quit, Lookup, Add, Remove;
         static String na;
         private JTextField Server, Port, Name, PNumber;
         static JTextArea ta=new JTextArea();
         static boolean tf=false;
         static boolean qu=false;
         static boolean co=false;
         clie()
              setTitle("geee");
              addWindowListener(new WindowAdapter()
              {  public void windowClosing(WindowEvent e){System.exit(0);}});
              JPanel nor=new JPanel();
              JPanel but=new JPanel();
              JPanel sou=new JPanel();
              JPanel mid=new JPanel();
              JPanel draw=new JPanel();
              draw=new DrawPanel();
              draw.setBackground(Color.RED);
              mid.add(draw);
              mid.setLayout(new GridLayout(3,1));
              nor.setBackground(Color.RED);
              but.setBackground(Color.RED);
              sou.setLayout(new GridLayout(2,1));
              //JTextArea ta=new JTextArea();
              sou.add(ta);
              but.setLayout(new GridLayout(2,4,25,50));
              Server=new JTextField(30);
              but.add(Server);
              Port=new JTextField(30);
              but.add(Port);
              Name=new JTextField(30);
              but.add(Name);
              PNumber=new JTextField(30);
              but.add(PNumber);
              Connect=new JButton("Connect");but.add(Connect);
              Connect.addActionListener(new ConnBut());
              Quit=new JButton("Quit");sou.add(Quit);
              Quit.addActionListener(new QBut());
              Lookup=new JButton("Lookup");but.add(Lookup);
              Lookup.addActionListener(new LookBut());
              Add=new JButton("Add");but.add(Add);
              Add.addActionListener(new AddBut());
              Remove=new JButton("Remove");but.add(Remove);
              Remove.addActionListener(new RemBut());
              mid.add(but);
              mid.add(sou);
              getContentPane().add(mid);
    class DrawPanel extends JPanel
              public void paintComponent(Graphics g)
                   super.paintComponent(g);
                   Font font=new Font("Serif",Font.BOLD,12);
                   g.setFont(font);
                   g.setColor(Color.BLACK);
                   g.drawString("Server",10,90);
                   g.drawString("Port",160,90);
                   g.drawString("Name",310,90);
                   g.drawString("Phone Number",470,90);
    public static void main(String[]args)
              JFrame jf=new clie();
              jf.setSize(600,400);
              jf.setVisible(true);
              String hostname;
              int port=7007;
              if(args.length==1) hostname=args[0];
              else
              {     System.out.println("this is a client");
              return;
              try{
              Socket sock=new Socket(hostname, port);
              String server=sock.getInetAddress().getHostName();
              System.out.println("Conected to server "+server);
              co=true;
              InputStream in=sock.getInputStream();
              OutputStream out=sock.getOutputStream();
              ObjectInputStream inStrm=new ObjectInputStream(in);
              ObjectOutputStream outStrm=new ObjectOutputStream(out);
              BufferedReader userInput=new BufferedReader(new InputStreamReader(System.in));
              String start=inStrm.readUTF();
              String aLine=userInput.readLine();
              sock.close();
              catch(UnknownHostException e)
              {     System.out.println(e);}
              catch(IOException e)
              {     System.out.println(e);}
    public void actionPerformed(ActionEvent e)
              Object source=e.getSource();
         if (source instanceof JButton)
              JButton pushed = (JButton)(e.getSource());}
    class LookBut implements ActionListener
         public void actionPerformed(ActionEvent e)
              if(co==false)
                   ta.setText("No connection in place");
              else
              String na=Name.getText();
              ta.setText(na);
    class QBut implements ActionListener
         public void actionPerformed(ActionEvent e)
              Object source=e.getSource();
              if (source instanceof JButton)
              System.exit(0);
              JButton pushed = (JButton)(e.getSource());
                   qu=true;
    class ConnBut implements ActionListener
         public void actionPerformed(ActionEvent e)
              if(co==false)
                   ta.setText("Server Does not Respond");
    class AddBut implements ActionListener
         public void actionPerformed(ActionEvent e)
              if (co==false)
                   ta.setText("No Connection in Place");
    class RemBut implements ActionListener
         public void actionPerformed(ActionEvent e)
              if(co==false)
                   ta.setText("No Connection in Place");
    }

  • How can i make this game to be over in 3 minutes?

    i'm really a total beginner, and this is the race game code for my school assignment.
    How can i possibly make this game to be over in 3 minutes?
    It says "game over" when you hit 20 cars.
    I want to make it say "you've made it!" or something when they survive for 3 minutes with less than 20 crashes.
    please help! T.T
    import java.awt.*;
    import java.applet.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.Timer;
    public class BugRace extends Applet implements KeyListener, Runnable{
      Image buff;
      Canvas Panel;
      Graphics2D gPanel;
      Graphics2D gBuffer;
      Bug redBug;
      Bug[] rivals=new Bug[20];
      Button StartButton;
      //Button StopButton;
      Thread game;
      Timer time;
      private boolean loop=true;
      Dimension dim=new Dimension(200, 300);
      private int road;
      Random rnd=new Random();
      private int crash = 0;
      public void init(){     
        prepareResource();
        setBackground(Color.gray);
        setSize(400,400);
        initPanel();
        add(Panel);
        // Start Button
        StartButton=new Button("START");
        add(StartButton);
        StartButton.addActionListener(new ActionListener(){
          public void actionPerformed(ActionEvent ae){
            // request focus for Panel to get key event
            Panel.requestFocus();
            if(!game.isAlive()){
                 game.start();}else if(game.isAlive()){
                 game.start();}
        /*StopButton=new Button("STOP");
        add(StopButton);
        //StopButton.addActionListener(new ActionListener(){
         public void actionPerformed(ActionEvent ae){
            //Panel.requestFocus();
              if(game.isAlive())
                   game.stop();}
      public void prepareResource(){ //load bug images
        Image imgRed=getImage(getCodeBase(),"redbug.gif");
        Image imgBlue=getImage(getCodeBase(),"bluebug.gif");
        Image imgYellow=getImage(getCodeBase(),"yellowbug.gif");
        Image imgPurple=getImage(getCodeBase(),"purplebug.gif");
        MediaTracker mt=new MediaTracker(this);
        try{
          mt.addImage(imgRed, 0);
          mt.addImage(imgBlue, 1);
          mt.addImage(imgYellow, 2);
          mt.addImage(imgPurple, 3);
          mt.waitForAll();
        }catch(Exception e){}
        buff=createImage((int)dim.getWidth(), (int)dim.getHeight());
        gBuffer=(Graphics2D)buff.getGraphics();
        redBug=new Bug(imgRed, 80,250, dim);  // user's bug
        for(int i=0;i<10;i++){
           rivals=new Bug(imgBlue, 0, 0); // rival blue bug
    for(int i=5;i<rivals.length;i++){
    rivals[i]=new Bug(imgYellow, 0, 0); // rival yellow bug
    for(int i=10;i<rivals.length;i++){
    rivals[i]=new Bug(imgPurple, 0, 0); // rival purple bug
    for(int i=0;i<rivals.length;i++){  // set locations for rival bugs
    setrivals(i);
    game=new Thread(this); // game thread for controlling
    public void stop(){
    loop=false; // stop the thread
    public void run(){
    while(loop){
    drawPanel(); // draw game screen
    try{ Thread.sleep(50);}catch(Exception e){}
    public void initPanel(){    // initialize the panel
    Panel=new Canvas(){
    public void paint(Graphics g){
    if(gPanel==null){
         gPanel=(Graphics2D)Panel.getGraphics();
    drawPanel();
    Panel.setSize(dim); // size of the panel
    Panel.addKeyListener(this); //add keylistener for the game
    // set rival bugs' location randomly, and make them not intersect each other
    void setrivals(int en){ 
    int x, y;
    next:while(true){
    x=rnd.nextInt((int)dim.getWidth()-rivals[en].getWidth());
    y=-rnd.nextInt(5000)-200;
    // if (x,y) intersect to each other, go to next
    for(int j=0;j<rivals.length;j++){
    if(j!=en && rivals[j].collision(x, y))continue next;
    // set (x, y) as en rival bug's location and exit from while loop.
    rivals[en].setLocation(x, y);
    break;
    void check(Bug en){       // check if bugs collides
    if(redBug.collision(en)){        // if collide,
    if(redBug.getX()>en.getX()){  // if rival bug is on the left side from user's,            
    en.move(-10, 0); // move rival bug in 10 to the left
    redBug.move(10, 0); // move user's bug in 10 to the right
    crash++;          //add # of crash
    else{                     // if rival bug is on the right side from user's,
    en.move(10,0); // move rival bug in 10 to the right
    redBug.move(-10, 0); // move user's bug in 10 to the left
    crash++;          //add # of crash
    synchronized void drawPanel(){                        // draw panel
    gBuffer.clearRect(0, 0, (int)dim.getWidth(), (int)dim.getHeight()); //clear buffer
    gBuffer.setPaint(new Color(0, 150, 0));          //fill background in green
    gBuffer.fillRect(0, 0, (int)dim.getWidth(), (int)dim.getHeight());
    drawRoad(); // draw the road
    // draw rival bugs moving down
    for(int i=0;i<rivals.length;i++){
    rivals[i].move(0, 15); // move rival bugs down
    rivals[i].draw(gBuffer, Panel); // draw the bugs in panel
    if(rivals[i].getY()>dim.getHeight()){ //if a rival bug is out of panel
         setrivals(i);} // set it at initial position
              check(rivals[i]); // check if they intersect
    redBug.draw(gBuffer, Panel); // draw user's bug
    gPanel.drawImage(buff, 0,0, Panel); // draw buffer in panel
    if(crash<20){
         gPanel.setFont(new Font(null,Font.BOLD,15));
         gPanel.drawString("crash:"+crash,30, 30);}
    else{
         gPanel.setFont(new Font(null,Font.BOLD,15));
         gPanel.drawString("crash:"+crash,30, 30);
         gPanel.setFont(new Font(null,Font.BOLD,20));
         gPanel.drawString("Game Over", 50, 100);
              gPanel.dispose();
    void drawRoad(){ // draw yellow center line
    road+=80;
    gBuffer.setPaint(Color.yellow);
    gBuffer.fillRect((int)dim.getWidth()/2, road,10,150);
    if(road>=dim.getHeight()){ //if the line goes lower than  panel
         road=-150;                    //move it up again
    }else if(crash >20){
         road=0;
    public void keyPressed(KeyEvent ke){       
    if(ke.getKeyCode()==KeyEvent.VK_LEFT){     // if left arrow is pressed,
    redBug.move(-20,0); // the bug moves to the left
    else if(ke.getKeyCode()==KeyEvent.VK_RIGHT){  // if right arrow is pressed
    redBug.move(20,0); // the bug moves to the right
    public void keyReleased(KeyEvent ke){}
    public void keyTyped(KeyEvent ke){}

    import java.util.Timer;
    import java.util.TimerTask;
    public class Test {
        public static void main (String[] args) {
            final Timer timer = new Timer ();
            System.out.println ("I'm gonna do something in 5 seconds.");
            timer.schedule (new TimerTask () {
                public void run () {
                    System.out.println ("Time's up !");
                    timer.cancel ();
            }, 5000);
    }if you want to display the time left it's better to make your own Thread that updates a "timeleft variable:
    {code}
    public class Test {
    //set the time Left to 3 mins.
    private long secondsLeft = 3 * 60;
    public Test () {
    new Thread (new Runnable () {
    public void run () {
    try {
    while (secondsLeft > 0) {
    //Let's update the timer every second.
    Thread.sleep (1000);
    secondsLeft = secondsLeft - 1;
    System.out.println ("Time left: " + (secondsLeft / 60) + ":" + (secondsLeft % 60));
    System.out.println ("Grats !");
    } catch (InterruptedException e) {}
    }).start ();
    public static void main (String[] args) {
    new Test ();
    {code}

  • User Name/Password class for MySQL -- it almost works ... almost

    I'm working on creating a user name/password class called Login that will get the information that is required to log into a MySQL database (This program is not an applet, by the way).
    In brief this class does following:
    * It creates a JFrame with JTextFields and a JPasswordField and a login button. All compents have ActionListener.
    * I am able to read the info from the fields (I tested this using System.out.println)
    * Another program calls this Login class (see code at end of post)
    I want the program to close the frame (I figured that out) and return the values to the calling program. I can't figure out how to have it return a cat string ( of "host|port|username|password" ). If this was one large piece of java source code, it'd be a piece of cake, but the code is broken into several java source components and I'm trying to figure out how to get the ActionListener to return the string.
    One web page mentioned using an ejector but haven't been able to find any information about that. Another thought was maybe putting some kind of code in the windowClosing event for the Login class.
    Ex:
      public void windowClosing(WindowEvent e)
         setVisible(false);
         dispose();
         // return value to calling function somehow
      }Any help would be greatly appreciated. I'm teaching myself this so I'm sure there are better ways to do the JFrame formatting, but here's the code anyway. I'll post the additional changes (in context) when I get a working version of this.
    //Login.java
    import java.awt.*;
    import java.awt.event.*;
    import java.lang.Object;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import javax.swing.*;
    import javax.swing.border.TitledBorder;
    public class Login extends JFrame implements ActionListener
       JTextField serverHost;
       IntTextField port;
       JTextField userName;
       JPasswordField password;
       JButton login;
       Canvas canvas;
       String ServerHost_String;
       String Port_String;
       String UserName_String;
       String Password_String;
       String Login_String;
       Font ssb10 = new Font("Sans Serif", Font.BOLD,10);
       Font hb30 = new Font("Helvetica", Font.BOLD,30);
       Integer rc;
       //public void init()
       public Login()
          // Set up buttons
          login = new JButton("Login");
          serverHost = new JTextField("localhost",10);
          port = new IntTextField(3306, 4);
          userName = new JTextField("root",10);
          password = new JPasswordField(10);
          // Draw Screen
          Canvas horizontal_spacer1 = new Horizontal_Spacer(420,15);
          Canvas horizontal_spacer2 = new Horizontal_Spacer(420,15);
          Canvas horizontal_spacer3 = new Horizontal_Spacer(420,15);
          Canvas horizontal_spacerA = new Horizontal_Spacer(100,45);
          Canvas horizontal_spacerB = new Horizontal_Spacer(100,45);
          Canvas vertical_spacer1 = new Vertical_Spacer();
          Canvas vertical_spacer2 = new Vertical_Spacer();
          Canvas vertical_spacerA = new Vertical_Spacer();
          Canvas vertical_spacerB = new Vertical_Spacer();
           * Top
          canvas = new Top_Logo();
          JPanel top = new JPanel();
          top.add(canvas);
          //top.add(horizontal_spacer1);
          add(BorderLayout.NORTH,top);
           * Middle
          Box p1 = Box.createHorizontalBox();
          Box p2 = Box.createHorizontalBox();
          Box p3 = Box.createHorizontalBox();
          JPanel bp = new JPanel();
          JLabel rbp = new JLabel();
          p1.setFont(ssb10);
          p2.setFont(ssb10);
          p3.setFont(ssb10);
          p1.setAlignmentX(Component.LEFT_ALIGNMENT);
          bp.setAlignmentX(Component.LEFT_ALIGNMENT);
          p3.setAlignmentX(Component.LEFT_ALIGNMENT);
          rbp.setLayout(new BoxLayout(rbp,BoxLayout.X_AXIS));
          rbp.setBorder(new TitledBorder("Connection to MySQL Server Instance"));
          JLabel lString = new JLabel("Server Host: ");
          lString.setFont(ssb10);
          // Setup server Host and Port JPanel
          p1.add(lString);
          p1.add(serverHost);
          lString = new JLabel("  Port: ");
          lString.setFont(ssb10);
          p1.add(lString);
          p1.add(port);
          // Setup username JPanel
          lString = new JLabel("Username:    ");
          lString.setFont(ssb10);
          p2.add(lString);
          p2.add(userName);
          // Setup password JPanel
          lString = new JLabel("Password:    ");
          lString.setFont(ssb10);
          p3.add(lString);
          p3.add(password);
          // Draw the big Jpanel
          //bp.add(horizontal_spacerA);
          bp.add(p1);
          bp.add(p2);
          bp.add(p3);
          //bp.add(horizontal_spacerB);
          rbp.add(vertical_spacerA);
          rbp.add(bp);
          rbp.add(vertical_spacerB);
          add(BorderLayout.WEST,vertical_spacer1);
          add(BorderLayout.CENTER,rbp);
          add(BorderLayout.EAST,vertical_spacer2);
          // Bottom
          JPanel bot = new JPanel();
          bot.setLayout(new BoxLayout(bot,BoxLayout.Y_AXIS));
          bot.add(horizontal_spacer2);
          bot.add(login);
          bot.add(horizontal_spacer3);
          add(BorderLayout.SOUTH,bot);
          // Draw JFrame
          setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          setSize(420,280);
          setResizable(false);
          setVisible(true);
          // Listen for buttons being clicked
          login.addActionListener(this);
          serverHost.addActionListener(this);
          userName.addActionListener(this);
          port.addActionListener(this);
          password.addActionListener(this);
       class Horizontal_Spacer extends Canvas
          Horizontal_Spacer(int X, int Y)
             setSize(X,Y);
             setVisible(true);
       class Vertical_Spacer extends Canvas
          Vertical_Spacer()
             setSize(25,10);
             setVisible(true);
       class Top_Logo extends Canvas
          Top_Logo()
             setBackground(Color.white);
             setSize(420,65);
             setVisible(true);
          public void paint(Graphics g)
               g.setFont(hb30);
               g.drawString("MySQL Login",20,45);
       public void actionPerformed(ActionEvent event)
          Object source = event.getSource();
          ServerHost_String=serverHost.getText();
          Port_String=port.getText();
          UserName_String=userName.getText();
          Password_String=new String(password.getPassword());
          if ((ServerHost_String.compareTo("")!=0) &&
              (Port_String.compareTo("")!=0) &&
              (UserName_String.compareTo("")!=0) &&
              (Password_String.compareTo("")!=0))
               Login_String=ServerHost_String + "|" +
                            Port_String + "|" +
                            UserName_String + "|" +
                            Password_String;
               setVisible(false);
               dispose();
          public void windowClosing(WindowEvent e)
            setVisible(false);
            dispose();
    //Login_Test.java
    import javax.swing.*;
    public class Login_Test extends JFrame
       //public void run()
       public static void main(String [] args)
          Login f = new Login();
    }Doc

    Let me get this clear.
    You want a login dialog.
    Some program calls the dialog and waits untile user respond
    once the user press ok or cancel it reutrn the users input to the caller.
    You can do this directly using JFrame
    but you can do it wil JDialog if you use it as aModal dialog.
    it will look like this
    class LogInDialog  extends JDialog implements ActionListener{
       String value;
       public LogInDialog(){
          setModel(true);
        // This is what you invoke
        public String loadDialog(){
            setVisible(true);
            return value;
        public void actionListener(..... e){
            if (e.getSource() == bCancel)
               value = null;
            else if (e.getSource() == bOk)
               value = //generate the string
            dispose();
    }

  • Help with this GUI !!

    here is the question and the code that i tried ... and what is coded as a comment that is I'm not sure about .... any help plz ..
    Q: Create a JFrame application that has:
    ?     One JButton labeled ?AC Milan?
    ?     Another JButton labeled ?INTER MILAN?
    ?     A JLabel with the text ?Result: 0 X 0?
    ?     A JLabel with the text ?Last Scorer: N/A ?
    ?     A Label with the text ?Winner: DRAW?;
    Now whenever you click on the AC Milan button, the result will be incremented for AC Milan to become 1 X 0, then 2 X 0.
    The Last Scorer means the last team to have scored.
    And the winner is the team that has more button clicks than the other.
    import java.awt.event.*;
    import javax.swing.*;
    import java.awt.*;
    public class Match extends JFrame  // implements ActionListener
         public  final int W = 150;
         public  final int H = 250;
         int i = 0;
         int j = 0;
         String last = "N/A";
         String win = "Draw";
         JFrame frm = new JFrame("Match");
         JButton butt1 = new JButton("AC MILAN");
         JButton butt2 = new JButton("INTER MILAN");
         JLabel lbl1 = new JLabel("Result: " + i + " X " + j );
         JLabel lbl2 = new JLabel("Last Scorer: " +last);
         JLabel lbl3 = new JLabel("Winner: " + win );
         public Match ()
              frm.setSize (W,H);
              frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frm.setLayout(new FlowLayout());
              frm.add(butt1);
              frm.add(butt2);
              frm.add(lbl1);
              frm.add(lbl2);
              frm.add(lbl3);
              frm.setVisible(true);
              //EndingListener bt1 = new EndingListener();
              //EndingListener bt2 = new EndingListener();
              //butt1.addActionListener(new ActionListener());
              //public void actionPerformed(ActionEvent ev)
              //     if (ev.getSource() == butt1)
              //          i++;
              //          lbl1.setText("Result: " + i + " X " + j );
              //          lbl2.setText("Last Scorer: " + "AC MILAN" );//butt1.caption
              //          lbl3.setText("Winner: " + /*the most clicked butt*/ );
              //     else if (ev.getSource() == butt2)
              //          j++;
              //          lbl1.setText("Result: "+i+" X "+j);
              //          lbl2.setText("Last Scorer: "+"INTER MILAN"); //butt2.caption
              //          lbl3.setText("Winner: " + /*the most clicked butt*/ );
         public static void main (String[]args)
              new Match();
    }Message was edited by:
    DaVeeCk

    here is the question and the code that i tried ...
    and what is coded as a comment that is I'm not sure
    about .... any help plz ..
    Q: Create a JFrame application that has:
    ?     One JButton labeled ?AC Milan?
    ?     Another JButton labeled ?INTER MILAN?
    ?     A JLabel with the text ?Result: 0 X 0?
    ?     A JLabel with the text ?Last Scorer: N/A ?
    ?     A Label with the text ?Winner: DRAW?;
    Now whenever you click on the AC Milan button, the
    result will be incremented for AC Milan to become 1 X
    0, then 2 X 0.
    The Last Scorer means the last team to have scored.
    nd the winner is the team that has more button clicks
    than the other.
    import java.awt.event.*;
    import javax.swing.*;
    import java.awt.*;
    public class Match extends JFrame  // implements
    ActionListener
         public  final int W = 150;
         public  final int H = 250;
         int i = 0;
         int j = 0;
         String last = "N/A";
         String win = "Draw";
         JFrame frm = new JFrame("Match");
         JButton butt1 = new JButton("AC MILAN");
         JButton butt2 = new JButton("INTER MILAN");
    JLabel lbl1 = new JLabel("Result: " + i + " X " + j
    j );
         JLabel lbl2 = new JLabel("Last Scorer: " +last);
         JLabel lbl3 = new JLabel("Winner: " + win );
         public Match ()
              frm.setSize (W,H);
              frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frm.setLayout(new FlowLayout());
              frm.add(butt1);
              frm.add(butt2);
              frm.add(lbl1);
              frm.add(lbl2);
              frm.add(lbl3);
              frm.setVisible(true);
              //EndingListener bt1 = new EndingListener();
              //EndingListener bt2 = new EndingListener();
              //butt1.addActionListener(new ActionListener());
              //public void actionPerformed(ActionEvent ev)
              //     if (ev.getSource() == butt1)
              //          i++;
              //          lbl1.setText("Result: " + i + " X " + j );
    //          lbl2.setText("Last Scorer: " + "AC MILAN"
    N" );//butt1.caption
    //          lbl3.setText("Winner: " + /*the most clicked
    ed butt*/ );
              //     else if (ev.getSource() == butt2)
              //          j++;
              //          lbl1.setText("Result: "+i+" X "+j);
    //          lbl2.setText("Last Scorer: "+"INTER MILAN");
    ); //butt2.caption
    //          lbl3.setText("Winner: " + /*the most clicked
    ed butt*/ );
         public static void main (String[]args)
              new Match();
    }Message was edited by:
    DaVeeCkOkay, well, I won't do your homework for you, but I'll point you in a right direction. First, since you are implementing ActionListener instead of doing an inline (which I prefer) your code "butt1.addActionListener(new ActionListener());" should be more like "butt1.addActionListener(this); Dont' know how you expect button 2 to work since you never add the action listener. Third, your action performed method shouldnt be inside your class. move it out there on the same level as your class and the main method. Finally, inside your action performed, you are heading in the right direction, but now you need to find a way to decide to end the game or not (probably depending on the score that just got adjusted *hint).                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Advance level drawing problem with Jframe and JPanel need optimize sol?

    Dear Experts,
    I m trying to create a GUI for puzzle game following some kind of "game GUI template", but i have problems in that,so i tried to implement that in various ways after looking on internet and discussions about drawing gui in swing, but i have problem with both of these, may be i m doing some silly mistake, which is still out of my consideration. please have a look at these two and recommend me one of them, which is running without problems (flickring and when you enlarge window the board draw copies (tiled) everywhere,
    Note: i don't want to inherit jpanel or Jframe
    here is my code : import java.awt.BorderLayout;
    public class GameMain extends JFrame {
         private static final long serialVersionUID = 1L;
         public int mX, mY;
         int localpoints = 0;
         protected static JTextField[][] squares;
         protected JLabel statusLabel = new JLabel("jugno");
         Label lbl_score = new Label("score");
         Label lbl_scorelocal = new Label("local score");
         protected static TTTService remoteTTTBoard;
         // Define constants for the game
         static final int CANVAS_WIDTH = 800; // width and height of the game screen
         static final int CANVAS_HEIGHT = 600;
         static final int UPDATE_RATE = 4; // number of game update per second
         static State state; // current state of the game
         private int mState;
         // Handle for the custom drawing panel
         private GameCanvas canvas;
         // Constructor to initialize the UI components and game objects
         public GameMain() {
              // Initialize the game objects
              gameInit();
              // UI components
              canvas = new GameCanvas();
              canvas.setPreferredSize(new Dimension(CANVAS_WIDTH, CANVAS_HEIGHT));
              this.setContentPane(canvas);
              this.setDefaultCloseOperation(EXIT_ON_CLOSE);
              this.pack();
              this.setTitle("MY GAME");
              this.setVisible(true);
         public void gameInit() {     
         // Shutdown the game, clean up code that runs only once.
         public void gameShutdown() {
         // To start and re-start the game.
         public void gameStart() {
         private void gameLoop() {
         public void keyPressed(KeyEvent e) {
         public void keyTyped(KeyEvent e) {
         public void gameKeyReleased(KeyEvent e) {
              PuzzleBoard bd = getBoard();
              for (int row = 0; row < 4; ++row) {
                   for (int col = 0; col < 4; ++col) {
                        if (e.getSource() == squares[row][col]) {
                             if (bd.isOpen(col, row)) {
                                  lbl_score.setText("Highest Score = "
                                            + Integer.toString(bd.getPoints()));
                                  setStatus1(bd);
                                  pickSquare1(col, row, squares[row][col].getText()
                                            .charAt(0));
         protected void pickSquare1(int col, int row, char c) {
              try {
                   remoteTTTBoard.pick(col, row, c);
              } catch (RemoteException e) {
                   System.out.println("Exception: " + e.getMessage());
                   e.printStackTrace();
                   System.exit(1);
         // method "called" by remote object to update the state of the game
         public void updateBoard(PuzzleBoard new_board) throws RemoteException {
              String s1;
              for (int row = 0; row < 4; ++row) {
                   for (int col = 0; col < 4; ++col) {
                        squares[row][col].setText(new_board.ownerStr(col, row));
              lbl_score.setText("Highest Score = "
                        + Integer.toString(new_board.getPoints()));
              setStatus1(new_board);
         protected void setStatus1(PuzzleBoard bd) {
              boolean locals = bd.getHave_winner();
              System.out.println("local win" + locals);
              if (locals == true) {
                   localpoints++;
                   System.out.println("in condition " + locals);
                   lbl_scorelocal.setText("Your Score = " + localpoints);
              lbl_score
                        .setText("Highest Score = " + Integer.toString(bd.getPoints()));
         protected PuzzleBoard getBoard() {
              PuzzleBoard res = null;
              try {
                   res = remoteTTTBoard.getState();
              } catch (RemoteException e) {
                   System.out.println("Exception: " + e.getMessage());
                   e.printStackTrace();
                   System.exit(1);
              return res;
         /** Custom drawing panel (designed as an inner class). */
         class GameCanvas extends JPanel implements KeyListener {
              /** Custom drawing codes */
              @Override
              public void paintComponent(Graphics g) {
                   // setOpaque(false);
                   super.paintComponent(g);
                   // main box; everything placed in this
                   // JPanel box = new JPanel();
                   setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
                   // add(statusLabel, BorderLayout.NORTH);
                   // set up the x's and o's
                   JPanel xs_and_os = new JPanel();
                   xs_and_os.setLayout(new GridLayout(5, 5, 0, 0));
                   squares = new JTextField[5][5];
                   for (int row = 0; row < 5; ++row) {
                        for (int col = 0; col < 5; ++col) {
                             squares[row][col] = new JTextField(1);
                             squares[row][col].addKeyListener(this);
                             if ((row == 0 && col == 1) || (row == 2 && col == 3)
                             || (row == 1 && col == 4) || (row == 4 && col == 4)
                                       || (row == 4 && col == 0))
                                  JPanel p = new JPanel(new BorderLayout());
                                  JLabel label;
                                  if (row == 0 && col == 1) {
                                       label = new JLabel("1");
                                       label.setHorizontalAlignment(JLabel.LEFT);
                                       label.setVerticalAlignment(JLabel.TOP);
                                  else if (row == 4 && col == 0) {// for two numbers or
                                       // two
                                       // blank box in on row
                                       label = new JLabel("2");
                                       label.setHorizontalAlignment(JLabel.LEFT);
                                       label.setVerticalAlignment(JLabel.TOP);
                                  else if (row == 1 && col == 4) {
                                       label = new JLabel("3");
                                       label.setHorizontalAlignment(JLabel.LEFT);
                                       label.setVerticalAlignment(JLabel.TOP);
                                  else if (row == 4) {
                                       label = new JLabel("4");
                                       label.setHorizontalAlignment(JLabel.LEFT);
                                       label.setVerticalAlignment(JLabel.TOP);
                                  else {
                                       label = new JLabel("5");
                                       label.setHorizontalAlignment(JLabel.LEFT);
                                       label.setVerticalAlignment(JLabel.TOP);
                                  label.setOpaque(true);
                                  label.setBackground(squares[row][col].getBackground());
                                  label.setPreferredSize(new Dimension(label
                                            .getPreferredSize().width, squares[row][col]
                                            .getPreferredSize().height));
                                  p.setBorder(squares[row][col].getBorder());
                                  squares[row][col].setBorder(null);
                                  p.add(label, BorderLayout.WEST);
                                  p.add(squares[row][col], BorderLayout.CENTER);
                                  xs_and_os.add(p);
                             } else if ((row == 2 && col == 1) || (row == 1 && col == 2)
                                       || (row == 3 && col == 3) || (row == 0 && col == 3)) {
                                  xs_and_os.add(squares[row][col]);
                                  // board[ row ][ col ].setEditable(false);
                                  // board[ row ][ col ].setText("");
                                  squares[row][col].setBackground(Color.RED);
                                  squares[row][col].addKeyListener(this);
                             } else {
                                  squares[row][col] = new JTextField(1);
                                  // squares[row][col].addActionListener(this);
                                  squares[row][col].addKeyListener(this);
                                  xs_and_os.add(squares[row][col]);
                   this.add(xs_and_os);
                   this.add(statusLabel);
                   this.add(lbl_score);
                   this.add(lbl_scorelocal);
              public void keyPressed(KeyEvent e) {
              public void keyReleased(KeyEvent e) {
                   gameKeyReleased(e);
              public void keyTyped(KeyEvent e) {
         // main
         public static void main(String[] args) {
              SwingUtilities.invokeLater(new Runnable() {
                   @Override
                   public void run() {
                        new GameMain();
      thanks a lot for your time , consideration and efforts.
    jibby
    Edited by: jibbylala on Sep 20, 2010 6:06 PM

    jibbylala wrote:
    thanks for mentioning as i wasn't able to write complete context here.Yep thanks camickr. I think that Darryl's succinct reply applies here as well.

  • Drawing a picture within JFrame when I've already created a JFrame

    Hi everyone,
    I was wondering if you could help me out with this problem I'm getting. I'm creating a program to simulate an 'elevator.' When first creating the project I created a brand new 'Java GUI Form' : 'JFrame Form'. From here I went on to drag-and-drop various command buttons and labels to create the user interface (the 'inside' of an elevator). Here is where my question comes in. On the very left of my interface I want to have the program draw a simulation of a box (the elevator) moving up and down with the 'floor numbers' the user pushes. However i don't know how to access the coding of the jFrame object that I created through the design editor so i can input the coding.
    First Question: What do i have to 'write' that would force that box to print into the current JFrame?
    Second Question: What Code (and where do i put it) essentially 'locks' the JFrame from being resized?

    Here, maybe by putting this it might help you recognize what i'm trying to say. The code i'm trying to put in is:
    JFrame window = new JFrame ("Drawing");
            window.setBounds(200,200,700,500);
            window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            window.setVisible(true);
            Container contentPane = window.getContentPane();
            contentPane.setBackground(new Color(125, 125, 125));
            Graphics g = contentPane.getGraphics();* This is a portion of the code
    When run, this program creates a NEW JFRAME WINDOWS, i'm trying to make it run inside an already existing JFrame, whose variable Name i dont know how to find.

  • Help with drawing strings on JFrame?!?!

    Hey guys, I'm really new to Java (just started AP Comp Sci last month), and we had a project to build a Mastermind application using numbers, which I did. However, I'm trying to learn more on my own, and was hoping to use the example code my teacher gave me to output what I want to say to a JFrame instead of just the command prompt.
    Here is the code for my Mastermind class:
    Code:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class Mastermind extends JFrame
         public static void main(String args[])
              int master[] = new int[4];
              int win = 0;
              for(int x = 0; x<4; x++)
                   master[x] = (int)(Math.random()*10);
              System.out.println();
              do {
                   int guess[] = new int[4];
                   int countMaster[] = new int[4];
              String numguess = JOptionPane.showInputDialog("Enter your guess (4 digits, please)");
              for (int x = 0;x<4;x++)
                   guess[x] = (numguess.charAt(x)-48);
              int correctlyPlaced = 0;
              int correct = 0;
              for (int x = 0;x<4;x++)
                   if(master[x] == guess[x])
                        correctlyPlaced += 1;
              for (int x = 0; x<4;x++)
                             for (int y = 0; y<4;y++)
                                  if((guess[x]==master[y]) && (countMaster[y]==0)) {
                                       correct++;
                                       countMaster[y]=1;
                                       y=5;
              System.out.print("Guess:\t\t\t");
              for (int x = 0;x<4;x++) {
                   System.out.print(guess[x]);
              System.out.println();
              System.out.println("Correct:\t\t"+correct);
              System.out.println("Correctly Placed:\t"+correctlyPlaced);
              if (correctlyPlaced==4) {
                   win=1;
         } while(win<1);
         System.out.println("You win!");
              System.exit(0);
    And here is the example code that my teacher gave me for how to draw a string on a JFrame:
    Code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Fonts extends JFrame {
         public Fonts()
              super("Using Fonts");
              setSize(420,125);
              show();
         public void paint(Graphics g)
              super.paint(g);
              g.setFont(new Font("Serif", Font.BOLD, 12));
              g.drawString("Serif 12 point bold.",20,50);
         public static void main(String args[])
              Fonts application = new Fonts();
              application.setDefaultCloseOperation (
                   JFrame.EXIT_ON_CLOSE);
    I would like to be able to put "Guess," "Correct," and "Correctly Placed," on a JFrame, with their respective variables. Any ideas? Thank you!!!

    800045 wrote:
    And DrClap, I get that, but I'm not sure how to put my existing code into the class file that uses the JFrame.You wouldn't put your existing code in there. Your existing code is designed to run as a console app and most of it is concerned with the machinery of getting input from the user. If you want to write it as a Swing app, then you wouldn't need any code which writes to a JFrame in the first place.
    So if your goal for learning on your own is to write GUI applications instead of console applications, then go off and read the Swing tutorials. Right now you're going down the wrong road. However if you're trying to learn something else on your own (I can't tell what that might be) then explain what it is you're trying to learn.

  • Inability to draw simple graphics in Java properly (threads and JFrame)

    I am trying to use a thread to continually draw randomly positioned and randomly sized squares in the middle of a JFrame window. I have got 'something' working with the following code, however when run, the actual window doesn't come up properly. If I resize the window it does, and I get the result I wanted, but when the window is first opened it does not fully draw itself on screen. Can anybody help here? I am a bit of a novice when it comes to Java
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.*;
    public class TestDraw extends JFrame implements Runnable {
    //DECLARE VARIABLES
         private JLabel lblText;
         private JButton btnBegin;
         private JPanel contentPane;
         private int CoordX, CoordY,SizeX, SizeY, Colour;     // Co'ords for drawing the squares
         Random random = new Random();                              // Random numbers (for square dimensions and colours)
         int n_1 = 450, n_2 = 130, n_3 = 100, n_4 = 4;          // The different ranges of randoms I require
         Thread squares = new Thread(this);                         // Implements a new thread
    //END OF DECLARE VARIABLES
    // CALLS INITIAL PROCEDURE, SETS VISIBLE ETC
         public TestDraw() {
              super();
              initializeComponent();
              this.setVisible(true);
    // INITIALISATION PROCEDURE CALL
         private void initializeComponent() {
              lblText = new JLabel();
              btnBegin = new JButton();
              contentPane = (JPanel)this.getContentPane();
              // lblText
              lblText.setText("This should draw squares on screen...");
              // btnBegin
              btnBegin.setText("Start");
              btnBegin.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        btnBegin_actionPerformed(e);
              // contentPane
              contentPane.setLayout(null);
              addComponent(contentPane, lblText, 10,300,364,18);
              addComponent(contentPane, btnBegin, 144,10,101,28);
              // TestDraw
              this.setTitle("TestDraw Program for CM0246");
              this.setLocation(new Point(0, 0));
              this.setSize(new Dimension(390, 350));
    // POSITION COMPONENTS ON SCREEN
         private void addComponent(Container container,Component c,int x,int y,int width,int height)     {
              c.setBounds(x,y,width,height);
              container.add(c);
    // EVENT HANDLING PROCEDURES
         private void btnBegin_actionPerformed(ActionEvent e) {
              System.out.println("\nAction Event from btnBegin called...");
              squares.start(); //STARTS THE SQUARES DRAWING THREAD (Draws random squares on screen)
    // THE MAIN METHOD (STARTS THE PROGRAM)
         public static void main(String[] args) {
              TestDraw bobdole = new TestDraw();
    // THE SQUARE DRAWINGS THREAD (SHOULD DRAW RANDOM SIZED AND COLOURED SQUARES IN RANDOM PLACES)
         public void run() {
              System.out.println("Thread running if this prints");
                   while(true) {
                        int int_1 = random.nextInt(n_1);     // chooses random int for X co'ord
                        int int_2 = random.nextInt(n_2)+70;     // chooses random int for Y co'ord
                        int int_3 = random.nextInt(n_3)+10;     // chooses random int for X dimension
                        int int_4 = random.nextInt(n_3)+10;     // chooses random int for Y dimension
                        CoordX = int_1;
                        CoordY = int_2;
                        SizeX  = int_3;
                        SizeY  = int_4;
                        repaint();
                        try {
                             squares.sleep(500);
                        catch (InterruptedException e) {
                             System.out.println(e);
    // THE PAINT METHOD ATTATCHED TO THE SQUARES THREAD
         public void paint( Graphics g ) {
              System.out.print("Colour" + Colour);
              g.setColor(Color.blue);
              g.fillRect(CoordX, CoordY, SizeX, SizeY);
    // END OF PROGRAM

    I don't see any problem when I run the program but.. In general you shouldn't paint directly on a frame by overloading the paint method. You should rather create a custom component on which you draw.
    But if you do overload paint, make sure you call super.paint before doing anything else.
    More information in this tutorial: http://java.sun.com/docs/books/tutorial/uiswing/painting/index.html

  • Drawing with double buffering to a JFrame

    I want to create a simple JFrame and draw stuff to it via Graphic object using double buffering.
    If I create a loop and draw constantly using JFrame.getGraphic().xxx, am i doing double buffering. ( 'cause i read somewhere that swing components automaticly use double buffering ). And is this the righ approuch ( or whatever it's spelled ) ?

    I want to create a simple JFrame and draw stuff to it
    Don't do that.
    If you want to do custom rendering then use JPanel or JComponent, not JFrame.
    If I create a loop and draw constantly using JFrame.getGraphic().xxx, am i doing double buffering.
    No.
    You're also painting outside the standard paint cycle, which is a Bad Idea.
    So, essentially, everything your suggesting is the wrong way to go about things.
    In its most simple form, double buffering works something like this, though there are a whole load of subtleties to consider (such as component resizing for a start)
    public class Foo extends JComponent
        private BufferedImage image = null;
        protected void paintComponent(Graphics g)
            if (image != null)
                image = createImage(getWidth(), getHeight());
                paintBuffer(ig);
            g.drawImage(image, 0, 0, this);
        private void paintBuffer()
            Graphics ig = image.getGraphics();
            // do the rendering
            ig.dispose();
    }

  • Draw geotiff in a JFrame

    Hi: However I found that some geotiff image can be displayed in a JFrame,however others can not.
    The core codes:
      PlanarImage resultImage = null;
      InputStream is = null;
      try {
       is = new FileInputStream(new File("D:/wu.tif"));
      } catch (FileNotFoundException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
      SeekableStream seekableStream = SeekableStream.wrapInputStream(is, true);
      ParameterBlock pb = new ParameterBlock();
      pb.add(seekableStream);
      resultImage = JAI.create("TIFF", pb);
      JFrame jf=new JFrame("Geo");
      jf.setSize(800,600);
      jf.setVisible(true);
      Graphics g=jf.getGraphics();
      g.drawImage(resultImage.getAsBufferedImage(), 0, 0, null);-----------------------
    The two geotiff, usa.tiff and wu.tif, the wu.tif can not drawed in the JFrame, it is a black blank.
    I wonder why?
    The files can be found there :
    [usa.tiff|http://www.mofile.com/pickup/uziiaq7x4zr6fnm/]
    [wu.tif|http://www.mofile.com/pickup/5uvoybjury2fxkn/]
    I hope someone can check it for me ,thanks.

    Maxideon wrote:
    The image files that your links prompt me to download have an exe extension? I'm not about to download them to find out what the deal is.No,the extension of the first is .tiff, and the second is tif, how can they become to exe?
    Well, is there a safe way to share the image?

  • Drawing JPEGs/GIFs directly on JFrames

    Hey all,
    Is it possible to draw an image DIRECTLY onto an instance of the JFrame class, rather than writing a subclass of a component? I suspect that a solution to my problem might have something to do with the getGraphics() method of JFrame.
    Mike.

    Have you looked into your own suggestion? Doesn't the Graphics object returned from getGraphics() provide a drawImage() method?

  • Draw a line on a JFrame

    I have 2 panels inside a JFrame and I want to separate the 2 panels using a visible line. How can I draw this line?

    You will need to over ride the paint(Graphics g) method.
    From there you can use the g.drawLine(startX,startY,endX,endY). So for instance if you had two panels next to each other and the line is a vertical line then you would do something similar to this.
    public void paint(Graphics g){
            super.paint(g);
            int x = this.jPanel1.getWidth();
            g.drawLine(x, 0, x, this.getHeight());
    }This is probably a good place to start learning java2d
    http://java.sun.com/docs/books/tutorial/2d/basic2d/index.html

Maybe you are looking for

  • Acrobat 8 Pro for Windows

    Just this morning I encountered a problem with converting a Word 7 doc to a pdf. Since that didn't work, I tried printing the doc to the Adobe Printer which usually works. Well this time it didn't and now 8 Pro won't even open from my desktop. I also

  • Universal WorkList (UWL) items forward

    Hi all. When a user goes to forward a workflow to someone, you get the "Forward" button. When doing the search for a person, a list is returned. Where is this list created from? We want to limit the list to be only managers, but right now, we are ret

  • WebLogic 10.3 refused to start up with FileNet Jace.jar in classpath

    I am trying to configure my application to connect to FileNet 4.5.1 Java APIs, and whenever I add the Jace.jar file to the WebLogic 10.3 startup script, the JVM quits with the following message: <Aug 6, 2012 4:01:14 PM PDT> <Critical> <WebLogicServer

  • Oc4j islands

    Hello all, when I create few more islands other than juts one default_isalnd for my oc4j , the http requests to my application are being load-balanced automatically with all the available island processes.Is this the default behavior when I create mo

  • Applications are showing errors 6303c

    My nokia 6303 c is showing lot of errors . . Even i open ovistore it is showing. java out of memory . Null pointer . Like that many applications are stopping in the middle only . What should i do?