Cant do setColor(Color.BLACK); to a graphic object inside a class

i have a graphic object inside a class:
JPanel panel = new JPanel();
Graphic lienzo = areadibujo.getGraphic();
and then i cant do this:
lienzo.setColor(Color.BLACK);
netbeans error:
<identifier> expected
i just can do that inside a method from the class...

HI i found the problem.
The problem is that when i create the graphic object i do this:
Graphics lienzo = areadibujo.getGraphics();
areadibujo.getGraphics(); returns null so when i try to do something like lienzo.drawline(1,1,200,200); it just says nullpointer error, i guess at the time i create graphic object the panel "areadibujo" is not still created because the frame doesnt still shows, i can correct this by copying Graphics lienzo = areadibujo.getGraphics(); inside a actionperfmoded or other event method , but i dont wanna do that, where does the panel object already is created in constructor?.... i dont know if i explain my self well or how can i force areadibujo.getGraphics() to return something...

Similar Messages

  • How to change font/ font color etc in a graphic object using JCombobox?

    Hello
    My program im writing recently is a small tiny application which can change fonts, font sizes, font colors and background color of the graphics object containing some strings. Im planning to use Jcomboboxes for all those 4 ideas in implementing those functions. Somehow it doesnt work! Any help would be grateful.
    So currently what ive done so far is that: Im using two classes to implement the whole program. One class is the main class which contains the GUI with its components (Jcomboboxes etc..) and the other class is a class extending JPanel which does all the drawing. Therefore it contains a graphics object in that class which draws the string. However what i want it to do is using jcombobox which should contain alit of all fonts available/ font sizes/ colors etc. When i scroll through the lists and click the one item i want - the graphics object properties (font sizes/ color etc) should change as a result.
    What ive gt so far is implemented the jcomboboxes in place. Problem is i cant get the font to change once selecting an item form it.
    Another problem is that to set the color of font - i need to use it with a graphics object in the paintcomponent method. In this case i dnt want to create several diff paint.. method with different property settings (font/ size/ color)
    Below is my code; perhaps you'll understand more looking at code.
    public class main...
    Color[] Colors = {Color.BLUE, Color.RED, Color.GREEN};
            ColorList = new JComboBox(Colors);
    ColorList.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent ev) {
                     JComboBox cb = (JComboBox)ev.getSource();
                    Color colorType = (Color)cb.getSelectedItem();
                    drawingBoard.setBackground(colorType);
              });;1) providing the GUI is correctly implemented with components
    2) Combobox stores the colors in an array
    3) ActionListener should do following job: (but cant get it right - that is where my problem is)
    - once selected the item (color/ font size etc... as i would have similar methods for each) i want, it should pass the item into the drawingboard class (JPanel) and then this class should do the job.
    public class DrawingBoard extends JPanel {
           private String message;
           public DrawingBoard() {
                  setBackground(Color.white);
                  Font font = new Font("Serif", Font.PLAIN, fontSize);
                  setFont(font);
                  message = "";
           public void setMessage(String m) {
                message = m;
                repaint();
           public void paintComponent(Graphics g) {
                  super.paintComponent(g);
                  //setBackground(Color.RED);
                  Graphics2D g2 = (Graphics2D) g;
                  g2.setRenderingHint             
                  g2.drawString(message, 50, 50);
           public void settingFont(String font) {
                //not sure how to implement this?                          //Jcombobox should pass an item to this
                                   //it should match against all known fonts in system then set that font to the graphics
          private void settingFontSize(Graphics g, int f) {
                         //same probelm with above..              
          public void setBackgroundColor(Color c) {
               setBackground(c);
               repaint(); // still not sure if this done corretly.
          public void setFontColor(Color c) {
                    //not sure how to do this part aswell.
                   //i know a method " g.setColor(c)" exist but i need to use a graphics object - and to do that i need to pass it in (then it will cause some confusion in the main class (previous code)
           My problems have been highlighted in the comments of code above.
    Any help will be much appreciated thanks!!!

    It is the completely correct code
    I hope that's what you need
    Just put DrawingBoard into JFrame and run
    Good luck!
    public class DrawingBoard extends JPanel implements ActionListener{
         private String message = "message";
         private Font font = new Font("Serif", Font.PLAIN, 10);
         private Color color = Color.RED;
         private Color bg = Color.WHITE;
         private int size = 10;
         public DrawingBoard(){
              JComboBox cbFont = new JComboBox(GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames());
              cbFont.setActionCommand("font");
              JComboBox cbSize = new JComboBox(new Integer[]{new Integer(14), new Integer(13)});
              cbSize.setActionCommand("size");
              JComboBox cbColor = new JComboBox(new Color[]{Color.BLUE, Color.RED, Color.GREEN});
              cbColor.setActionCommand("color");
              JComboBox cbBG = new JComboBox(new Color[]{Color.BLUE, Color.RED, Color.GREEN});
              cbBG.setActionCommand("bg");
              add(cbFont);
              cbFont.addActionListener(this);
              add(cbSize);
              cbSize.addActionListener(this);
              add(cbColor);
              cbColor.addActionListener(this);
              add(cbBG);
              cbBG.addActionListener(this);
         public void setMessage(String m){
              message = m;
              repaint();
         protected void paintComponent(Graphics g){
              super.paintComponent(g);
              Graphics2D g2 = (Graphics2D)g;
              g2.setColor(bg);//set background color
              g2.fillRect(0,0, getWidth(), getHeight());          
              g2.setColor(color);//set text color
              FontRenderContext frc = g2.getFontRenderContext();
              TextLayout tl = new TextLayout(message,font,frc);//set font and message
              AffineTransform at = new AffineTransform();
              at.setToTranslation(getWidth()/2-tl.getBounds().getWidth()/2,
                        getWidth()/2 + tl.getBounds().getHeight()/2);//set text at center of panel
              g2.fill(tl.getOutline(at));
         public void actionPerformed(ActionEvent e){
              JComboBox cb = (JComboBox)e.getSource();
              if (e.getActionCommand().equals("font")){
                   font = new Font(cb.getSelectedItem().toString(), Font.PLAIN, size);
              }else if (e.getActionCommand().equals("size")){
                   size = ((Integer)cb.getSelectedItem()).intValue();
              }else if (e.getActionCommand().equals("color")){
                   color = (Color)cb.getSelectedItem();
              }else if (e.getActionCommand().equals("bg")){
                   bg = (Color)cb.getSelectedItem();
              repaint();
    }

  • I cant get it to work! NullPointerExeption at first awt.Graphics Object

    I am writing a game with AWT having it as an applet. I intend NOT to use anything outside of Java 1.1
    For my Game i thought that i ATLEAST need the following classes:
    MainGame, Level, Unit.
    I Started writing Level. wrote a fewe methods for it such as
    drawGras(int grastype) And started to write MainGame to see if they would work together. it's is/is going to be my first Java application where i actually know what object orienting is... I have already wrote a game in Java but with out knowing what a class or what object orienting realy is(the game works rather good to) but this time i wanted to use object orienting but came up with problems =( if first posted in "New to Javaprogramming" but they couldn't help me and advice me here
    My previous post: http://forum.java.sun.com/thread.jsp?forum=54&thread=290558
    Here's my code:
    import java.awt.*;
    public class MainGame extends java.applet.Applet
         implements Runnable {
         Thread runner;
         Image ImgLevel, ImgUnit;
         public MainGame() {
              Level nr1 = new Level();
              nr1.init();
              nr1.setGround(300);
              nr1.drawGras(1);
              nr1.CalcGraphics();
              nr1.drawSky(1);
              Image ImgLevel = nr1.getLevelImage();
         public void paint(Graphics g) {
              g.drawImage(ImgLevel,0,0,this);
         public void update(Graphics g) {
              paint(g);
         public void init() {
              MainGame Game = new MainGame();
         public void stop() {
              runner = null;
              System.exit(1);
         public void start() {
              if(runner == null) {
                   runner = new Thread(this);
                   runner.start();
         void Pause(int time) {
             try {
                 Thread.sleep(time);
             } catch(InterruptedException e) {
               System.out.println(e.toString());
         public void run() {
              Thread thisThread = Thread.currentThread();
                   while(thisThread == runner) {
    class Level extends java.applet.Applet {
        Font BigText = new Font("Arial", Font.PLAIN, 36);
        Font Normal = new Font("Arial", Font.PLAIN, 14);
        Font Bold = new Font("Arial", Font.BOLD, 14);
        Graphics GrLevel;
        int pattern, sky, GroundtoWalk, Ground;
        Color BgColor = new Color(166,202,240);
        Color gras1 = new Color(0,255,0);
        Color gras2 = new Color(0,200,0);
        Color gras3 = new Color(0,100,0);
        Image ImgLevel;
        void setBgColor(int r, int g, int b) {
            BgColor = new Color(r,g,b);
        void CalcGraphics() {
            ImgLevel = createImage(800,600);
            GrLevel = ImgLevel.getGraphics();
        void setGround(int GrounD) {
            Ground = GrounD;
        void GroundToWalkADD(int addToGround) {
            GroundtoWalk = Ground + addToGround;
        void setGroundToWalk(int GrToWalk) {
            GroundtoWalk = GrToWalk;
        public void init() {
              System.out.println("Init 1"); // This was placed here when i was checking how far it got when debuging
              CalcGraphics();
              System.out.println("Init 2");
              drawGras(1);
              System.out.println("Init 3");
              repaint();
              System.out.println("Init 4");
        Image getLevelImage() {
            return ImgLevel;
        public void paint(Graphics g) {
              g.drawImage(ImgLevel,0,0,this);
        public void update(Graphics g) {
            paint(g);
        void drawGras(int pt) {
         GrLevel.setColor(BgColor);
         GrLevel.fillRect(0,0,800,600);
         switch(pt) {
              case 1:
                   GrLevel.setColor(gras1);
                   GrLevel.fillRect(0,GroundtoWalk,800,300);
                   GrLevel.setClip(0,GroundtoWalk,800,300);
                   for(int i = 0; 890>i;i=i+5) {
                        GrLevel.setColor(gras2);
                        GrLevel.drawLine(0+i,GroundtoWalk,-190+i,GroundtoWalk+300);
                   for(int i=950; 0<i; i=i-5) {
                        GrLevel.setColor(gras3);
                        GrLevel.drawLine(890-i,GroundtoWalk,1000-i,GroundtoWalk+300);
              break;
              case 2:
                   GrLevel.setColor(gras2);
                   GrLevel.fillRect(0,GroundtoWalk+5,800,300);
                   for(int i = 0; 890>i;i=i+5) {
                        GrLevel.setColor(gras3);
                        GrLevel.drawLine(0+i,GroundtoWalk,-190+i,GroundtoWalk+300);
                   for(int i=950; 0<i; i=i-5) {
                        GrLevel.setColor(gras1);
                        GrLevel.drawLine(890-i,GroundtoWalk,1000-i,GroundtoWalk+300);
              break;
              case 3:
                   GrLevel.setColor(gras3);
                   GrLevel.fillRect(0,GroundtoWalk+10,800,300);
                   for(int i = 0; 800>i; i=i+20) {
                        GrLevel.fillArc(0+i,GroundtoWalk,20,20,180,-180);
              break;
         pattern = pt;
        int getGrasPattern() {
             return pattern;
        void drawSky(int cl) {
                GrLevel.setColor(BgColor);
                GrLevel.fillRect(0,0,800,155);
                switch(cl) {
                    case 1:
                   for(int y = 0;y<7;y++) {
                   for(int x = 0;x<800;x=x+20) {
                                GrLevel.setColor(Color.white);
                                GrLevel.drawArc(x,y*20,20,20,180,180);
                                GrLevel.setColor(Color.red);
                                GrLevel.drawArc(x,y*20+4,20,20,180,180);
                                GrLevel.setColor(Color.yellow);
                                GrLevel.drawArc(x,y*20+2,20,20,180,180);
                                GrLevel.setColor(Color.green);
                                GrLevel.drawArc(x,y*20+8,20,20,180,180);
                                GrLevel.setColor(Color.blue);
                                GrLevel.drawArc(x,y*20+12,20,20,180,180);
                                GrLevel.setColor(Color.pink);
                                GrLevel.drawArc(x,y*20+16,20,20,180,180);
              break;
              case 2:
                        GrLevel.setColor(Color.gray);
              break;
         sky = cl;
         GrLevel.setFont(BigText);
         GrLevel.setColor(Color.black);
         GrLevel.fillRect(0,0,800,50);
         GrLevel.setColor(Color.white);
         GrLevel.drawString("Score Tabel - comming someday",((size().width)/2)-260, 40);
        int getSkyTyp() {
             return sky;
    }I tested running the code of class Level by puting it into Level.java and compiled it...ran it with appletviewer and it worked as it was intended to.
    But when i compiled it with MainGame... and in the HTML started MainGame.class,.....applet didn't intializeand i got the following error messege:
    Init 1
    java.lang.NullPointerException
            at Level.CalcGraphics(MainGame.java:84)
            at MainGame.<init>(MainGame.java:11)Line 82: void CalcGraphics() {
    Line 83: ImgLevel = createImage(800,600);
    Line 84: GrLevel = ImgLevel.getGraphics(); // The First awt.Graphics object
    Line 85: }
    Line 9:      public MainGame() {
    Line 10:     Level nr1 = new Level();
    Line 11:     nr1.CalcGraphics(); // calling the method above -> same error first awt.Graphics Object.
    If i change it os that "drawGras" comes first it's first awt.Graphics Line will show the same error
    Hope some one can and will help me

    As per the documentation of
    java.awt.Component.createImage(int,int):
    Creates an off-screen drawable image to be used for
    double buffering.
    Parameters:
    width - the specified width
    height - the specified height
    Returns:
    an off-screen drawable image, which can be used for
    double buffering. The return value may be null if the
    component is not displayable. This will always happen
    if GraphicsEnvironment.isHeadless() returns true.
    Since:
    JDK1.0 its not
    ImgLevel = createImage(800,600); that's making the problem but The first awt.Graphics Object in class Level, no mather which on it is =((
    >
    The key part is '...may be null if the component is
    not displayable.'
    You should put your graphics initialization code in
    start(), which will be called when your applet is
    ready to go. Before then, your applet is not
    displayable. (Also, remember to dispose() your
    graphics in your stop() method, if not sooner.)for the part writen above...I'll try to change it like you are saying.
    Thanx for your help!

  • How do I set color in IndexColorModel for Graphics

    I can't find a reasonable way to set the color so my test code is below:
    The IndexColorModel, BufferedImage, and Graphics2D construction is:
    IndexColorModel icm4=new IndexColorModel(4,16,r4,g4,b4);
    BufferedImage bi4=new
    BufferedImage(300,200,BufferedImage.TYPE_BYTE_BINARY,icm4);
    Graphics2D bi4g2=bi4.createGraphics(); where most of the rest of the code is:
    byte[]r4=new byte[] {000,(byte)255,(byte)000,(byte)000,(byte)255,(byte)255,(byte)000,(byte)255,(byte)255,(byte)255,(byte)100,(byte)150,(byte)200,(byte)255,(byte)000,(byte)000};
    byte[]g4=new byte[] {000,(byte)000,(byte)255,(byte)000,(byte)255,(byte)000,(byte)255,(byte)255,(byte)075,(byte)127,(byte)100,(byte)150,(byte)200,(byte)255,(byte)000,(byte)000};
    byte[]b4=new byte[] {000,(byte)000,(byte)000,(byte)255,(byte)000,(byte)255,(byte)255,(byte)255,(byte)000,(byte)127,(byte)100,(byte)150,(byte)200,(byte)175,(byte)000,(byte)000};
    bi4g2.setColor(Color.black);
    bi4g2.drawString("bi4g2.drawString black",20,10);
    bi4g2.setColor(Color.red  );
    bi4g2.drawString("bi4g2.drawString red",20,20);
    bi4g2.setColor(Color.green);
    bi4g2.drawString("bi4g2.drawString green",20,30);
    bi4g2.setColor(Color.blue );
    bi4g2.drawString("bi4g2.drawString blue",20,40);
    bi4g2.setColor(Color.cyan );
    bi4g2.drawString("bi4g2.drawString cyan",20,50);
    bi4g2.setColor(Color.gray );
    bi4g2.drawString("bi4g2.drawString gray",20,60);
    bi4g2.setColor(Color.pink );
    bi4g2.drawString("bi4g2.drawString pink",20,70);
    bi4g2.setColor(Color.white);
    bi4g2.drawString("bi4g2.drawString white",20,80);
    bi4g2.setColor(Color.orange);
    bi4g2.drawString("bi4g2.drawString orange",20,90);
    bi4g2.setColor(Color.yellow);
    bi4g2.drawString("bi4g2.drawString yellow",20,100);
    bi4g2.setColor(Color.magenta);
    bi4g2.drawString("bi4g2.drawString magenta",20,110);
    bi4g2.setColor(Color.darkGray);
    bi4g2.drawString("bi4g2.drawString darkGray",20,120);
    bi4g2.setColor(Color.lightGray);
    bi4g2.drawString("bi4g2.drawString lightGray",20,130); What is the correct way to set color?
    This doesn't work so well, but it sort of works.

    Are you talking about ePubs or iBook Author which is a similar but separate application.
    Pages doesn't have spreads, you have to construct the adjacent pages with each half of any textboxes or images on the left and right hand pages of a spread.
    Peter

  • Draw to an image using graphics object

    ive been trying to this. create a starfield 800px wide and twice the height of the screen 2x600. this image would be scrolling down the screen giving the appearance of moving through space. what i did was create an image the called "starField", and created a graphics object "starFieldObj" to draw dots (stars) to this image.
    is this the correct way to do this? my program seems to work differently depending on where i call "generateStarField()" which draws to "starFieldObj"
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    public class Alpha1 extends Canvas implements Runnable, MouseMotionListener, MouseListener, KeyListener {
         private Image buffer; //bufer image
         private Graphics gfx;
         private Graphics starFieldObj;
         private Image playerShip;
         private int frames = 60; //frames per second
         private MediaTracker mediaTracker; //tracks loaded images
         private boolean ready; //ready to  start animation
         private int [] keys = new int[256];
         private int playerShipX = 100;
         private int playerShipY = 100;
         private static Random random = new Random();
         private Image starField;
         private int starFieldSpeed = 5;
         private int starFieldX = 0;
         private int starFieldY = -600;
         public static void main(String[] args)
              Alpha1 t = new Alpha1();
              Frame f = new Frame("blah");
              f.setSize(800, 600);
              f.add(t, BorderLayout.CENTER);
              f.show();
              t.start();
              t.requestFocus();
              f.addWindowListener(new WindowAdapter(){
                   public void windowClosing(WindowEvent e){
                        System.exit(0);}});
         public Alpha1()
              addKeyListener(this);
              addMouseListener(this);
              ready = false;
              mediaTracker = new MediaTracker(this);
              playerShip = getToolkit().getImage("testship1.png");
              //starField = getToolkit().getImage("testbg.png");
              //mediaTracker.addImage(playerShip, 0);
              mediaTracker.addImage(starField, 0);
              try {
                   mediaTracker.waitForID(0);
              catch (InterruptedException e) {
                   e.printStackTrace();
         public void start()
              buffer = createImage(getSize().width,getSize().height);
              //starField = createImage(getSize().width,getSize().height * 2);
              gfx = buffer.getGraphics();
              //starFieldObj = starField.getGraphics();
              generateStarfield();
              ready = true;
              new Thread(this).start();
         public void mouseDragged(MouseEvent e)     {}
         public void mouseMoved(MouseEvent e)     
              playerShipX = e.getX();
              playerShipY = e.getY();
         public void mouseReleased(MouseEvent e)     {}
         public void mousePressed(MouseEvent e)     {}
         public void mouseExited(MouseEvent e)     {}
         public void mouseEntered(MouseEvent e)  {}
         public void mouseClicked(MouseEvent e)     {}
         public void keyTyped(KeyEvent keyevent)     {}
         public void keyPressed(KeyEvent keyevent)
              keys[keyevent.getKeyCode()] = 1;
              System.out.println(keyevent.getKeyCode());
         public void keyReleased(KeyEvent keyevent)     
              keys[keyevent.getKeyCode()] = 0;
         public void run()
              while (true)
                   if (isVisible())
                        repaint();
                        updatePositions();
                   }//end if
                   try 
                   { Thread.sleep(1000/frames); }
                   catch (InterruptedException e)
                   { e.printStackTrace(); }
              }//end while
         public void paint(Graphics g) {     /*empty etc*/ }
         public void updatePositions()
              if (keys[38] == 1 & keys[40] == 0) //IF UP IS PRESSED
              { playerShipY -= 3; }
              if (keys[40] == 1 & keys[38] == 0) //IF DOWN IS PRESSED
              { playerShipY += 6; }
              if (keys[37] == 1 & keys[39] == 0) //IF LEFT IS PRESSED
              { playerShipX -= 5; }
              if (keys[39] == 1 & keys[37] == 0) //IF RIGHT IS PRESSED
              { playerShipX += 5; }
              //starFieldY = starFieldY + starFieldSpeed;
              //if (starFieldY == 0)
              //     starFieldY = -600;
              //     System.out.println("dadssa");
         public int getRandom(int from, int to)
              if (from > to)
                   int randTemp;
                   randTemp = from;
                   from = to;
                   to = randTemp;
              return random.nextInt(to-from+1)+from;
         public void generateStarfield()
              starFieldObj.setColor(Color.black);
              starFieldObj.fillRect (0, 0, 800, 600 * 2);
              for (int td=0; td < 900 ; td++) //draw 900x2 dots on 800x1200 image
                        starFieldObj.fillRect (getRandom(1,800), getRandom(1,600), 1, 1);
                        starFieldObj.fillRect (getRandom(1,800) + 800, getRandom(1,600) + 800, 1, 1);
         public void update(Graphics g)
              if (ready)
                   gfx.setColor(Color.black);
                   gfx.fillRect (0, 0, this.getSize().width, this.getSize().height);
                   //gfx.drawImage(starField,starFieldX,starFieldY,null);
                   gfx.drawImage(playerShip,playerShipX,playerShipY,null);
                   //gfx.drawString(Integer.toString(showFps),5,5);
                   g.drawImage(buffer,0,0,null);
    }

    updated code, i cant get starField to be 1200px in height
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    public class Alpha1 extends Canvas implements Runnable, MouseMotionListener, MouseListener, KeyListener {
         private Image buffer; //bufer image
         private Graphics gfx;
         private Graphics starFieldObj;
         private Image playerShip;
         private int frames = 60; //frames per second
         private MediaTracker mediaTracker; //tracks loaded images
         private boolean ready; //ready to  start animation
         private int [] keys = new int[256];
         private int playerShipX = 100;
         private int playerShipY = 100;
         private static Random random = new Random();
         private Image starField;
         private int starFieldSpeed = 5;
         private int starFieldX = 0;
         private int starFieldY = -600;
         public static void main(String[] args)
              Alpha1 t = new Alpha1();
              Frame f = new Frame("blah");
              f.setSize(800, 600);
              f.add(t, BorderLayout.CENTER);
              f.show();
              t.start();
              t.requestFocus();
              f.addWindowListener(new WindowAdapter(){
                   public void windowClosing(WindowEvent e){
                        System.exit(0);}});
         public Alpha1()
              addKeyListener(this);
              addMouseListener(this);
              ready = false;
              mediaTracker = new MediaTracker(this);
              playerShip = getToolkit().getImage("testship1.png");
              //starField = getToolkit().getImage("testbg.png");
              //mediaTracker.addImage(playerShip, 0);
              mediaTracker.addImage(starField, 0);
              try {
                   mediaTracker.waitForID(0);
              catch (InterruptedException e) {
                   e.printStackTrace();
         public void start()
              buffer = createImage(getSize().width,getSize().height);
              starField = createImage(getSize().width,1200);
              gfx = buffer.getGraphics();
              starFieldObj = starField.getGraphics();
              ready = true;
              new Thread(this).start();
         public void mouseDragged(MouseEvent e)     {}
         public void mouseMoved(MouseEvent e)     
              playerShipX = e.getX();
              playerShipY = e.getY();
         public void mouseReleased(MouseEvent e)     {}
         public void mousePressed(MouseEvent e)     {}
         public void mouseExited(MouseEvent e)     {}
         public void mouseEntered(MouseEvent e)  {}
         public void mouseClicked(MouseEvent e)     {}
         public void keyTyped(KeyEvent keyevent)     {}
         public void keyPressed(KeyEvent keyevent)
              keys[keyevent.getKeyCode()] = 1;
              System.out.println(keyevent.getKeyCode());
         public void keyReleased(KeyEvent keyevent)     
              keys[keyevent.getKeyCode()] = 0;
         public void run()
              generateStarfield();
              while (true)
                   if (isVisible())
                        repaint();
                        updatePositions();
                   }//end if
                   try 
                   { Thread.sleep(1000/frames); }
                   catch (InterruptedException e)
                   { e.printStackTrace(); }
              }//end while
         public void paint(Graphics g) {     /*empty etc*/ }
         public void updatePositions()
              if (keys[38] == 1 & keys[40] == 0) //IF UP IS PRESSED
              { playerShipY -= 3; }
              if (keys[40] == 1 & keys[38] == 0) //IF DOWN IS PRESSED
              { playerShipY += 6; }
              if (keys[37] == 1 & keys[39] == 0) //IF LEFT IS PRESSED
              { playerShipX -= 5; }
              if (keys[39] == 1 & keys[37] == 0) //IF RIGHT IS PRESSED
              { playerShipX += 5; }
              starFieldY = starFieldY + starFieldSpeed;
              if (starFieldY == 0)
                   starFieldY = -600;
                   System.out.println("dadssa");
         public int getRandom(int from, int to)
              if (from > to)
                   int randTemp;
                   randTemp = from;
                   from = to;
                   to = randTemp;
              return random.nextInt(to-from+1)+from;
         public void generateStarfield()
              starFieldObj.setColor(Color.black);
              starFieldObj.fillRect (0, 0, 800, 1200);
              for (int td=0; td < 900 ; td++) //draw 900x2 dots on 800x1200 image
                        starFieldObj.setColor(Color.white);
                        starFieldObj.fillRect (getRandom(1,800), getRandom(1,600), 1, 1);
                        starFieldObj.fillRect (getRandom(1,800) + 800, getRandom(1,600) + 800, 1, 1);
         public void update(Graphics g)
              if (ready)
                   gfx.setColor(Color.black);
                   //gfx.fillRect (0, 0, this.getSize().width, this.getSize().height);
                   gfx.drawImage(starField,starFieldX,starFieldY,null);
                   gfx.drawImage(playerShip,playerShipX,playerShipY,null);
                   //gfx.drawString(Integer.toString(showFps),5,5);
                   g.drawImage(buffer,0,0,null);
    }

  • Handing Graphics Object To Run() Method

    Hi,
    I have written code that draws 20 x 20 lines over a bufferedimage and the performs calculations on each of the cells created by this division.
    I want to be able to show a blue square over the cell currently being worked on. As the calculations progress the square moves from cell to cell until complete.
    The problem I face is that when i have my buffered image displayed and then run through the calculations the whole process is done so fast that you never see the blue square moving you just see the completed state. The obvious answer to this is to use a thread but how do I hand "Graphics g" to a thread as an argument? Whenever I try
    public void run(Graphics g)I get a compile error saying that the class should be declared abstract. Is it ever possible to hand run() an argument?
    Any other suggestions as to how I can show this drawing process slow enough to be visible to the user?

    Look at this:
    import java.awt.event.*;
    import java.awt.*;
    public class Barc extends Frame 
         mapPanel     map  = new mapPanel();
         Calc         calc = new Calc(map);
    public Barc()
         addWindowListener(new WindowAdapter()
        {     public void windowClosing(WindowEvent ev)
              {     dispose();
                   System.exit(0);}});
         setBounds(10,10,500,440);
         add(map);     
         setVisible(true);
         new Thread(calc).start();
    public class mapPanel extends Panel
         int cell = -1;
         int xc,yc;
    public mapPanel()
    public void paintCell(int c)
         if (cell != -1)
              yc = (cell/20)*20+2 ;
              xc = (cell%20)*20+2;
               repaint(xc,yc,17,17);
         cell = c;
         yc = (cell/20) * 20+2 ;
         xc = (cell%20)*20+2;
         repaint(xc,yc,17,17);
    public void update(Graphics g)
         paint(g);
    public void paint(Graphics g)
         Rectangle r = g.getClipBounds();
         g.setColor(Color.pink);
         g.fillRect(r.x,r.y,r.width,r.height);
         g.setColor(Color.black);
         for (int x=0; x < 21; x++) g.drawLine(x*20,0,x*20,400);
         for (int y=0; y < 21; y++) g.drawLine(0,y*20,400,y*20);
         if (cell != -1)
              g.setColor(Color.blue);
              g.fillRect(xc,yc,17,17);
    public class Calc implements Runnable
         mapPanel  map;
    public Calc(mapPanel m)
         map       = m;
    public synchronized void run()
         int    i = 0;     
         double d = 1000;
         while (i < 400)
               map.paintCell(i++);
              for (int r=0; r < 1111111; r++) d = d/124.67*131.46;
    public static void main(String[] args )
         new Barc();
    Noah

  • How do you set the font color for a specific entire row inside a JTable?

    How do you set the font color for a specific entire row inside a JTable?
    I want to change the font color for only a couple of rows inside a JTable.
    I've seen some ways to possibly do this with an individual cell.
    Clarification on changing the font color in an individual cell would be helpful too if
    there is no easy way to do this for a row.

    hai,
    Try out with this piece of code.Create your table and assign the renderer to each column in the table.
    CellColorRenderer m_CellColorRenderer = new CellColorRenderer();
    for(int i=0;i<your_JTable.getColumnCount();i++)
    your_JTable.getColumnModel().getColumn(i).setCellRenderer(m_CellColorRenderer);
    class CellColorRenderer extends JLabel implements TableCellRenderer
    CellColorRenderer()     
    setOpaque(true);     
    setHorizontalAlignment(LEFT);
    setVerticalAlignment(CENTER);
    setBackground(Color.white);
    setForeground(Color.black);
    protected void setValue(Object value)
         setText((value == null) ? "" : value.toString());
    public Component getTableCellRendererComponent(JTable table,Object value,boolean isSelected, boolean hasFocus, int row,int column)
         if(isSelected == true)
              setForeground(Color.red);
         else
              setForeground(Color.black);
         setValue(value);
         return this;
    regards,
    bala

  • Changing Graphics object

    Hoa can I change the color properties of the graphics object of one component in another component?

    The short answer is you can't. Graphics objects are not part of the state of a
    component -- they are created when rendering needs to be done and
    are disposed afterwards. Also, the same graphics object is shared: the same
    graphics objects is adjusted and used to repaint a frame and all its components,
    for example.
    Components do have some "graphical" state, however, like their foreground
    and background color and font. What is your goal?

  • Is there a script to change black and white graphics to a color?

    I have a folder of black and white graphics.  I want to change them all to a color quickly without having to open each one and change the color, preferably in a new folder.   Is this possible?

    Good day!
    Please check out the chapter "Automation" in the Reference.
    If the task can be recorded as a plain Action it can be applied to multiple Files for example via File > Automate > Batch or File > Scripts > Image Processor.
    Regards,
    Pfaffenbichler

  • JComponent.setbackground(Color.BLACK) is NOT working

    I am creating Space Invaders game and have GamePanel as my JComponent, named panel. The background is not changing for sum reason though???
    import java.awt.*;
    import javax.swing.*;
    public class SpaceInvaders{
         //variables
         public static final int WIDTH = 800;
         public static final int HEIGHT = 800;
         GamePanel panel;
         public SpaceInvaders()
              //create frame
              JFrame demoFrame = new JFrame("Space Invaders");
              demoFrame.setBounds(0,0,WIDTH,HEIGHT);
              demoFrame.setVisible(true);
              demoFrame.setResizable(false);
              demoFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              demoFrame.setBackground(Color.BLACK);
              //create panel
              GamePanel panel = new GamePanel(this);
              panel.setBackground(Color.BLACK);
              demoFrame.add(panel);
              //add buttons
              JButton startButton = new JButton("Start");
              startButton.setEnabled(true);
              JButton stopButton = new JButton("Stop");
              stopButton.setEnabled(true);
    ..... import java.awt.*;
    import javax.swing.*;
    import java.awt.Image;
    import java.awt.event.KeyListener;
    import java.awt.event.KeyEvent;
    import java.awt.image.BufferStrategy;
    import javax.swing.*;
    import java.awt.event.*;
    public class GamePanel extends JComponent implements KeyListener, ActionListener
         SpaceInvaders game;
         static Player player1;
         Bullets bullet;
         private BufferStrategy strategy;
         static int alienNum = 36;
         static int alienRow = 6;
         static int alienCol = 6;
         static Aliens[][] aliens;
         static Bullets[] bullets;
         private Timer timer;
         int bulletNum=0;
         public GamePanel(SpaceInvaders game)
              this.game = game;
              player1 = new Player(this);
              player1.start();
              aliens = new Aliens[alienRow][alienCol];
              for(int i=0; i<alienRow; i++)
                   for(int j=0; j<alienCol; j++){
                        aliens[i][j] = new Aliens(this);
                        aliens[i][j].setX(i*50);
                        aliens[i][j].setY(j*50);
              bullets = new Bullets[5];
                   bullets[0]=new Bullets(this);
              timer=new Timer(500, this);
              //timer.setDelay(500);
              timer.start();
              this.setFocusable(true);
            this.addKeyListener(this);
         public void paintComponent(Graphics g)
              super.paintComponent(g);
              Image pic1 = player1.getImage();
    ...........

    I changed the GamePanel class to extend JPanel instead of extend JComponent and it works now. Didnt realise JComponent had no paint functions.. Thanks for your help.
    import java.awt.image.BufferStrategy;
    import javax.swing.*;
    import java.awt.event.*;
    public class GamePanel extends JPanel implements KeyListener, ActionListener
         SpaceInvaders game;
         static Player player1;
         Bullets bullet;
         private BufferStrategy strategy;

  • Font.setColor(Color.blue);   for labels.

    Hi,
    I am having some trouble with changing the colour of my font:
    The colour was fine until my OS was updated and now it has changed from that nice purplish(#666699 ) to black.
    Is there anyway of saying something like:
    Font myFont = new Font("Garamond", Font.BOLD, 24);
    myFont.setColor(Color.blue);
    or even an rgb value? I dont want to paint it to a canvas - it is for a label.
    Thanks in advance,
    K

    by the way, you can use RGB codes if you want. So like if you wanted say a navy blue, you could do:
    label.setForeground(new Color(0,0,100));

  • New Quad-G5 with Apple 30" display WON'T DISPLAY THE COLOR BLACK???!!!!

    Just got this system up and running with all my software and for some reason if I show video with an all black screen there are blue lines tarnishing the image. If I let the computer go to sleep and then wake it up any black is afflicted with the same problem. Now if just the display goes to sleep (not the computer) and it gets woken up then the problem just occurs in video again. HELP! This computer should be able to display the color black.

    Sounds like a video card issue.

  • OSX.6 change filename color black to white on dark background

    OSX.6 change filename color black to white on dark background

    Thanks for that, but what I asking was how to change the OSX default filename font color from black to white, so it becomes more easily visible when dark backgrounds are selected in icon view, eg the same way the Desktop default does, except when files are not on the Desktop.
    or to put it another way:
    if anyone's worked out an easy way to how to change the color of the font itself, rather than changing the folder/filename background using File, Label, Color, eg because light colors may already be in use as Labels, and so mean something else.
    or as explored in this archived discussion:
    How to change the color of the file name Font in Finder window and Desktop
    https://discussions.apple.com/thread/1744863?threadID=1744863
    Perhaps this is easy for programmers but not for users???

  • Spot colors Black, All have the same alternate color values

    If printer’s mark [Crop, Registration, Page] is enable in the InDesign preset options, we are getting “Spot colors Black, All have the same alternate color values” error in the PITSTOP log report.

    Rob, here's screenshot of Acrobats Output Preview Object Inspector. You can download my PDF here - //www.fileswap.com/dl/Q1CzzOzEqt/
    I'm not sure if CM was assigned to document when created or  afterwards. In Color Settings preferences is stated Fogra 39 (if it matters - document was meanwhile saved and opened...). Are there other options to assign workspace to exsisting document?
    Peter, this is not the case. Placed image has embeded same color profile as is working space of document in ID. I tried the same with sRGB image placed in same ID document and compared it to PS but color shift (greenish) is present - it looks exactly the same.
    Guys, I can't tell you how happy I am to have you help me with this terrible and nerve-wracking problem.

  • Cannot Find Color Black in Color Picker

    I would like to use the color black with the Adjustment Brush, but I cannot locate the color black in the Color Picker that appears when I click on the color swatch in the Adjustment Brush dialog. Could anyone give me a clue? In particular, I'd like to create an Adjustment Brush preset that includes painting with the color black. Thanks.

    Consider what the color brush does. It it designed to not impact luminance, only tint! So when you brush with a color with saturation 0 (the grey at the bottom), nothing will happen! Only something will happen when you have a color with a certain saturation selected. If you want to lower the luminance of something, use the brightness slider on the brush, or the exposure slider.

Maybe you are looking for

  • Multiple accounts, one computer

    We have several family members using itunes, with several different ipods. We would all like to purchase tunes from the itunes store with independent sources - credit cards, gift cards etc. When a gift card is enabled, it remains active until fully u

  • System.close() and resources

    Hi, in my application I start many threads, and them open files. Those threads are like daemons waiting for changes in those files. If i.e. a critical error is detected, is valid to finish the app a "System.exit()", or do I have to close every file a

  • Final Cut Server Client Error won't start Application

    Hello I am new to Final Cut Server 1.1 I have setup the server on a Mac Pro Intel based with 8Gb of memory 2x3.2Ghz Quad Core processor. the server is running fine I am able to connect to it from another workstation (windows and MAC) through the web

  • How do you reset your account information to change country?

    I have arrived in spain and now it only gives me spain as my country. This means i cannot upgrade to premium as my credit card is a New Zealand and doesnt match. Why is it only giving me one country option? Help please!

  • How do I set my iphone to tether with my samsung galaxy note 10.1

    How di I set my iphone 4si to tether with my samsung galaxy note 10.1