Panel Draw

I want to draw on a Jpanel. Please point me to the appropriate API to do this.
I want to draw a line, a rectangle.
Thanks for your help in advance.
WBR

You need to override the [url http://java.sun.com/j2se/1.4.1/docs/api/javax/swing/JComponent.html#paintComponent(java.awt.Graphics) ]paintComponent method, and use calls on the [url http://java.sun.com/j2se/1.4.1/docs/api/java/awt/Graphics.html]Graphics object passed in.
Pete

Similar Messages

  • Radio panel and selection dependent panel draw

    Hi
    I've got two problems with my applet which have me stumped. http://zeldia.cap.ed.ac.uk/Lumbribase/array_exp.php?cluster=LRP00075_8
    1) I'd like the radio buttons on the top panel closer together. I've tried setting the panel grid layout to (1,5) (in the hope of 3 blanks on the right) and I've tried setting the prefered size but it seems to ignor the horizontal parameter unless I set it bigger that the available space.
    2) The checkbox panel on the right is only relevant when the 'exposure' radio button is selected. How can I make it only add this panel when 'exposure' selected and thus checkBoxSetting[4]= true;
    Thanks in advance for any info you can give.
    Ann
    import java.applet.Applet;
    import java.awt.Graphics;
    import java.awt.Color;
    import java.awt.*;
    import java.awt.event.*;
    import java.lang.Math;
    import java.net.*;
    import java.io.*;
    import java.util.*;
    import javax.swing.*;
    import java.text.*;
    /*import java.sql.*;
    import java.sql.DriverManager;
    import java.sql.Connection;
    import java.sql.SQLException;
    public class ArrayExpApplet extends Applet
                           implements ItemListener, ActionListener  {
         private JCheckBox ATButton;
         private JCheckBox CdButton;
         private JCheckBox CuButton;
         private JCheckBox PAHButton;
         private JCheckBox ExposureButton;
         private JCheckBox ControlButton;
       static String ExposureString = "Exp";
       static String ControlString = "Con";
         private boolean[] checkBoxSetting = {true,true,true,true,false,true};
         private double[][] expLevels = new double[4][5];
         private double[]   controlLevels = new double[3];
         private Color[] EColor = new Color[5];
         private int originX=100;
         private int height=200;
         private int originY=height+(originX/2);
         private double controlScale=-1;
         private double expScale=-1;
         private double controlMax=0;
         private double expMax=0;
         private JPanel side =  CheckBoxPanelSide();
         private Panel canvasPanel = new Panel();
         public void init() {
          System.out.println("initiating...");
          setBackground(new Color(224, 238, 238));;
              //get the php expression string and read into 2D numeric array
              String expression_str = this.getParameter("expression_string");
              System.out.println("expression_string "+expression_str);
              String[] rows = expression_str.split (";");
              for (int k = 0; k < rows.length; k++) {
                   System.out.println("row "+k+" = "+rows[k]);
                   String[] cols = rows[k].split (",");
                   for (int l = 0; l < cols.length; l++) {
                        System.out.println("col "+l+" = "+cols[l]);
                        expLevels[k][l]= Double.parseDouble(cols[l]);
              //get the php control string and read into a numeric array
              String control_str = this.getParameter("control_string");
              System.out.println("control_string "+control_str);
              rows = control_str.split (",");
              for (int k = 0; k < rows.length; k++) {
                   System.out.println("row "+k+" = "+rows[k]);
                   controlLevels[k]= Double.parseDouble(rows[k]);
              //find max expression to scale y axis
              for (int i=0; i<4; i++) {
                   for (int j=0; j<5; j++){
                        if (expLevels[i][j]>expMax) {expMax=expLevels[i][j];}
              expScale=height/(double)expMax;
              //find max control to scale y axis
              for (int i=0; i<3; i++) {
                   if (controlLevels>controlMax) {controlMax=controlLevels[i];}
              controlScale=height/(double)controlMax;
              //set up an array of 5 colours
              EColor[0]= new Color(200,0,255); //magenta
              EColor[1]= new Color(0,0,255);      //green
              EColor[2]= new Color(0,255,0);      //blue
              EColor[3]= new Color(254,190,0); //yellow
              EColor[4]= new Color(224, 238, 238); //background
    public void start() {
    System.out.println("starting...");
    //          Panel canvasPanel = new Panel();
              Panel entirePanel = new Panel();
              Canvas graph = new Canvas();
              JPanel top = CheckBoxPanelTop();
              JPanel side = CheckBoxPanelSide();
              setLayout(new BorderLayout());
              //layout total area as boxes top to bottom
              entirePanel.setLayout(new BoxLayout(entirePanel, BoxLayout.PAGE_AXIS));
              //put top checkboxes in top box
              entirePanel.add(top);
              //layout area as boxes left to right
              canvasPanel.setLayout(new BoxLayout(canvasPanel, BoxLayout.LINE_AXIS));
              //put canvasPanel in bottom box
              entirePanel.add(canvasPanel);
                   //Put a graph in the first box.
                   canvasPanel.add(graph);
                   //Put checkboxes in the right box.
                   canvasPanel.add(side);
              add("North", entirePanel);
              add("East", canvasPanel);
         public JPanel CheckBoxPanelSide() {
              //Create the check boxes.
              ATButton = new JCheckBox("Atrazine");
              ATButton.setForeground(EColor[0]);
              ATButton.setBackground(new Color(224, 238, 238));
              ATButton.setSelected(true);
              checkBoxSetting[0]=true;
              CdButton = new JCheckBox("Cadmium");
              CdButton.setForeground(EColor[1]);
              CdButton.setBackground(new Color(224, 238, 238));
              CdButton.setSelected(true);
              checkBoxSetting[1]=true;
              CuButton = new JCheckBox("Copper");
              CuButton.setForeground(EColor[2]);
              CuButton.setBackground(new Color(224, 238, 238));
              CuButton.setSelected(true);
              checkBoxSetting[2]=true;
              PAHButton = new JCheckBox("PAH");
              PAHButton.setForeground(EColor[3]);
              PAHButton.setBackground(new Color(224, 238, 238));
              PAHButton.setSelected(true);
              checkBoxSetting[3]=true;
              //Register a listener for the check boxes.
              ATButton.addItemListener(this);
              CdButton.addItemListener(this);
              CuButton.addItemListener(this);
              PAHButton.addItemListener(this);
              JPanel s = new JPanel();
              s.setLayout(new GridLayout(6,1));
              s.setBackground(new Color(224, 238, 238));
              s.setBorder(BorderFactory.createLineBorder (Color.blue, 2));
              s.add(ATButton);
              s.add(CdButton);
              s.add(CuButton);
              s.add(PAHButton);
              return (s);
         public JPanel CheckBoxPanelTop() {
              //Create the radio buttons.
              JRadioButton ExposureButton = new JRadioButton("Exposure");
              ExposureButton.setBackground(new Color(224, 238, 238));
              ExposureButton.setSelected(true);
    ExposureButton.setActionCommand(ExposureString);
              checkBoxSetting[4]=true;
              JRadioButton ControlButton = new JRadioButton("Control");
              ControlButton.setBackground(new Color(224, 238, 238));
    ControlButton.setActionCommand(ControlString);
              ControlButton.setSelected(false);
              //Group the radio buttons.
              ButtonGroup group = new ButtonGroup();
              group.add(ControlButton);
              group.add(ExposureButton);
    //Register a listener for the radio buttons.
              ControlButton.addActionListener(this);
              ExposureButton.addActionListener(this);
              JPanel t = new JPanel();
              t.setLayout(new GridLayout(1,5));
              t.setBackground(new Color(224, 238, 238));
              t.setBorder(BorderFactory.createLineBorder (Color.blue, 2));
              t.setPreferredSize(new Dimension(50, 35));
              t.add(ControlButton);
              t.add(ExposureButton);
              return (t);
    // Listens to the radio buttons.
         public void actionPerformed(ActionEvent e) {
              System.out.println(""+e.getActionCommand());
              if (e.getActionCommand() == "Exp") {checkBoxSetting[4]= true;}
              if (e.getActionCommand() == "Con") {checkBoxSetting[4]= false;}
              repaint();
    // add a checkbox listener
         public void itemStateChanged(ItemEvent event) {
              char c = '-';
              Object source = event.getItemSelectable();
              if (source == ATButton) {
                   if (checkBoxSetting[0]== false) {checkBoxSetting[0]= true;}
                   else {checkBoxSetting[0]= false;}
                   c = 'a';
                   System.out.println("CheckBox "+c);
              else if (source == CdButton) {
                   if (checkBoxSetting[1]== false) {checkBoxSetting[1]= true;}
                   else {checkBoxSetting[1]= false;}
                   c = 'd';
                   System.out.println("CheckBox "+c);
              else if (source == CuButton) {
                   if (checkBoxSetting[2]== false) {checkBoxSetting[2]= true;}
                   else {checkBoxSetting[2]= false;}
                   c = 'u';
                   System.out.println("CheckBox "+c);
              else if (source == PAHButton) {
                   if (checkBoxSetting[3]== false) {checkBoxSetting[3]= true;}
                   else {checkBoxSetting[3]= false;}
                   c = 'p';
                   System.out.println("CheckBox "+c);
              repaint();
         public void paint(Graphics g) {
              System.out.println("Paint");
              if (checkBoxSetting[4]== true) {   //paint exposures
                   System.out.println("painting exposure");
                   //Draw the data
                   int step=100; //distance between exposures on x axis
                   int x=originX; int y;
                   for (int i=0; i<4; i++) {
                        System.out.println("CheckBox "+i+" is "+checkBoxSetting[i]);
                        if (checkBoxSetting[i]) {
                             g.setColor(EColor[i]);
                             for (int j=0; j<4; j++){
                                  y=j+1;
                                  g.drawLine(x,originY-(int)(expLevels[i][j]*expScale), x+step, originY-(int)(expLevels[i][y]*expScale));
                                  x=x+step;
                             x=originX;
                   //draw axis
                   g.setColor(Color.black);
                   g.drawLine(originX, (originX/2), originX, originY);
                   g.drawLine(originX, originY, originX+(step*4), originY);
                   //tickmark axis
                   g.drawLine(originX, originY, originX, originY+5);
                   g.drawLine(originX+step, originY, originX+step, originY+5);
                   g.drawLine(originX+(step*2), originY, originX+(step*2), originY+5);
                   g.drawLine(originX+(step*3), originY, originX+(step*3), originY+5);
                   g.drawLine(originX+(step*4), originY, originX+(step*4), originY+5);
                   g.drawLine(originX, originY, originX-5, originY);
                   g.drawLine(originX, originY- (int) (expMax*expScale*0.25), originX-5, originY- (int) (expMax*expScale*0.25));//400*.5=200*.25=50
                   g.drawLine(originX, originY- (int) (expMax*expScale*0.5), originX-5, originY- (int) (expMax*expScale*0.5));
                   g.drawLine(originX, originY- (int) (expMax*expScale*0.75), originX-5, originY- (int) (expMax*expScale*0.75));
                   g.drawLine(originX, originY- (int) (expMax*expScale), originX-5, originY- (int) (expMax*expScale));
                   //lable x axis
                   g.drawString("LC0", originX-9, originY+20);
                   g.drawString("LC12.5", originX-18+step, originY+20);
                   g.drawString("LC25", originX-12+(step*2), originY+20);
                   g.drawString("LC37.5", originX-18+(step*3), originY+20);
                   g.drawString("LC50", originX-12+(step*4), originY+20);
                   g.drawString("Exposure", originX-24+(step*2), originY+40);
                   //lable y axis
                   String fmt = "0.00#";
                   DecimalFormat df = new DecimalFormat(fmt);
                   int xs=originX; int ys=originY; int zs=(int)((expMax/height)*0.25);
    //               g.drawString("x"+xs+" y"+ys+" zs"+zs+" expMax"+expMax+" expScale"+expScale, 0, originY+60);
                   g.drawString("0", originX-20, originY+4);
                   g.drawString(""+df.format((double)(expMax*0.25)), originX-45, originY+4- (int) (expMax*expScale*0.25));//400*.5=200*.25=50
                   g.drawString(""+df.format((double)(expMax*0.50)), originX-45, originY+4- (int) (expMax*expScale*0.5));
                   g.drawString(""+df.format((double)(expMax*0.75)), originX-45, originY+4- (int) (expMax*expScale*0.75));
                   g.drawString(""+df.format(expMax), originX-45, originY+4- (int) (expMax*expScale));
                   g.drawString("E", originX-100, originY-(int)(height*0.5)-50);
                   g.drawString("x", originX-100, originY-(int)(height*0.5)-40);
                   g.drawString("p", originX-100, originY-(int)(height*0.5)-30);
                   g.drawString("r", originX-100, originY-(int)(height*0.5)-20);
                   g.drawString("e", originX-100, originY-(int)(height*0.5)-10);
                   g.drawString("s", originX-100, originY-(int)(height*0.5));
                   g.drawString("s", originX-100, originY-(int)(height*0.5)+10);
                   g.drawString("i", originX-98, originY-(int)(height*0.5)+20);
                   g.drawString("o", originX-100, originY-(int)(height*0.5)+30);
                   g.drawString("n", originX-100, originY-(int)(height*0.5)+40);
              else {                // paint control
                   System.out.println("painting control");
                   //Draw the data
                   int step=200; //distance between controls on x axis
                   int x=originX; int y;
                   for (int i=0; i<2; i++) {
                        g.setColor(EColor[0]);
                        int j=i+1;
                        g.drawLine(x,originY-(int)(controlLevels[i]*controlScale), x+step, originY-(int)(controlLevels[j]*controlScale));
                        x=x+step;
                   //draw axis
                   g.setColor(Color.black);
                   g.drawLine(originX, (originX/2), originX, originY);
                   g.drawLine(originX, originY, originX+(step*2), originY);
                   //tickmark axis
                   g.drawLine(originX, originY, originX, originY+5);
                   g.drawLine(originX+step, originY, originX+step, originY+5);
                   g.drawLine(originX+(step*2), originY, originX+(step*2), originY+5);
                   g.drawLine(originX, originY, originX-5, originY);
                   g.drawLine(originX, originY- (int) (expMax*expScale*0.25), originX-5, originY- (int) (expMax*expScale*0.25));//400*.5=200*.25=50
                   g.drawLine(originX, originY- (int) (expMax*expScale*0.5), originX-5, originY- (int) (expMax*expScale*0.5));
                   g.drawLine(originX, originY- (int) (expMax*expScale*0.75), originX-5, originY- (int) (expMax*expScale*0.75));
                   g.drawLine(originX, originY- (int) (expMax*expScale), originX-5, originY- (int) (expMax*expScale));
                   //lable x axis
                   g.drawString("Late Cocoon", originX-27, originY+20);
                   g.drawString("Juvenile", originX-20+step, originY+20);
                   g.drawString("Adult", originX-20+(step*2), originY+20);
                   g.drawString("Growth stage", originX-36+step, originY+40);
                   //lable y axis
                   String fmt = "0.00#";
                   DecimalFormat df = new DecimalFormat(fmt);
                   int xs=originX; int ys=originY; int zs=(int)((controlMax/height)*0.25);
    //               g.drawString("x"+xs+" y"+ys+" zs"+zs+" controlMax"+controlMax+" scale"+scale, 0, originY+60);
                   g.drawString("0", originX-15, originY+4);
                   g.drawString(""+df.format((double)(controlMax*0.25)), originX-35, originY+4- (int) (controlMax*controlScale*0.25));//400*.5=200*.25=50
                   g.drawString(""+df.format((double)(controlMax*0.50)), originX-35, originY+4- (int) (controlMax*controlScale*0.5));
                   g.drawString(""+df.format((double)(controlMax*0.75)), originX-35, originY+4- (int) (controlMax*controlScale*0.75));
                   g.drawString(""+df.format(controlMax), originX-35, originY+4- (int) (controlMax*controlScale));
                   g.drawString("E", originX-100, originY-(int)(height*0.5)-50);
                   g.drawString("x", originX-100, originY-(int)(height*0.5)-40);
                   g.drawString("p", originX-100, originY-(int)(height*0.5)-30);
                   g.drawString("r", originX-100, originY-(int)(height*0.5)-20);
                   g.drawString("e", originX-100, originY-(int)(height*0.5)-10);
                   g.drawString("s", originX-100, originY-(int)(height*0.5));
                   g.drawString("s", originX-100, originY-(int)(height*0.5)+10);
                   g.drawString("i", originX-98, originY-(int)(height*0.5)+20);
                   g.drawString("o", originX-100, originY-(int)(height*0.5)+30);
                   g.drawString("n", originX-100, originY-(int)(height*0.5)+40);
         //If we don't specify this, the canvas might not show up at all
         //(depending on the layout manager).
         public Dimension getMinimumSize() {return new Dimension(550,300);}
         //If we don't specify this, the canvas might not show up at all
         //(depending on the layout manager).
         public Dimension getPreferredSize() {return getMinimumSize();}
         public void stop() {
              System.out.println("stopping...");
         public void destroy() {
              System.out.println("preparing to unload...");

    Thanks.
    I've tried moving the lines ...
    //Put checkboxes in the right box.
    canvasPanel.add(side);from the start method to the radio button listerner...
        // Listens to the radio buttons.
         public void actionPerformed(ActionEvent e) {
              System.out.println(""+e.getActionCommand());
              if (e.getActionCommand() == "Exp") {
                   checkBoxSetting[4]= true;
                   //Put checkboxes in the right box.
                   canvasPanel.add(side);
              if (e.getActionCommand() == "Con") {checkBoxSetting[4]= false;}
              repaint();
        }and into the paint method...
         public void paint(Graphics g) {
              System.out.println("Paint");
              if (checkBoxSetting[4]== true) {   //paint exposures
                   System.out.println("painting exposure");
                   //Put checkboxes in the right box.
                   canvasPanel.add(side);
                   //Draw the dataand in both cases the code complies and the applet runs without error messages but the panel is never displayed???

  • Indesign CC slows/stalls when Page panel drawing thumbnails

    Upgraded to InDesign CC on a 2012 MacPro workstation with 40GB of RAM running Mountain Lion. When I have a multipage file open, InDesign slows and essentially stalls while it slowly redraws Page panel thumbnails. I can turn the thumbnails off, once it finally finishes drawing them, but they're often very useful for navigation in a long document (only about 40 pages). I've tried restarting, changing the thumbnail sizes, etc. with no real effect on the stalling.

    We would need some additional information and if possible the file in which you are facing this issue.
    OS, machine configuration. You can email the file @ [email protected]
    Thanks in advance,
    Rohit

  • Crazy first gnome session - panels/drawing problems [SOLVED]

    I was following the Beginner's guide almost religiously apart from Xorg config (I have an Intel 950 GM on lenovo thinkpad r60e, i use the intel driver, not i810), where I did my best to configure conservatively. installed gnome, then as root:
    $ startx
    i got three shell windows
    $ gnome-session
    and get the following:
    every time a new window opens, i see its 'boundaries' first which hover with the pointer and then have to click to show it. as you can see, all the windows have panels displaying.
    couple other things, I cannot find an xsession-errors file. if it exists, where would it be?
    apologies for not being a code monkey. should i post my xorg.conf?
    Last edited by elephantos (2008-06-14 06:58:45)

    The behavior is perfectly expected.
    You did 'startx' as root. Root has no .xinitrc by default, so startx called xinit and xinit looked for /root/.xinitrc. Not finding it, xinit resorted to using /etc/X11/xinit/xinitrc. If you study /etc/X11/xinit/xinitrc, you will notice that it calls twm. So you opened a twm session, which has 3 terminals open by default, and then tried starting GNOME on top of twm, which worked out kind of half twm, half-GNOMISH.

  • How to draw a shape to Panel instead of draw to Frame

    I have a Frame and add a Panel into this Frame. I want to draw a shape to Panel instead of draw to Frame. how do i do?

    You can do two different things:
    1) For temporary drawings that will disappear when the component is repainted, you can use getGraphics() on the Panel, draw on the Graphics, then dispose the Graphics.
    2) For persistant drawings, subclass Panel and override the paint(Graphics g) method. Anything in there will be painted along with the panel. Start with super.paint(g); when you override for good coding practice.

  • Panel in Panel?

    Hi,
    I am new here and appologize if I posted in a wrong group.
    I created an image Panel drawing 2D graphics, polygons, rectangles, etc, in my applet. There is only one panel in my applet.
    If it's possible to put up a table, connected to DB, in the middle of the graphics after click the mouse event for certain range?
    Thank you for advance.
    Elvin

    For a overview of the layout managers and which stretch their children see https://blogs.oracle.com/ATEAM_WEBCENTER/entry/adf_faces_layout_containers_quick
    Timo

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

  • Calling a drawLine() from one class to another from an ActionEvent

    I have several JPanel objects called and placed on a JFrame. The JFrame has a RadioButton group with radio buttons. If I select a radio button and call a drawLine() method from a JPanel, I receive a "NullPointerException". Is it not possible to call this graphic method from one class to another?
    Thanks for any input you can provide.
    John

    Remember that each panel draws it's own current state. So you need the ActionPerformed to change the state in your target panel.
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class PanelComm extends JPanel {
      private SubPanelOne subPanelOne = new SubPanelOne();
      private SubPanelTwo subPanelTwo = new SubPanelTwo();
      public class SubPanelOne extends JPanel {
        public SubPanelOne () {
          setLayout ( new BorderLayout() );
          setBorder ( BorderFactory.createTitledBorder ( "SubPanel One" ) );
          Reactor     reactor    = new Reactor();
          ButtonGroup group      = new ButtonGroup();
          JPanel      radioPanel = new JPanel(new GridLayout(0, 1));
          JRadioButton buttonOne = new JRadioButton ( "One" );
          buttonOne.addActionListener ( reactor );
          group.add ( buttonOne );
          radioPanel.add ( buttonOne );
          JRadioButton buttonTwo = new JRadioButton ( "Two" );
          buttonTwo.addActionListener ( reactor );
          group.add ( buttonTwo );
          radioPanel.add ( buttonTwo );
          JRadioButton buttonThree = new JRadioButton ( "Three" );
          buttonThree.addActionListener ( reactor );
          group.add ( buttonThree );
          radioPanel.add ( buttonThree );
          add ( radioPanel ,BorderLayout.LINE_START );
        protected void paintComponent ( Graphics _g ) {
          super.paintComponent ( _g );
          Graphics2D g = (Graphics2D)_g;
          g.setRenderingHint ( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
      public class SubPanelTwo extends JPanel {
        private JLabel text = new JLabel();
        public SubPanelTwo () {
          setLayout ( new BorderLayout() );
          setBorder ( BorderFactory.createTitledBorder ( "SubPanel Two" ) );
          text.setFont ( new Font ( "Verdana" ,Font.PLAIN ,30 ) );
          text.setHorizontalAlignment ( JLabel.CENTER );
          add ( text ,BorderLayout.CENTER );
        protected void paintComponent ( Graphics _g ) {
          super.paintComponent ( _g );
          Graphics2D g = (Graphics2D)_g;
          g.setRenderingHint ( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
        public void setChoice ( String cmd ) {
          text.setText ( cmd );
      public class Reactor implements ActionListener {
        public void actionPerformed ( ActionEvent e ) {
          subPanelTwo.setChoice ( e.getActionCommand() );
      public PanelComm () {
        setLayout ( new GridLayout ( 1 ,2 ) );
        add ( subPanelOne );
        add ( subPanelTwo );
      //  main
      public static void main ( String[] args ) {
        JFrame f = new JFrame ( "Panel Communication" );
        f.setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE );
        f.getContentPane().add ( new PanelComm() ,BorderLayout.CENTER );
        f.setSize ( 320 ,120 );
        f.setVisible ( true );
      }  // main
    }

  • Who can help me :)--a problem with java program(reset problem in java )

    I do not know how to make the button reset,my program only could reset diagram but button.If any one who could help me to solve this problem.The problem is When the reset button is pressed, the image should immediately revert to the black square, and the 4 widgets listed above should show values that
    correspond to the black square.The code like this,first one is shapes:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class shapes extends JFrame {
         private JPanel buttonPanel; // panel for buttons
         private DrawPanel myPanel;  // panel for shapes
         private JButton resetButton;
        private JComboBox colorComboBox;
         private JRadioButton circleButton, squareButton;
         private ButtonGroup radioGroup;
         private JCheckBox filledButton;
        private JSlider sizeSlider;
         private boolean isShow;
         private int shape;
         private boolean isFill=true;
        private String colorNames[] = {"black", "blue", "cyan", "darkGray", "gray",
                                   "green", "lightgray", "magenta", "orange",
                                   "pink", "red", "white", "yellow"};   // color names list in ComboBox
        private Color colors[] = {Color.black, Color.blue, Color.cyan, Color.darkGray,
                              Color.gray, Color.green, Color.lightGray, Color.magenta,
                              Color.orange, Color.pink, Color.red, Color.white, Color.yellow};
         public shapes() {
             super("Draw Shapes");
             // creat custom drawing panel
            myPanel = new DrawPanel(); // instantiate a DrawPanel object
            myPanel.setBackground(Color.white);
             // set up resetButton
            // register an event handler for resetButton's ActionEvent
            resetButton = new JButton ("reset");
             resetButton.addActionListener(
              // anonymous inner class to handle resetButton events
                 new ActionListener() {
                       // draw a black filled square shape after clicking resetButton
                     public void actionPerformed (ActionEvent event) {
                             // call DrawPanel method setShowStatus and pass an parameter
                          // to decide if show the shape
                         myPanel.setShowStatus(true);
                             isShow = myPanel.getShowStatus();
                             shape = DrawPanel.SQUARE;
                         // call DrawPanel method setShape to indicate shape to draw
                             myPanel.setShape(shape);
                         // call DrawPanel method setFill to indicate to draw a filled shape
                             myPanel.setFill(true);
                         // call DrawPanel method draw
                             myPanel.draw();
                             myPanel.setFill(true);
                             myPanel.setForeground(Color.black);
                   }// end anonymous inner class
             );// end call to addActionListener
            // set up colorComboBox
            // register event handlers for colorComboBox's ItemEvent
            colorComboBox = new JComboBox(colorNames);
            colorComboBox.setMaximumRowCount(5);
            colorComboBox.addItemListener(
                 // anonymous inner class to handle colorComboBox events
                 new ItemListener() {
                     // select shape's color
                     public void itemStateChanged(ItemEvent event) {
                         if(event.getStateChange() == ItemEvent.SELECTED)
                             // call DrawPanel method setForeground
                             // and pass an element value of colors array
                             myPanel.setForeground(colors[colorComboBox.getSelectedIndex()]);
                        myPanel.draw();
                }// end anonymous inner class
            ); // end call to addItemListener
            // set up a pair of RadioButtons
            // register an event handler for RadioButtons' ItemEvent
             squareButton = new JRadioButton ("Square", true);
             circleButton = new JRadioButton ("Circle", false);
             radioGroup = new ButtonGroup();
             radioGroup.add(squareButton);
             radioGroup.add(circleButton);
            squareButton.addItemListener(
                // anonymous inner class to handle squareButton events
                new ItemListener() {
                       public void itemStateChanged (ItemEvent event) {
                           if (isShow==true) {
                                 shape = DrawPanel.SQUARE;
                                 myPanel.setShape(shape);
                                 myPanel.draw();
                   }// end anonymous inner class
             );// end call to addItemListener
             circleButton.addItemListener(
                   // anonymous inner class to handle circleButton events
                new ItemListener() {
                       public void itemStateChanged (ItemEvent event) {
                             if (isShow==true) {
                                 shape = DrawPanel.CIRCLE;
                                 myPanel.setShape(shape);
                                 myPanel.draw();
                             else
                                 System.out.println("Please click Reset button first");
                   }// end anonymous inner class
             );// end call to addItemListener
             // set up filledButton
            // register an event handler for filledButton's ItemEvent
            filledButton = new JCheckBox("Filled", true);
             filledButton.addItemListener(
              // anonymous inner class to handle filledButton events
            new ItemListener() {
                  public void itemStateChanged (ItemEvent event) {
                    if (isShow==true) {
                            if (event.getStateChange() == ItemEvent.SELECTED) {
                                  isFill=true;
                                  myPanel.setFill(isFill);
                                  myPanel.draw();
                            else {
                                isFill=false;
                                  myPanel.setFill(isFill);
                                  myPanel.draw();
                    else
                        System.out.println("Please click Reset button first");
              }// end anonymous inner class
             );// end call to addItemListener
            // set up sizeSlider
            // register an event handler for sizeSlider's ChangeEvent
            sizeSlider = new JSlider(SwingConstants.HORIZONTAL, 0, 300, 100);
            sizeSlider.setMajorTickSpacing(10);
            sizeSlider.setPaintTicks(true);
            sizeSlider.addChangeListener(
                 // anonymous inner class to handle sizeSlider events
                 new ChangeListener() {
                      public void stateChanged(ChangeEvent event) {
                          myPanel.setShapeSize(sizeSlider.getValue());
                             myPanel.draw();
                 }// end anonymous inner class
             );// end call to addChangeListener
            // set up panel containing buttons
             buttonPanel = new JPanel();
            buttonPanel.setLayout(new GridLayout(4, 1, 0, 50));
             buttonPanel.add(resetButton);
             buttonPanel.add(filledButton);
            buttonPanel.add(colorComboBox);
            JPanel radioButtonPanel = new JPanel();
            radioButtonPanel.setLayout(new GridLayout(2, 1, 0, 20));
            radioButtonPanel.add(squareButton);
            radioButtonPanel.add(circleButton);
            buttonPanel.add(radioButtonPanel);
            // attach button panel & draw panel to content panel
            Container container = getContentPane();
            container.setLayout(new BorderLayout(10,10));
            container.add(myPanel, BorderLayout.CENTER);
             container.add(buttonPanel, BorderLayout.EAST);
            container.add(sizeSlider, BorderLayout.SOUTH);
            setSize(500, 400);
             setVisible(true);
         public static void main(String args[]) {
             shapes application = new shapes();
             application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }second one is drawpanel:
    import java.awt.*;
    import javax.swing.*;
    public class DrawPanel extends JPanel {
         public final static int CIRCLE = 1, SQUARE = 2;
         private int shape;
         private boolean fill;
         private boolean showStatus;
        private int shapeSize = 100;
        private Color foreground;
         // draw a specified shape
        public void paintComponent (Graphics g){
              super.paintComponent(g);
              // find center
            int x=(getSize().width-shapeSize)/2;
              int y=(getSize().height-shapeSize)/2;
              if (shape == CIRCLE) {
                 if (fill == true){
                     g.setColor(foreground);
                      g.fillOval(x, y, shapeSize, shapeSize);
                else{
                       g.setColor(foreground);
                    g.drawOval(x, y, shapeSize, shapeSize);
              else if (shape == SQUARE){
                 if (fill == true){
                     g.setColor(foreground);
                        g.fillRect(x, y, shapeSize, shapeSize);
                else{
                        g.setColor(foreground);
                    g.drawRect(x, y, shapeSize, shapeSize);
        // set showStatus value
        public void setShowStatus (boolean s) {
              showStatus = s;
         // return showstatus value
        public boolean getShowStatus () {
              return showStatus;
         // set fill value
        public void setFill(boolean isFill) {
              fill = isFill;
         // set shape value
        public void setShape(int shapeToDraw) {
              shape = shapeToDraw;
        // set shapeSize value
        public void setShapeSize(int newShapeSize) {
              shapeSize = newShapeSize;
        // set foreground value
        public void setForeground(Color newColor) {
              foreground = newColor;
         // repaint DrawPanel
        public void draw (){
              if(showStatus == true)
              repaint();
    }If any kind people who can help me.
    many thanks to you!

    4 widgets???
    maybe this is what you mean.
    add this inside your actionPerformed method for the reset action
    squareButton.setSelected(true);
    colorComboBox.setSelectedIndex(0);
    if not be more clear in your post.

  • Make a check box in LiveCycle with a personal character or image as check mark ( info to share...)

    Hello everybody,
    It makes now several weeks i go trough the different forums to find a way to make the check mark of a check box in LiveCycle with a personal color instead of the default black mark, that seems to be the only option available.
    I saw somebody else with that question, but no answer.
    So i found a work around, that make the check box really flexible.
    Here it is:
    REMEMBER that this will work only with forms saved as dynamic PDF.
    Open a new form in Livecycle.
    1) Open Library panel ( Shift+F12) and select Check Box and put it in the page with the dimension and position you like and select it.
    Open the Object panel ( Shift+F7), select field section and under Caption make it blank. Select Binding Section and under name write in ' CheckBox '. for the rest leave all the section values as they are.
    2) In Library select, in the standard section, the icon for making a text object. Put it in the page and size it to your needs and put it on the top of the CheckBox. Select it.
    In the Object Panel, Draw section and under Presence 'Visible'.
    Open the Font panel ( Shift+F4) and under font section, Font : select the Wingdings font and choose the symbol to use as the mark, under Size : the size you need, under Style: font color you like. If the result of the mark is to your feel, set the object to 'invisible'. Leave all other values as they are.
    Open the Hierarchy panel (Shift+F11), right click on the static object and rename it to ' CheckMarkModel ' .
    For information : changing the text object to an image object let's you use an image for the mark in the checkbox.
    3) In Library, select in the standard section the icon for making a Button. Put it in the page and size it to the CheckBox dimension and put it on the top of the text object. Select it. In the Object panel, under Caption : make it blank, under Appearance : select custom in the drop down list an in the dialog box that comes up set the edges to none and the
    background to none. Leave the rest as it is.
    Open the Hierarchy panel (Shift+F11), right click on the Button object and rename it to ' ClickCheckBoxButton ' .
    Now open the Script Editor (Shift+Ctrl+F5), on the left under Show : select in the list the ' Click ' event, under Language : select JavaScript, copy to the window the following script :
    if (CheckMarkOnOff.rawValue == "0")
    CheckMarkOnOff.rawValue = "1";
    CheckMarkModel.presence = "visible";
    else if (CheckMarkOnOff.rawValue == "1")
    CheckMarkModel.presence = "invisible";
    CheckMarkOnOff.rawValue = "0";
    4)Now put in the page an other Check Box, put it on the top of the Button object and select it. In the Object panel, Field section, under Caption : make it blank, under Appearance : none, under Presence : invisible, let the rest as it is. In the Value section, under Type : Read Only, under Default : Off. In the Binding section, under Name : name it CheckMarkOnOff, leave the rest as it is.
    5) So you have now four objects in the page 1. In the Hierarchy panel set each object by dragging them in
    this order :
    CheckBox
    CheckMarkModel
    ClickCheckBoxButton
    CheckMarkOnOff
    In the form select all the objects and group them. If you copy the group as many times you need you automatically will have an other Check Box, ready to work.
    So here you are with an personal Check Box.
    Don't forget to set the preview PDF to dynamic under Menu /File/Form Properties, the in the dialog box that shows up /Default tab and under the XDP Preview format : select in the list an Acrobat Dynamic form.
    REMEMBER that this will work only with forms saved as dynamic PDF.
    If somebody from Adobe could upload the sample file i made, to the forum, so that anybody can download it to his computer, would be appreciated, email me at : [email protected] .
    Regards Mike.

    I also faced this same problem and there is an actual solution but it involves modifying the xml source for the checkbox - however it is a simple modification so if your not familiar with editing the xml source don't worry about that. <br /><br />Click on the checkbox you want to modify and then click on the XML Source tab. LiveCycle will take you to that point in the XML. <br /><br />Now, scroll down until the close of the ui node( </ui> )within the checkbox field and modify the font node to look like the following:<br /><br /></ui>  -- close of UI node<br /><font typeface="Arial"><br />   <fill><br />      <color value="0,0,255"/><br />   </fill><br /></font><br /><br />This produces a checkbox with a blue check mark. <br />You can, of course, make the color any RGB number you want.<br /><br />You can then save that field in your library and reuse it anytime you want and it will always have that color checkmark. <br /><br />Good luck. <br />-Andrew

  • Help me It's Urgent check my code and solve the puzzle.......

    Hi,
    Im adding my code below...my problem is when i add text to my panel....whenver it exceeds it's not scrolling try to help me plzzzzzzzzzzz
    /*<applet code=ScrollPaneTest.class height=300 width=300>
    </applet>*/
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    class NewPanel extends JPanel
         int x=30;
         int y=40;
         NewPanel()
         this.setBackground(Color.white);
         public void draw(String str)
         Graphics g=getGraphics();
         Font font=new Font("TypeWriter", Font.BOLD, 15);
         g.setFont(font);
         g.setColor(Color.red);
         g.drawString(str, x, y);
         y=y+20;
    public class ScrollPaneTest extends JApplet implements ActionListener
         JTextField text;
         JButton send;
         NewPanel panel;
         JScrollPane pane;
         Container contentPane;
         JPanel southPanel;
         JTextArea textArea;
         public void init()
              contentPane=getContentPane();
              southPanel=new JPanel();
              textArea=new JTextArea();
              contentPane.setLayout(new BorderLayout());
              text=new JTextField(20);
              send=new JButton("Send");
              panel=new NewPanel();
              pane=new JScrollPane(panel);
              southPanel.setLayout(new FlowLayout());
              southPanel.add(text);
              southPanel.add(send);
              contentPane.add(southPanel, BorderLayout.SOUTH);
              contentPane.add(pane);
              send.addActionListener(this);
         public void actionPerformed(ActionEvent e)
              JButton button=(JButton)e.getSource();
              if(button.getText().equals("Send"))
                   String str=text.getText();
                   panel.draw(str);
                   //textArea.append(str);
                   //textArea.append("\n");
    It's working for TextArea but it's not working for panel...anyone can help me to solve this
    Thanks in Advance!

    Use real code tags (see Formatting tips before you post). Have you ever tried to preview your posting?
    Why do you want to draw Strings on a JPanel in the first place (as apposed to do what normal people do, that is use some kind of JTextComponent)? Is it because you want a different Border or background color than the JTextArea's defaults?

  • How do I replace one video file with another

    Hey all
    I'm new to Imovie, so please bare over with me.
    I made a long movie using a MOD format file from my JVC home camera
    When I where to convert or burn the movie in Imovie it made an error.
    After much trouble I found out that it was the MOD format that was the problem
    So I bought an expensive piece of software that converted the MOD file to MOV:
    And with a new test project it now works flawless...
    Anyways back to the original project and the problem:
    - I have now converted the original MOD file to MOV
    - I have the original Imovie project with the MOD file.
    How do I replace the mod file in the imovie project with the new mov file, while keeping, that is transfering all my work on the mod file over to the new mov file?
    Thnx
    Kris

    • In the Layers Panel draw the Layer’s Vector Mask icon onto the trashcan-icon
    • move that Layer above the new Text Layer
    • invoke Create Clipping Mask (command-alt-G) from Layers Panel’s fly-out menu or alt-click on the line separating the two Layers’ icons

  • How do I replace one vector mask with another?

    I have a template for a web site that I'm trying to figure out as I learn CS5.  The template has a vector mask created out of some writing that was converted into an object/vector mask.  I would like to replace with a layer I created that has different writing in it.  How would I replace the vector mask in the template with the new object I created?
    Thanks for any help you can give.
    Best -- Catherine

    • In the Layers Panel draw the Layer’s Vector Mask icon onto the trashcan-icon
    • move that Layer above the new Text Layer
    • invoke Create Clipping Mask (command-alt-G) from Layers Panel’s fly-out menu or alt-click on the line separating the two Layers’ icons

  • RePaint() bug or doing something wrong?

    Im writing an application which consist of a JFrame and two JPanels.
    They are laid out with a BoxLayout.
    The upper JPanel basiclly draws an image out.
    The lower JPanel is listening for mousemotionevents from the upper JPanel. Whenever a mousemotion events occur I write the x,y - coords of the mouse out in the lower JPanel.
    The lower JPanel's code look somthing like this:
    public class LowerPanel extends JPanel implements MouseMotionListener{
    UpperPanel.addMouseMotionListener(this);
    public void mouseMoved(MouseEvent e){
    updating x,y coords..
    repaint();
    public void paint(Graphics e){
         e.clearRect(10,10,100,50);
         e.drawString("Coordinates of mouse.... x,y=...");
    Now to the problem.. when the program starts everything looks ok with two panels, the upper panel showing the image and the lower panel drawing the "default" coords of 0,0. As soon as I start moving the mouse inside the upper panel the image of the upper panel is drawn inside the lower Panel as well?! Except from that everything works as it should. The coords are updating when I move the mouse but.. with the upper panels image as background to it heh.. does anyone know what is causing this and how to fix it? Please :]

    to make the problem more clear:
    It seems like the lower Panel captures the upper Panel's output somehow and draws it out before drawing it's own content. (?!)
    I really need help with this one.. no idea what im doing wrong. :[                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • A problem with java program(reset problem in java GUY)

    I do not know how to make the button reset,my program only could reset diagram but button.If any one who could help me to solve this problem.The problem is When the reset button is pressed, the image should immediately revert to the black square, and the 4 widgets listed above should show values that
    correspond to the black square.
    import java.awt.*;
    import javax.swing.*;
    public class DrawPanel extends JPanel {
         public final static int CIRCLE = 1, SQUARE = 2;
         private int shape;
         private boolean fill;
         private boolean showStatus;
        private int shapeSize = 100;
        private Color foreground;
         // draw a specified shape
        public void paintComponent (Graphics g){
              super.paintComponent(g);
              // find center
            int x=(getSize().width-shapeSize)/2;
              int y=(getSize().height-shapeSize)/2;
              if (shape == CIRCLE) {
                 if (fill == true){
                     g.setColor(foreground);
                      g.fillOval(x, y, shapeSize, shapeSize);
                else{
                       g.setColor(foreground);
                    g.drawOval(x, y, shapeSize, shapeSize);
              else if (shape == SQUARE){
                 if (fill == true){
                     g.setColor(foreground);
                        g.fillRect(x, y, shapeSize, shapeSize);
                else{
                        g.setColor(foreground);
                    g.drawRect(x, y, shapeSize, shapeSize);
        // set showStatus value
        public void setShowStatus (boolean s) {
              showStatus = s;
         // return showstatus value
        public boolean getShowStatus () {
              return showStatus;
         // set fill value
        public void setFill(boolean isFill) {
              fill = isFill;
         // set shape value
        public void setShape(int shapeToDraw) {
              shape = shapeToDraw;
        // set shapeSize value
        public void setShapeSize(int newShapeSize) {
              shapeSize = newShapeSize;
        // set foreground value
        public void setForeground(Color newColor) {
              foreground = newColor;
         // repaint DrawPanel
        public void draw (){
              if(showStatus == true)
              repaint();
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class shapes extends JFrame {
         private JPanel buttonPanel; // panel for buttons
         private DrawPanel myPanel;  // panel for shapes
         private JButton resetButton;
        private JComboBox colorComboBox;
         private JRadioButton circleButton, squareButton;
         private ButtonGroup radioGroup;
         private JCheckBox filledButton;
        private JSlider sizeSlider;
         private boolean isShow;
         private int shape;
         private boolean isFill=true;
        private String colorNames[] = {"black", "blue", "cyan", "darkGray", "gray",
                                   "green", "lightgray", "magenta", "orange",
                                   "pink", "red", "white", "yellow"};   // color names list in ComboBox
        private Color colors[] = {Color.black, Color.blue, Color.cyan, Color.darkGray,
                              Color.gray, Color.green, Color.lightGray, Color.magenta,
                              Color.orange, Color.pink, Color.red, Color.white, Color.yellow};
         public shapes() {
             super("Draw Shapes");
             // creat custom drawing panel
            myPanel = new DrawPanel(); // instantiate a DrawPanel object
            myPanel.setBackground(Color.white);
             // set up resetButton
            // register an event handler for resetButton's ActionEvent
            resetButton = new JButton ("reset");
             resetButton.addActionListener(
              // anonymous inner class to handle resetButton events
                 new ActionListener() {
                       // draw a black filled square shape after clicking resetButton
                     public void actionPerformed (ActionEvent event) {
                             // call DrawPanel method setShowStatus and pass an parameter
                          // to decide if show the shape
                         myPanel.setShowStatus(true);
                             isShow = myPanel.getShowStatus();
                             shape = DrawPanel.SQUARE;
                         // call DrawPanel method setShape to indicate shape to draw
                             myPanel.setShape(shape);
                         // call DrawPanel method setFill to indicate to draw a filled shape
                             myPanel.setFill(true);
                         // call DrawPanel method draw
                             myPanel.draw();
                             myPanel.setFill(true);
                             myPanel.setForeground(Color.black);
                   }// end anonymous inner class
             );// end call to addActionListener
            // set up colorComboBox
            // register event handlers for colorComboBox's ItemEvent
            colorComboBox = new JComboBox(colorNames);
            colorComboBox.setMaximumRowCount(5);
            colorComboBox.addItemListener(
                 // anonymous inner class to handle colorComboBox events
                 new ItemListener() {
                     // select shape's color
                     public void itemStateChanged(ItemEvent event) {
                         if(event.getStateChange() == ItemEvent.SELECTED)
                             // call DrawPanel method setForeground
                             // and pass an element value of colors array
                             myPanel.setForeground(colors[colorComboBox.getSelectedIndex()]);
                        myPanel.draw();
                }// end anonymous inner class
            ); // end call to addItemListener
            // set up a pair of RadioButtons
            // register an event handler for RadioButtons' ItemEvent
             squareButton = new JRadioButton ("Square", true);
             circleButton = new JRadioButton ("Circle", false);
             radioGroup = new ButtonGroup();
             radioGroup.add(squareButton);
             radioGroup.add(circleButton);
            squareButton.addItemListener(
                // anonymous inner class to handle squareButton events
                new ItemListener() {
                       public void itemStateChanged (ItemEvent event) {
                           if (isShow==true) {
                                 shape = DrawPanel.SQUARE;
                                 myPanel.setShape(shape);
                                 myPanel.draw();
                   }// end anonymous inner class
             );// end call to addItemListener
             circleButton.addItemListener(
                   // anonymous inner class to handle circleButton events
                new ItemListener() {
                       public void itemStateChanged (ItemEvent event) {
                             if (isShow==true) {
                                 shape = DrawPanel.CIRCLE;
                                 myPanel.setShape(shape);
                                 myPanel.draw();
                             else
                                 System.out.println("Please click Reset button first");
                   }// end anonymous inner class
             );// end call to addItemListener
             // set up filledButton
            // register an event handler for filledButton's ItemEvent
            filledButton = new JCheckBox("Filled", true);
             filledButton.addItemListener(
              // anonymous inner class to handle filledButton events
            new ItemListener() {
                  public void itemStateChanged (ItemEvent event) {
                    if (isShow==true) {
                            if (event.getStateChange() == ItemEvent.SELECTED) {
                                  isFill=true;
                                  myPanel.setFill(isFill);
                                  myPanel.draw();
                            else {
                                isFill=false;
                                  myPanel.setFill(isFill);
                                  myPanel.draw();
                    else
                        System.out.println("Please click Reset button first");
              }// end anonymous inner class
             );// end call to addItemListener
            // set up sizeSlider
            // register an event handler for sizeSlider's ChangeEvent
            sizeSlider = new JSlider(SwingConstants.HORIZONTAL, 0, 300, 100);
            sizeSlider.setMajorTickSpacing(10);
            sizeSlider.setPaintTicks(true);
            sizeSlider.addChangeListener(
                 // anonymous inner class to handle sizeSlider events
                 new ChangeListener() {
                      public void stateChanged(ChangeEvent event) {
                          myPanel.setShapeSize(sizeSlider.getValue());
                             myPanel.draw();
                 }// end anonymous inner class
             );// end call to addChangeListener
            // set up panel containing buttons
             buttonPanel = new JPanel();
            buttonPanel.setLayout(new GridLayout(4, 1, 0, 50));
             buttonPanel.add(resetButton);
             buttonPanel.add(filledButton);
            buttonPanel.add(colorComboBox);
            JPanel radioButtonPanel = new JPanel();
            radioButtonPanel.setLayout(new GridLayout(2, 1, 0, 20));
            radioButtonPanel.add(squareButton);
            radioButtonPanel.add(circleButton);
            buttonPanel.add(radioButtonPanel);
            // attach button panel & draw panel to content panel
            Container container = getContentPane();
            container.setLayout(new BorderLayout(10,10));
            container.add(myPanel, BorderLayout.CENTER);
             container.add(buttonPanel, BorderLayout.EAST);
            container.add(sizeSlider, BorderLayout.SOUTH);
            setSize(500, 400);
             setVisible(true);
         public static void main(String args[]) {
             shapes application = new shapes();
             application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }Many thanks

    Who is this Java guy anyway?

Maybe you are looking for

  • Routine coding in infopackage

    Hi ABAP fans I need to extract the data package from the current day (sy-dat). The only availabe date field in the source system has a length of 14: YYYYMMDDHHMMSS. I would like to extract via this field, but need to manipulate it in the way of sy-da

  • Safari not displaying Facebook properly

    Since yesterday, Safari stopped displaying Facebook properly. I get a white page with no formatting, just a column of links. That is the only site I have problems with. All others seem to work fine and Facebook displays properly if I'm using Firefox.

  • Paying for calls to my skype to go numbers

    WHY IS NO ONE REPLYING TO THESE **bleep**IN TEXES   I HAVE A PROBLEM WITH MY SKYPE TO GO NUMBERS ON MY MOBILE AS IT TAKING MY MINUTES FROM MY VODAPHONE PLAN AND THIS MONTH THEY HAVE CHARGED ME $25 DOLLARS I HAVE  A $20 CREDIT WITH SKYPE SOME ONE PLEA

  • No icon of the photoshop

    After purchasing CC and downloading The Photoshop and The Lightroom, I have only Lightroom icon and no Photoshop icon on the desktop. Where it is?

  • I started my subscription to Creative Cloud before I knew it would not be ready until June

    Can I put my subscription on hold until Illustrator is available as a Creative Cloud App?