SetColor not working

In an Applet, in the paint(), the color never changes and the default color (black) is always set. Why this is not working?
String[] colores = ("blue", "cyan", "green", "magenta", "orange", "pink", "red", "yellow", "black", "lightGray", "darkGray", "gray" };
h=0;
for(i=1; i<=numero_personas; i++){
if(str1.compareTo(str2[i]) == 0){
h++;
g.setColor(Color.getColor(colores[h]));
else
g.setColor(Color.getColor(colores[h]));
g.draw3DRect(21,21, 100 ,5,true);
g.fill3DRect(21,21, 100 ,5,true);
I think I'm not using getColor correctly. I dont want to use [Color.blue | Color.red | ...]. In order to change the color depending on the string comparison, What do I need to do?
Thanks

Ahem, yes, except for the fact that the "colores"
thing is not a member of the Colors class, hence the
error on the line that includes:I'm to tired...Sorry...
getColor public static Color getColor(String nm)Finds a color in the
system properties.
The argument is treated as the name of a system property to be
obtained. The string value of this property is then interpreted as an integer which is then converted to a Color object.
If the specified property is not found or could not be parsed as an integer then null is returned
Since I've noticed you're Spanish, from Valencia I suppose, isn't this method searching the colors in english in a spanish OS?? This way it wount find anything I suppose...Not sure about this, but try in the
colores array to writte them in spanish....
Hope it helps,
ANeto

Similar Messages

  • Cutom.xss Not working in R12

    Hi ,
    I have done some color change on a table column based on certain condition. which is working fine in 11i instance but when i have migrated the same in R12 it is not working.
    Code in (PR) :
    OALinkBean bean1 = (OALinkBean)webBean.findChildRecursive("Addi1");
    if (thsholdVal<CalThVAl)
    { row.setcolor("1");
    OADataBoundValueViewObject cssjob1 = new OADataBoundValueViewObject(bean1,"color");
    bean1.setAttributeValue(oracle.cabo.ui.UIConstants.STYLE_CLASS_ATTR, cssjob1);
    else
    row.setcolor("2");
    OADataBoundValueViewObject cssjob1 = new OADataBoundValueViewObject(bean1,"color");
    bean1.setAttributeValue(oracle.cabo.ui.UIConstants.STYLE_CLASS_ATTR, cssjob1);
    Custom.xss code: (Location $OA_HTML/cabo/styles)
    <style selector=".2">
    <includeStyle name="DefaultFontFamily"/>
    <property name="background-color">#00FF00</property>
    </style>
    <style selector=".1">
    <includeStyle name="DefaultFontFamily"/>
    <property name="background-color">#FF0000</property>
    </style>
    Please give me a response if i missed any thing or i need to make some R12 specific change.

    I don't think there is a specific change required for R12. Have you bounced the Apache after replacing the custom.xss file?
    Thanks
    Shree

  • Drawstring is not working in Linux !!!

    hi everbody
    Graphics.drawString is not working properly on Linux ,
    how can i fix it.
    what is problem.
    on XP , 10gR2 db evertything is ok. 326x160 picture and "Sample Text." seen on browser.
    on Oracle Unbrakeble Linux , 11g db 326x160 picture seen on browser but "Sample Text." absent on picture !!!!!
    complete code is below
    Thanks.
    create or replace and compile java source named java1 as
    import java.awt.*;
    import java.awt.image.BufferedImage;
    import java.io.*;
    import com.sun.image.codec.jpeg.JPEGCodec;
    import com.sun.image.codec.jpeg.JPEGImageEncoder;
    public class MyGraph
    public static byte[] vcanvas (int width ,int height ) throws IOException
    BufferedImage bimage = new BufferedImage(width,height, BufferedImage.TYPE_INT_RGB);
    Graphics g = bimage.createGraphics();
    g.setColor(Color.white);
    g.fillRect(0, 0, width - 1, height - 1);
    g.setColor(Color.red);
    g.drawRect(0,0,width-1,height-1);
    g.setColor(Color.black);
    g.drawRect(2,2,width-3,height-3);
    g.drawString("Sample Text.",10,height/2);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    JPEGImageEncoder jpeg = JPEGCodec.createJPEGEncoder(baos);
    jpeg.encode(bimage);
    baos.flush();
    baos.close();
    return baos.toByteArray();
    } // MyGraph
    create or replace function javaimage(w number,h number) return varchar2
    as LANGUAGE JAVA name 'MyGraph.vcanvas(int, int) return byte[]';
    create or replace procedure imgXYZ is
    vData varchar2(32767);
    begin
    owa_util.mime_header('image/jpeg', FALSE );
    owa_util.http_header_close;
    vData:=javaimage(326,160);
    htp.prn(vData);
    end;
    http://server:port/schema/imgXYZ

    You have to start Http server for that :
    $ $ORACLE_HOME/Apache/Apache/bin/apachectl start

  • Code is not working

    below is my code. It is not working. When i click launch on wireless toolkit suddenly this line, java.io.IOException, appears in output panel on netbeans 6.5. Nothing is launched on wireless toolkit. Please help
    import javax.microedition.midlet.*;
    import javax.microedition.lcdui.*;
    public class GameMIDlet extends MIDlet {
    private Display display;
    public void startApp() {
    try {
    display = Display.getDisplay(this);
    SimpleGameCanvas gameCanvas = new SimpleGameCanvas();
    gameCanvas.start();
    display.setCurrent(gameCanvas);
    } catch (Exception ex) {
    System.out.println(ex);
    public Display getDisplay() {
    return display;
    public void pauseApp() {
    public void destroyApp(boolean unconditional) {
    exit();
    public void exit() {
    System.gc();
    destroyApp(false);
    notifyDestroyed();
    import javax.microedition.lcdui.*;
    import javax.microedition.lcdui.game.*;
    public class SimpleGameCanvas extends GameCanvas implements Runnable {
    private boolean isPlay; // Game Loop runs when isPlay is true
    private long delay; // To give thread consistency
    private int currentX, currentY; // To hold current position of the 'X'
    private int width; // To hold screen width
    private int height; // To hold screen height
    // Sprites to be used
    private Sprite sprite;
    private Sprite nonTransparentSprite;
    // Constructor and initialization
    public SimpleGameCanvas() throws Exception {
    super(true);
    width = getWidth();
    height = getHeight();
    currentX = width / 2;
    currentY = height / 2;
    delay = 20;
    // Load Images to Sprites
    Image image = Image.createImage("couple.gif");
    sprite = new Sprite(image, 32, 32);
    Image imageTemp = Image.createImage("couple.gif");
    nonTransparentSprite = new Sprite(imageTemp, 32, 32);
    // Automatically start thread for game loop
    public void start() {
    isPlay = true;
    Thread t = new Thread(this);
    t.start();
    public void stop() {
    isPlay = false;
    // Main Game Loop
    public void run() {
    Graphics g = getGraphics();
    while (isPlay == true) {
    input();
    drawScreen(g);
    try {
    Thread.sleep(delay);
    } catch (InterruptedException ie) {
    // Method to Handle User Inputs
    private void input() {
    int keyStates = getKeyStates();
    sprite.setFrame(0);
    // Left
    if ((keyStates & LEFT_PRESSED) != 0) {
    currentX = Math.max(0, currentX - 1);
    sprite.setFrame(1);
    // Right
    if ((keyStates & RIGHT_PRESSED) != 0) {
    if (currentX + 5 < width) {
    currentX = Math.min(width, currentX + 1);
    sprite.setFrame(3);
    // Up
    if ((keyStates & UP_PRESSED) != 0) {
    currentY = Math.max(0, currentY - 1);
    sprite.setFrame(2);
    // Down
    if ((keyStates & DOWN_PRESSED) != 0) {
    if (currentY + 10 < height) {
    currentY = Math.min(height, currentY + 1);
    sprite.setFrame(4);
    // Method to Display Graphics
    private void drawScreen(Graphics g) {
    g.setColor(0xFF0000);
    g.fillRect(0, 0, getWidth(), getHeight());
    g.setColor(0x0000ff);
    // display sprites
    sprite.setPosition(currentX, currentY);
    sprite.paint(g);
    nonTransparentSprite.paint(g);
    flushGraphics();
    }

    I have used e.printStackTrace() .. and below is the result
    java.lang.IllegalArgumentException
         at javax.microedition.lcdui.game.Sprite.<init>(+41)
    Uncaught exception java/lang/NullPointerException.
         at SimpleGameCanvas.<init>(+67)
         at GameMIDlet.startApp(+15)
         at javax.microedition.midlet.MIDletProxy.startApp(+7)
         at com.sun.midp.midlet.Scheduler.schedule(+270)
         at com.sun.midp.main.Main.runLocalClass(+28)
         at com.sun.midp.main.Main.main(+80)

  • 'NAVIGATE_ABSOLUTE' method is not working in UWL

    We are working on Portal 7.0.
    Recently We have upgraded from SP 13-0 To 13-5.
    After this upgradation We are facing some problems, following is the scenario:
    1.     We have a ABAP Web DynPro Application say 'A', which has button "View Details".
    2.     On Clicking of "View_Details"  We navigate to other ABAP Web DynPro Application say 'B' .
         This was done using the 'NAVIGATE_ABSOLUTE' method of the 'IF_WD_PORTAL_INTEGRATION'.
    3.     Now The Same Application 'A' is being send as the Workitem to Approver's inbox.
    4.     Approver also was able to click on 'View_Details' button and  Application 'B' used to call using 'NAVIGATE_ABSOLUTE'.
    5.     After upgradation, Point 2 is working fine. but point 4 is not working i.e. 'NAVIGATE_ABSOLUTE' functionality is not working when the application is send as workitem.
    Please guide us for the above problem. Points assured for best solution.

    Hi
    Thanks for your reply. Actually i wrote simple applets and those are working well.
    So i did debug the code and i found that when i am running the following code in Apple MAC IE, nothing is happening in handleEvent method. Especially it is not going into the if statement (if (evt.id==401)). here i am checking for KEY_PRESS. I also tried with keyDown method but same problem in MAC IE.
    I am pasting the code that is giving me problem.
    import java.awt.*;
    import java.applet.*;
    public class testApplet extends Applet
    public void init()
    setLayout(new BorderLayout());
    editableArea = new EditableArea();
    editableArea.setBackground(Color.yellow);
    add("Center", editableArea);
    EditableArea editableArea;
    import java.awt.*;
    public class EditableArea extends Canvas
    String s = "";
    public boolean handleEvent(Event evt)
    if (evt.id==401)
    if(evt.key >= 32 && evt.key <= 255)
    char c = (char)evt.key;
    s = s + c;
    repaint();
    return super.handleEvent(evt);
    public void paint( Graphics g )
    g.setColor(Color.blue);
    g.drawString( s,5,15);
    --------------------------------------------------------------------

  • Why does my JButton not work?

    Hi,
    I am programming a Traffic Light, consisting of 3 lights, and a caption describing who's Traffic Light it is. Traffic Lights are to be used inside a bigger program. But as it is, I'm trying out how to program one Traffic Light.
    I created a Light object. A TrafficLight object contains 3 of these objects, and a caption. The TrafficLight object is to be used as a button, so the user can push it, after which some magic has to happen, which I still need to develop. The problem I have is the button does not work.
    So, the relevant parts of the code. First the main:
         public static void main (String [] args) {
              JFrame frame = new JFrame();
              frame.setBounds(0, 0, 100, 400);
              TrafficLight light = new TrafficLight("Caption", "ERR", true);
              frame.add(light);
              // frame.pack();
              frame.setVisible(true);
         }Then the TrafficLight object:
        public TrafficLight () {
            setUp();
        private void setUp() {
         JComponent component = createComponent();
         add(component);
         setVisible (true);
        private JComponent createComponent () {
            JPanel panel = new JPanel(null);
            panel.setBounds (xCoordinate, yCoordinate, WIDTH, HEIGHT);
            JButton tlsButton = new JButton();
            tlsButton.setBounds(xCoordinate, yCoordinate, WIDTH, HEIGHT);
            boolean isOn = true;
            boolean isNewProblem = true;
            tlsButton.setActionCommand(name);
            tlsButton.addActionListener(this);
            // Create the lights
            redLight = new TlsLight (0, 0, Color.RED, isOn, isNewProblem);
            tlsButton.add(redLight);
            yellowLight = new TlsLight (0, WIDTH, Color.YELLOW, !isOn, isNewProblem);
            tlsButton.add(yellowLight);
            greenLight = new TlsLight (0, 2 * WIDTH, Color.GREEN, isOn, !isNewProblem);
            tlsButton.add(greenLight);
            tlsButton.add(customerLabel, Component.CENTER_ALIGNMENTl);
            panel.add(tlsButton);
            return panel;
        }And, finally, the TlsLight object:
        public void paint (Graphics graphics) {
            setSize(width, width);
            int diameter = width - 2 * insets;
            // Paint the background (square) based on if the Customer has a new problem or not
            if(isNewProblem) {
                background = Color.GRAY;
            else {
                background = Color.BLACK;
            graphics.setColor(background);
            graphics.fillRect(xPos, yPos, width, height);
            // Set color light based on problemStatus
            if(isOn) {
                graphics.setColor(theColor);
            } else {
                graphics.setColor(background);
            graphics.fillOval(xPos + insets, yPos + insets, diameter, diameter);
            // Set the background of the light
            graphics.setColor(Color.WHITE);       
            // Paint the background
            graphics.drawOval(xPos + insets, yPos + insets, diameter, diameter);
        }When I push the button, nothing happens. Do you know what I need to do to get my prog working?
    TIA,
    Abel

    I don't know what goes on in your ActionListener, but I have a feeling that something is missing there.
    public TrafficLight () {
            setUp();
        private void setUp() {
         JComponent component = createComponent();
         add(component);
         setVisible (true);
        private JComponent createComponent () {
            JPanel panel = new JPanel(null);
            panel.setBounds (xCoordinate, yCoordinate, WIDTH, HEIGHT);
            JButton tlsButton = new JButton();
            tlsButton.setBounds(xCoordinate, yCoordinate, WIDTH, HEIGHT);
            boolean isOn = true;
            boolean isNewProblem = true;
            tlsButton.setActionCommand(name);
            //tlsButton.addActionListener(this);
            tlsButton.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent evt){
                            System.out.println("Hello World!"); //Implement with you own stuff....
            // Create the lights
            redLight = new TlsLight (0, 0, Color.RED, isOn, isNewProblem);
            tlsButton.add(redLight);
            yellowLight = new TlsLight (0, WIDTH, Color.YELLOW, !isOn, isNewProblem);
            tlsButton.add(yellowLight);
            greenLight = new TlsLight (0, 2 * WIDTH, Color.GREEN, isOn, !isNewProblem);
            tlsButton.add(greenLight);
            tlsButton.add(customerLabel, Component.CENTER_ALIGNMENTl);
            panel.add(tlsButton);
            return panel;
        }

  • KeyListener not working in Linux

    Hello guys, I'm having a weird problem I was hoping I could get resolved.
    I finished a Pong applet for my Java class, and it works just fine under Windows and on my Mac.
    But when I run it under Linux, the Applet doesn't work correctly.
    The applet draws, and my timer works, but my KeyListener does not work.
    I believe all of my Java files are updated properly.
    But I do not understand why KeyListener does not work under Linux, but it does in Windows.
    I then made a very basic applet just to test my KeyListener, and it still does not work.
    This is how I was taught to do KeyListeners, but if I'm doing something wrong, please help me out!
    here is the basic program code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Test extends JApplet implements KeyListener
    int x = 0;
    int y = 250;
    public void init()
    addKeyListener(this);
    public void paint(Graphics g)
    g.setColor(Color.white);
    g.fillRect(0,0,500,500);
    g.setColor(Color.black);
    g.fillRect(x,y,50,50);
    public void keyPressed(KeyEvent event)
    int keyCode = event.getKeyCode();
    if(keyCode == KeyEvent.VK_RIGHT)
    x += 10;
    public void keyReleased(KeyEvent event)
    public void keyTyped(KeyEvent event)

    What if don't use a KeyListener but instead use key binding? For instance,
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    @SuppressWarnings("serial")
    public class Test2 extends JPanel {
      private static final int DELTA_X = 10;
      private static final int DELTA_Y = DELTA_X;
      private static final Dimension MAIN_SIZE = new Dimension(600, 600);
      enum Arrows {
        LEFT(KeyEvent.VK_LEFT, -DELTA_X, 0),
        RIGHT(KeyEvent.VK_RIGHT, DELTA_X, 0),
        UP(KeyEvent.VK_UP, 0, -DELTA_Y),
        DOWN(KeyEvent.VK_DOWN, 0, DELTA_Y);
        private int keyCode;
        private int deltaX, deltaY;
        private Arrows(int keyCode, int deltaX, int deltaY) {
          this.keyCode = keyCode;
          this.deltaX = deltaX;
          this.deltaY = deltaY;
        public int getDeltaX() {
          return deltaX;
        public int getDeltaY() {
          return deltaY;
        public int getKeyCode() {
          return keyCode;
      int x = 0;
      int y = 250;
      public Test2() {
        setBackground(Color.white);
        setPreferredSize(MAIN_SIZE);
        InputMap inMap = getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
        ActionMap actMap = getActionMap();
        for (Arrows arrow : Arrows.values()) {
          inMap.put(KeyStroke.getKeyStroke(arrow.getKeyCode(), 0), arrow);
          actMap.put(arrow, new MyAction(arrow));
      private class MyAction extends AbstractAction {
        private Arrows arrow;
        public MyAction(Arrows arrow) {
          this.arrow = arrow;
        public void actionPerformed(ActionEvent e) {
          x += arrow.getDeltaX();
          y += arrow.getDeltaY();
          repaint();
      @Override
      public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.setColor(Color.black);
        g.fillRect(x, y, 50, 50);
    import javax.swing.JApplet;
    @SuppressWarnings("serial")
    public class TestApplet extends JApplet {
      public void init() {
        try {
          javax.swing.SwingUtilities.invokeAndWait(new Runnable() {
            public void run() {
              createGUI();
        } catch (Exception e) {
          System.err.println("createGUI didn't successfully complete");
      private void createGUI() {
        getContentPane().add(new Test2());
    }

  • Code not working... again :P

    This is my 'paddle' game. You bounce a ball around the around the screen, and it's all working. I'm on the final part, which is what happens when you miss the ball (it goes off the left side of the screen). I'd like to print out a message to the middle of my screen saying "Press R to Reset", while the ball is not anywhere to be seen on the screen (is there a way I can get it to stop moving? my method right now is just to place it far away off screen, which just doesn't seem very professional to me). I made an if statement that should control this, but it's not working (when the you miss the ball, it disappears but nothing prints to the screen, and pressing R doesn't do anything either ) .
    To skip quickly to the if statement just use the find option in your browser and put in 'PROBLEM'
    This is all written in an applet.
    This is my code:
    int width, height, x, ypaddle, xball = 1, yball = 1, xctrl = 1, yctrl = 1, speed = 5, scorekeeper = 0, startkeeper = 0, keykeeper;
        Graphics g;
        String startagain;
        char move;
        Thread run;
        private Random random = new Random ();
        int ballstart = random.nextInt (400);
         *Initializes variables
        public void init ()
            resize (700, 500);
            setBackground (Color.white);
            addKeyListener (this);
            addMouseListener (this);
            addMouseMotionListener (this);
            run = new Thread (this);
            run.start ();
            startagain = "To Reset Press R";
            xball = ballstart;
            yball = ballstart;
        public void run ()
            while (true)
                try
                    run.sleep (50);
                    if (xctrl == 1 && startkeeper == 0)
                        xball = xball + speed;
                    if (yctrl == 1 && startkeeper == 0)
                        yball = yball + speed;
                    if (xctrl == 0 && startkeeper == 0)
                        xball = xball - speed;
                    if (yctrl == 0 && startkeeper == 0)
                        yball = yball - speed;
                    if (xball + 50 >= 660 && startkeeper == 0)
                        xball = xball - speed;
                        xctrl = 0;
                    if ((xball + 50) < 15 && yball <= ypaddle + 50 && yball >= ypaddle - 70 && startkeeper == 0)
                        xball = xball + speed;
                        xctrl = 1;
                    if (yball + 50 >= 460 && startkeeper == 0)
                        yball = yball - speed;
                        yctrl = 0;
                    if (yball + 50 <= 35 && startkeeper == 0)
                        yball = yball + speed;
                        yctrl = 1;
    //PROBLEM BELOW
                    if (xball + 50 <= 0 && startkeeper == 0)
                        if (xball + 50 <= 0)
                            yball = -100;
                            xball = -100;
                            repaint ();
                            g.drawString (startagain, 300, 300);
                        if (xball + 50 <= 0 && startkeeper == 1)
                            scorekeeper = scorekeeper + 1;
                            xball = ballstart;
                            yball = ballstart;
                            startkeeper = 0;
                    repaint ();
                catch (Exception e)
        public void keyPressed (KeyEvent e)
            keykeeper = e.getKeyChar ();
            if (keykeeper == 'r')
                startkeeper = 1;
                keykeeper = 'x';
        }

    For a public Usenet forum, most readers will stop reading by 20Kb, and start complaining at 30Kb.
    lol, I have a long way to go before i make programs that big :P
    By incompatible snippet, do you mean I should post the whole thing? Here it is:
    // The "Ping" class.
    import java.applet.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.Random;
    *Ping
    *@author Lenny
    public class Ping extends Applet
        implements KeyListener, MouseListener, MouseMotionListener, Runnable
        int width, height, x, ypaddle, xball = 1, yball = 1, xctrl = 1, yctrl = 1, speed = 5, scorekeeper = 0, startkeeper = 0, keykeeper;
        Graphics g;
        String startagain;
        char move;
        Thread run;
        private Random random = new Random ();
        int ballstart = random.nextInt (400);
         *Initializes variables
        public void init ()
            resize (700, 500);
            setBackground (Color.white);
            addKeyListener (this);
            addMouseListener (this);
            addMouseMotionListener (this);
            run = new Thread (this);
            run.start ();
            startagain = "To Reset Press R";
            xball = ballstart;
            yball = ballstart;
        public void run ()
            while (true)
                try
                    run.sleep (50);
                    if (xctrl == 1 && startkeeper == 0)
                        xball = xball + speed;
                    if (yctrl == 1 && startkeeper == 0)
                        yball = yball + speed;
                    if (xctrl == 0 && startkeeper == 0)
                        xball = xball - speed;
                    if (yctrl == 0 && startkeeper == 0)
                        yball = yball - speed;
                    if (xball + 50 >= 660 && startkeeper == 0)
                        xball = xball - speed;
                        xctrl = 0;
                    if ((xball + 50) < 15 && yball <= ypaddle + 50 && yball >= ypaddle - 70 && startkeeper == 0)
                        xball = xball + speed;
                        xctrl = 1;
                    if (yball + 50 >= 460 && startkeeper == 0)
                        yball = yball - speed;
                        yctrl = 0;
                    if (yball + 50 <= 35 && startkeeper == 0)
                        yball = yball + speed;
                        yctrl = 1;
    //PROBLEM HERE
                    if (xball + 50 <= 0 && startkeeper == 0)
                        if (xball + 50 <= 0)
                            yball = -100;
                            xball = -100;
                            repaint ();
                            g.drawString (startagain, 300, 300);
                        if (xball + 50 <= 0 && startkeeper == 1)
                            scorekeeper = scorekeeper + 1;
                            xball = ballstart;
                            yball = ballstart;
                            startkeeper = 0;
                    repaint ();
                catch (Exception e)
        public void keyPressed (KeyEvent e)
            keykeeper = e.getKeyChar ();
            if (keykeeper == 'r')
                startkeeper = 1;
                keykeeper = 'x';
        public void keyReleased (KeyEvent e)
        public void keyTyped (KeyEvent e)
        public void mouseEntered (MouseEvent e)
        public void mouseExited (MouseEvent e)
        public void mousePressed (MouseEvent e)
        public void mouseReleased (MouseEvent e)
        public void mouseClicked (MouseEvent e)
        public void mouseMoved (MouseEvent e)
            ypaddle = e.getY ();
            repaint ();
        public void mouseDragged (MouseEvent e)
        public void paint (Graphics g)
            paddle (g, ypaddle);
            walls (g);
            //enemies (g);
            ball (g);
         * Creates the paddle for hitting the ball
         *@param    y   value used to move the paddle vertically
        public void paddle (Graphics g, int y)
            g.fillRect (10, y - 25, 15, 70);
         *Creates the walls for the ball to bounce off of.
        public void walls (Graphics g)
            g.setColor (Color.yellow);
            g.fillRect (25, 10, 675, 25);
            g.setColor (Color.red);
            g.fillRect (675, 10, 25, 475);
            g.setColor (Color.cyan);
            g.fillRect (25, 475, 675, 25);
         *Creates the enemies to avoid.
        public void enemies (Graphics g)
            int place1 = random.nextInt (1000);
            int place1a = random.nextInt (1000);
            int place2 = random.nextInt (1000);
            int place2a = random.nextInt (1000);
            g.setColor (Color.black);
            g.fillOval (place1, place1a, 10, 10);
        public void ball (Graphics g)
            g.setColor (Color.black);
            g.fillRect (xball + 50, yball + 50, 20, 20);
            g.setColor (Color.white);
            g.fillRect (xball + 53, yball + 55, 5, 5);
            g.fillRect (xball + 63, yball + 55, 5, 5);
            g.fillRect (xball + 56, yball + 63, 9, 5);
    } // Ping classEdited by: soundweave on Jan 16, 2010 7:54 PM

  • Code not working, anyone know why?

    I'm making a simple pong game, and it's important to me that I use JAVA as efficient as possible (that is, use object orientated stuff, mostly). So, for drawing the ball and the players, I had thought up the following steps:
    - the applet has an array list that contains drawables*
    - if the ball and players need to be drawn, the applet uses a for-each loop, wich will call the draw(Graphics g) of all the drawables in the array list.
    * interface, guarantees that the method public void draw(Graphics g) is pressent.
    This is how I programmed it:
    http://willhostforfood.com/access.php?fileid=32821
    Only problem is, it doesn't work. The method paint() of the applet should result in "Hello World" being drawn on the screen (I know this seems like an eleborate method, but using seperate objects will help organise things once I have like, 20 - 30 balls on screen), but it doesn't.
    Does anyone know why it is not working?

    Here ya go, this is something I did quite a while ago, knock yourself out:
    package RandomColor;
    import java.awt.Canvas;
    import java.awt.Color;
    import java.awt.Cursor;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.image.BufferedImage;
    import java.awt.Image;
    import java.awt.image.MemoryImageSource;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.awt.event.MouseMotionListener;
    import java.awt.event.MouseWheelEvent;
    import java.awt.event.MouseWheelListener;
    import java.awt.Point;
    import java.awt.Toolkit;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import java.util.Random;
    public class RandomColor extends JFrame implements MouseListener, MouseMotionListener, MouseWheelListener{
      private BufferedImage myImage = null;
      private Canvas myCanvas = null;
      private Color bgColor = Color.BLACK;
      public RandomColor() throws java.lang.Exception {
        super();
        setUndecorated(true);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setBackground(bgColor);
        Dimension myDimension = Toolkit.getDefaultToolkit().getScreenSize();
        setSize(myDimension);
        setMinimumSize(myDimension);
        JPanel myJP = new JPanel();
        myJP.setBackground(bgColor);
        Dimension dImage = new Dimension(this.getAccessibleContext().getAccessibleComponent().getSize());
        myCanvas = new Canvas();
        myCanvas.addMouseListener(this);
        myCanvas.addMouseMotionListener(this);
        myCanvas.addMouseWheelListener(this);
        myCanvas.setSize(dImage.width, dImage.height);
        myJP.add(myCanvas);
        add(myJP);
    // start of code to hide the cursor   
        int[] pixels = new int[16 * 16];
        Image image = Toolkit.getDefaultToolkit().createImage(new MemoryImageSource(16, 16, pixels, 0, 16));
        Cursor transparentCursor = Toolkit.getDefaultToolkit().createCustomCursor(image, new Point(0, 0), "invisiblecursor");
        getContentPane().setCursor(transparentCursor);
    // end of code to hide cursor   
        pack();
        setVisible(true);
        Random myR = new Random();
        myImage = new BufferedImage((int) (dImage.getWidth()+0.99), (int) (dImage.getHeight()+0.99), BufferedImage.TYPE_INT_RGB);
        int i = myImage.getWidth();
        int j = myImage.getHeight();
        Ball[] myBall = {new Ball(), new Ball(), new Ball()};
        for (int k=0; k<myBall.length; k++){
          myBall[k].setBackGroundColor(Color.BLACK);
          myBall[k].setBounds(0, i, 0, j);
          myBall[k].setRandomColor(true);
          myBall[k].setLocation(myR.nextInt(i), myR.nextInt(j));
          myBall[k].setMoveRate(32, 32, 1, 1, true);
          myBall[k].setSize( 289, 167);
        Graphics g = myImage.getGraphics();
        while(true) {
          for (int k=0; k<myBall.length; k++){
            g.setColor(myBall[k].fgColor);
            g.fillOval(myBall[k].x, myBall[k].y, myBall[k].width, myBall[k].height);
          invalidate();
          paint(getGraphics());
          for (int k=0; k<myBall.length; k++){
            g.setColor(myBall[k].bgColor);
            g.fillOval(myBall[k].x, myBall[k].y, myBall[k].width, myBall[k].height);
            myBall[k].move();
      public void mouseClicked(MouseEvent e){
        exit();
      public void mouseDragged(MouseEvent e){
    //    exit();
      public void mouseEntered(MouseEvent e){
    //    exit();
      public void mouseExited(MouseEvent e){
    //    exit();
      public void mouseMoved(MouseEvent e){
    //    exit();
      public void mousePressed(MouseEvent e){
        exit();
      public void mouseReleased(MouseEvent e){
        exit();
      public void mouseWheelMoved(MouseWheelEvent e){
        exit();
      private void exit(){
        System.exit(0);
      public void paint(Graphics g){
        super.paint(g);
        myCanvas.getGraphics().drawImage(myImage, 0, 0, null);
      public static void main(String[] args) throws java.lang.Exception {
        new RandomColor();
        System.out.println("Done -- RandomColor");
    }Ball Class:
    package RandomColor;
    import java.awt.Color;
    import java.util.Random;
    public class Ball {
      private int iLeft      = 0;
      private int iRight     = 0;
      private int iTop       = 0;
      private int iBottom    = 0;
      private int moveX      = 1;
      private int moveY      = 1;
      private int xScale     = moveX;
      private int yScale     = moveY;
      private int xDirection = 1;
      private int yDirection = 1;
      private boolean moveRandom = false;
      private boolean colorRandom = false;
      private Random myRand = null;
      public Color fgColor = Color.BLACK;
      public Color bgColor = Color.BLACK;
      public int x = 0;
      public int y = 0; 
      public int width  = 1;
      public int height = 1;
      public Ball(){
        myRand = new Random();
        setRandomColor(colorRandom);
      public void move(){
        x = 5 + x + (xScale*xDirection);
        y = 5 + y + (yScale*yDirection);
        if(x<=iLeft){
          x = 0;
          if(moveRandom) xScale = myRand.nextInt(moveX);else xScale = moveX;
          xDirection *= (-1);
          if(colorRandom) setRandomColor(colorRandom);
        if(x>=iRight-width){
          x = iRight-width;
          if(moveRandom) xScale = myRand.nextInt(moveX);else xScale = moveX;
          xDirection *= (-1);
          if(colorRandom) setRandomColor(colorRandom);
        if(y<=iTop){
          y = 0;
          if(moveRandom) yScale = myRand.nextInt(moveY);else xScale = moveY;
          yDirection *= (-1);
          if(colorRandom) setRandomColor(colorRandom);
        if(y>=iBottom-height){
          y = iBottom-height;
          if(moveRandom) yScale = myRand.nextInt(moveY);else xScale = moveY;
          yDirection *= (-1);
          if(colorRandom) setRandomColor(colorRandom);
      public void setColor(Color c){
        fgColor = c;
      public void setBackGroundColor(Color c){
        bgColor = c;
      public void setBounds(int Left, int Right, int Top, int Bottom){
        iLeft   = Left;
        iRight  = Right;
        iTop    = Top;
        iBottom = Bottom;
      public void setLocation(int x, int y){
        this.x = x;
        this.y = y;
      public void setMoveRate(int xMove, int yMove, int xDir, int yDir, boolean randMove){
        moveX       = xMove;
        moveY       = yMove;
        moveRandom  = randMove;
        xDirection  = xDir;
        yDirection  = yDir;
      public void setRandomColor(boolean random){
        colorRandom = random;
        switch (myRand.nextInt(3)+1){
          case 1:  fgColor = Color.BLUE;
                   break;
          case 2:  fgColor = Color.GREEN;
                   break;
          case 3:  fgColor = Color.RED;
                   break;
          default: fgColor = Color.BLACK;
                   break;
      public void setSize(int width, int height){
        this.width  = width;
        this.height = height;
    }

  • Repaint() method is not working in MAC IE

    Hi All
    why repaint method is not working in MAC IE ? What i am doing is in one class which is inheriting Canvas class getting the keybord input then adding it to main applet.
    Please help me i am trying it for whole week and i couldn't find any solution. I didn't put my code but if anyone is willing to help me i can post it.
    Thanks in advancs
    Shan

    Hi
    Thanks for your reply. Actually i wrote simple applets and those are working well.
    So i did debug the code and i found that when i am running the following code in Apple MAC IE, nothing is happening in handleEvent method. Especially it is not going into the if statement (if (evt.id==401)). here i am checking for KEY_PRESS. I also tried with keyDown method but same problem in MAC IE.
    I am pasting the code that is giving me problem.
    import java.awt.*;
    import java.applet.*;
    public class testApplet extends Applet
    public void init()
    setLayout(new BorderLayout());
    editableArea = new EditableArea();
    editableArea.setBackground(Color.yellow);
    add("Center", editableArea);
    EditableArea editableArea;
    import java.awt.*;
    public class EditableArea extends Canvas
    String s = "";
    public boolean handleEvent(Event evt)
    if (evt.id==401)
    if(evt.key >= 32 && evt.key <= 255)
    char c = (char)evt.key;
    s = s + c;
    repaint();
    return super.handleEvent(evt);
    public void paint( Graphics g )
    g.setColor(Color.blue);
    g.drawString( s,5,15);
    --------------------------------------------------------------------

  • Draw method is not working

    Why the drawLine() is working only inside the paint method??
    BufferedImage image = new BufferedImage(800,500,BufferedImage.TYPE_INT_ARGB);
         Graphics2D g = (Graphics2D)image.getGraphics();
    public void paint(Graphics g)
                   g.setColor(Color.black);
                             //Here, the drawLine() method works
                   g.drawLine(50,0,50,150);
    public void paintX(Graphics g,Point c)
                        //Here, the drawLine() method does not work
                        g.setColor(Color.black);
                   g.drawLine(0-e,0-e,50-e,50-e);
                   g.drawLine(0-e,50-e,50-e,0-e);
                   repaint();
         }

    er, unless you're using JDK 1.5 and it introduces methods I know nothing about, as far as I know
    public void paintX(..) is not a AWT or Swing method. Thus it will never be invoked unless you call it.

  • Why handleEvent is not working in AppleMac IE ?!

    Hi There
    I am trying to write an editor which should work in Apple MAC and Windows !!.I wrote the following classes and working fine in Windows IE/Netscape and MAC Netscape, But not working in MAC IE. Someone please point out me where i am making mistake. I used JDK1.0.2 version to combile the classes.
    import java.awt.*;
    import java.applet.*;
    public class testApplet extends Applet
    public void init()
    setLayout(new BorderLayout());
    editableArea = new EditableArea();
    editableArea.setBackground(Color.yellow);
    add("Center", editableArea);
    EditableArea editableArea;
    import java.awt.*;
    public class EditableArea extends Canvas
    String s = "";
    public boolean handleEvent(Event evt)
    if (evt.id==401)
    if(evt.key >= 32 && evt.key <= 255)
    char c = (char)evt.key;
    s = s + c;
    repaint();
    return super.handleEvent(evt);
    public void paint( Graphics g )
    g.setColor(Color.blue);
    g.drawString( s,5,15);
    --------------------------------------------------------------------

    Someone please give me some idea, i am struggling for long time. As our customers are printers they need the MAC IE. Any help will be appreciated.

  • When my thread starts running, at that time keylistener is not working.

    when my thread starts running, at that time keylistener is not working.
    plz reply me.

    //FrameShow.java
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.event.*;
    import java.awt.Dimension;
    import java.awt.geom.Dimension2D;
    import java.awt.*;
    import java.awt.image.*;
    import java.awt.event.*;
    import java.util.logging.Level;
    import java.awt.event.*;
    import java.util.*;
    public class FrameShow extends JFrame implements ActionListener,KeyListener
         boolean paused=false;
         JButton stop;
         JButton start;
         JButton exit;
         public IncludePanel CenterPanel;
         public FrameShow()
    CenterPanel= new IncludePanel();
              Functions fn=new Functions();
              int height=fn.getScreenHeight();
              int width=fn.getScreenWidth();
              setTitle("Game Assignment--Santanu Tripathy--MCA");
              setSize(width,height);
              setResizable(false);
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              show();
              initComponents();
              DefaultColorSet();
              this.addKeyListener(this);
         this.setFocusable(true);
         public void initComponents()
              Container contentpane=getContentPane();
              //Creating Panel For Different Side
              JPanel EastPanel= new JPanel();
              JPanel WestPanel= new JPanel();
              JPanel NorthPanel= new JPanel();
              JPanel SouthPanel= new JPanel();
              //CenterPanel = new IncludePanel();
              //IncludePanel CenterPanel= new IncludePanel();
              EastPanel.setPreferredSize(new Dimension(100,10));
              WestPanel.setPreferredSize(new Dimension(100,10));
              NorthPanel.setPreferredSize(new Dimension(10,100));
              SouthPanel.setPreferredSize(new Dimension(10,100));
              //CenterPanel.setPreferredSize(new Dimension(200,200));
              //Adding Color to the Panels
              NorthPanel.setBackground(Color.green);
              SouthPanel.setBackground(Color.orange);
              CenterPanel.setBackground(Color.black);
              //Creating Border For Different Side
              Border EastBr = javax.swing.BorderFactory.createEtchedBorder(Color.cyan, Color.red);
              Border WestBr = javax.swing.BorderFactory.createEtchedBorder(Color.cyan, Color.red);
              Border NorthBr = javax.swing.BorderFactory.createEtchedBorder(Color.cyan, Color.red);
              Border SouthBr = javax.swing.BorderFactory.createEtchedBorder(Color.cyan, Color.red);
              Border CenterBr = javax.swing.BorderFactory.createEtchedBorder(Color.cyan, Color.red);
              //Creating Components For East Panel
              JLabel left= new JLabel("LEFT");
              JLabel right= new JLabel("RIGHT");
              JLabel rotate= new JLabel("ROTATE");
              left.setForeground(Color.blue);
              right.setForeground(Color.blue);
              rotate.setForeground(Color.blue);
              //Creating Components For West Panel
              ButtonGroup group = new ButtonGroup();
              JRadioButton rb1 = new JRadioButton("Pink",false);
              JRadioButton rb2 = new JRadioButton("Cyan",false);
              JRadioButton rb3 = new JRadioButton("Orange",false);
              JRadioButton _default = new JRadioButton("Black",true);
              rb1.setForeground(Color.pink);
              rb2.setForeground(Color.cyan);
              rb3.setForeground(Color.orange);
              _default.setForeground(Color.black);
              //Creating Components For North Panel
              JLabel name= new JLabel("Santanu Tripathy");
              name.setForeground(Color.blue);
              name.setFont(new Font("Serif",Font.BOLD,30));
              //Creating Components For South Panel
              start = new JButton();
              stop = new JButton();
              exit = new JButton();
              start.setToolTipText("Click this button to start the game");
              start.setFont(new java.awt.Font("Trebuchet MS", 0, 12));
              start.setText("START");
              start.setBorder(javax.swing.BorderFactory.createCompoundBorder(javax.swing.BorderFactory.createEmptyBorder(3, 5, 3, 5), javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED)));
              start.setMaximumSize(new java.awt.Dimension(90, 35));
              start.setMinimumSize(new java.awt.Dimension(90, 35));
              start.setPreferredSize(new java.awt.Dimension(95, 35));
              if(paused)
                   stop.setToolTipText("Click this button to pause the game");
              else
                   stop.setToolTipText("Click this button to resume the game");
              stop.setFont(new java.awt.Font("Trebuchet MS", 0, 12));
              stop.setText("PAUSE");
              stop.setBorder(javax.swing.BorderFactory.createCompoundBorder(javax.swing.BorderFactory.createEmptyBorder(3, 5, 3, 5), javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED)));
              stop.setMaximumSize(new java.awt.Dimension(90, 35));
              stop.setMinimumSize(new java.awt.Dimension(90, 35));
              stop.setPreferredSize(new java.awt.Dimension(95, 35));
              exit.setToolTipText("Click this button to exit from the game");
              exit.setFont(new java.awt.Font("Trebuchet MS", 0, 12));
              exit.setText("EXIT");
              exit.setBorder(javax.swing.BorderFactory.createCompoundBorder(javax.swing.BorderFactory.createEmptyBorder(3, 5, 3, 5), javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED)));
              exit.setMaximumSize(new java.awt.Dimension(90, 35));
              exit.setMinimumSize(new java.awt.Dimension(90, 35));
              exit.setPreferredSize(new java.awt.Dimension(95, 35));
              //Adding some extra things to the Panels
              group.add(rb1);
              group.add(rb2);
              group.add(rb3);
              group.add(_default);
              //Adding Component into the Panels
              EastPanel.add(left);
              EastPanel.add(right);
              EastPanel.add(rotate);
              WestPanel.add(rb1);
              WestPanel.add(rb2);
              WestPanel.add(rb3);
              WestPanel.add(_default);
              NorthPanel.add(name);
              SouthPanel.add(start);
              SouthPanel.add(stop);
              SouthPanel.add(exit);
              //Adding Border Into the Panels
              EastPanel.setBorder(EastBr);
              WestPanel.setBorder(WestBr);
              NorthPanel.setBorder(NorthBr);
              SouthPanel.setBorder(SouthBr);
              CenterPanel.setBorder(CenterBr);
              //Adding Panels into the Container
              EastPanel.setLayout(new GridLayout(0,1));
              contentpane.add(EastPanel,BorderLayout.EAST);
              WestPanel.setLayout(new GridLayout(0,1));
              contentpane.add(WestPanel,BorderLayout.WEST);
              contentpane.add(NorthPanel,BorderLayout.NORTH);
              contentpane.add(SouthPanel,BorderLayout.SOUTH);
              contentpane.add(CenterPanel,BorderLayout.CENTER);
              //Adding Action Listeners
              rb1.addActionListener(this);
              rb2.addActionListener(this);
              rb3.addActionListener(this);
              _default.addActionListener(this);
              exit.addActionListener(this);
              start.addActionListener(this);
    try
              start.addActionListener(
    new ActionListener() {
    public void actionPerformed( ActionEvent e )
                        start.setEnabled(false);
    CenterPanel.drawCircle();
    catch(Exception e)
    {System.out.println("Exception is attached with sart button exp = "+e);}
    try
              stop.addActionListener(
    new ActionListener() {
    public void actionPerformed( ActionEvent e )
                        paused=!paused;
                        if(paused)
                             start.setToolTipText("Click this button to resume the game");
                             stop.setText("RESUME");
                        else
                             start.setToolTipText("Click this button to pause the game");
                             stop.setText("PAUSE");
    CenterPanel.pause();
    catch(Exception e)
    {System.out.println("Exception is attached with sart button exp = "+e);}
         public void DefaultColorSet()
              getContentPane().setBackground(Color.white);
         public void actionPerformed(ActionEvent AE)
              String str=(String)AE.getActionCommand();
              if(str.equalsIgnoreCase("pink"))
                   CenterPanel.setBackground(Color.pink);
              if(str.equalsIgnoreCase("cyan"))
                   CenterPanel.setBackground(Color.cyan);
              if(str.equalsIgnoreCase("orange"))
                   CenterPanel.setBackground(Color.orange);
              if(str.equalsIgnoreCase("black"))
                   CenterPanel.setBackground(Color.black);
              if(str.equalsIgnoreCase("exit"))
                   System.exit(0);
         public void keyTyped(KeyEvent kevt)
    //repaint();
    public void keyPressed(KeyEvent e)
              System.out.println("here key pressed");
              //CenterPanel.dec();
         public void keyReleased(KeyEvent ke) {}
    }//End of FrameShow.ja
    //IncludePanel.java
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import java.awt.Graphics.*;
    import java.awt.Dimension;
    import java.awt.geom.Dimension2D;
    import java.util.*;
    import java.util.logging.Level;
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.event.*;
    public class IncludePanel extends JPanel implements Runnable
    int x=0,y=0;
    int color_1=0;
    int color_2=1;
    int start=0;
    Thread th;
    Image red,blue,green,yellow;
    java.util.List image;
    static boolean PAUSE=false;
         public IncludePanel()
         red= Toolkit.getDefaultToolkit().getImage("red.png");
         blue= Toolkit.getDefaultToolkit().getImage("blue.png");
         green= Toolkit.getDefaultToolkit().getImage("green.png");
         yellow= Toolkit.getDefaultToolkit().getImage("yellow.png");
    public void paintComponent(Graphics g)
              super.paintComponent(g);
              draw(g);
    public void dec()
         System.out.println("in dec method");
         x=x+30;
    public void draw(Graphics g)
              g.setColor(Color.red);
              int xx=0,yy=0;
              for (int row=0;row<=12;row++)
                   g.drawLine(xx,yy,180,yy);
                   yy=yy+30;
              xx=0;
              yy=0;
              for (int col=0;col<=6;col++)
                   g.drawLine(xx,yy,xx,360);
                   xx=xx+30;
              if(color_1==0)
                   g.drawImage(red, x, y, this);
              else if(color_1==1)
                   g.drawImage(blue,x, y, this);
              else if(color_1==2)
                   g.drawImage(green,x,y, this);
              else if(color_1==3)
                   g.drawImage(yellow,x,y, this);
    x=x+30;
              if(color_2==0)
                   g.drawImage(red, x, y, this);
              else if(color_2==1)
                   g.drawImage(blue,x,y, this);
              else if(color_2==2)
                   g.drawImage(green,x,y, this);
              else if(color_2==3)
                   g.drawImage(yellow,x,y, this);
    x=0;
    public void drawCircle( )
         th=new Thread(this);
         th.start();
         public void pause()
              if(PAUSE)
                   th.resume();
                   PAUSE=false;
                   return;
              if(!PAUSE)
              PAUSE=true;
         public synchronized void run()
              Random rand = new Random();
              Thread ani=Thread.currentThread();
              while(ani==th)
                   if(PAUSE)
                        th.suspend();
                   if(y==330)
                        color_1 = Math.abs(rand.nextInt())%4;
                        color_2 = Math.abs(rand.nextInt())%4;
                        if(color_1==color_2)
                             color_2=(color_2+1)%4;
                        y=0;
                   else
                        y=y+30;
                   repaint();
                   try
                        Thread.sleep(700);
                   catch(Exception e)
         }//End of run
    i sent two entire program

  • Code to change JTable cell color not working

    My code below is supposed to change the color
    of a single JTable cell however its not working.
    Could anyone please tell me why?
    Here's the code:
    import java.awt.*;
    import javax.swing.table.*;
    import javax.swing.*;
    import java.awt.event.*;
    public class ColorTable extends JTable {
    public ColorTable() {
    AbstractTableModel tableModel = new AbstractTableModel() {
    public Class getColumnClass(int column) { return Integer.class; }
    public int getColumnCount() { return 6; }
    public int getRowCount() { return 10;}
    public Object getValueAt(int row,int col) { return new Integer(row * col); }
    setModel(tableModel);
    setDefaultRenderer(Integer.class,new ColorRenderer(Color.cyan));
    this.setRowSelectionAllowed(false);
    this.setCellSelectionEnabled(true);
    addMouseListener(new MouseAdapter() {
    private ColorRenderer renderer;
    private JColorChooser chooser = new JColorChooser();
    public void mousePressed(MouseEvent e) {
    if(e.getModifiers() == MouseEvent.BUTTON3_MASK) {
    System.out.print("rowAtPoint(e.getPoint())=" +rowAtPoint(e.getPoint()));
    System.out.print( "columnAtPoint(e.getPoint()))=" + columnAtPoint(e.getPoint()));
    renderer = (ColorRenderer)getCellRenderer(rowAtPoint(e.getPoint()), columnAtPoint(e.getPoint()));
    // chooser.setColor(renderer.getColor());
    renderer.setColor(chooser.showDialog((Component)e.getSource(),"Choose Cell Color",chooser.getColor()));
    class ColorRenderer extends DefaultTableCellRenderer {
    private Color cellColor;
    public ColorRenderer(Color color) { cellColor = color; }
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
    System.out.print("row= " + row + "\n");
    System.out.print("column= " + column + "\n");
    System.out.print("OBJECT VALUE=" + value.toString());
    //Component comp = super.getTableCellRendererComponent(table,value,isSelected,hasFocus,row,column);
    super.getTableCellRendererComponent(table,value,isSelected,hasFocus,row,column);
    if (isSelected) {
    setOpaque(true);
    setBackground(cellColor);
    else {
    setBackground(Color.white);
    setForeground(Color.black);
    return this;
    public void setColor(Color color)
    cellColor = color;
    ColorTable.this.repaint();
    public Color getColor() { return cellColor; }
    public static void main(String[] args) {
    JFrame frame = new JFrame();
    JPanel panel = new JPanel();
    ColorTable table = new ColorTable();
    panel.add(table);
    frame.getContentPane().add(panel);
    frame.setSize(500,250);
    frame.setVisible(true);

    My code below is supposed to change the color
    of a single JTable cell however its not working.
    Could anyone please tell me why?
    Here's the code:
    import java.awt.*;
    import javax.swing.table.*;
    import javax.swing.*;
    import java.awt.event.*;
    public class ColorTable extends JTable {
    public ColorTable() {
    AbstractTableModel tableModel = new AbstractTableModel() {
    public Class getColumnClass(int column) { return Integer.class; }
    public int getColumnCount() { return 6; }
    public int getRowCount() { return 10;}
    public Object getValueAt(int row,int col) { return new Integer(row * col); }
    setModel(tableModel);
    setDefaultRenderer(Integer.class,new ColorRenderer(Color.cyan));
    this.setRowSelectionAllowed(false);
    this.setCellSelectionEnabled(true);
    addMouseListener(new MouseAdapter() {
    private ColorRenderer renderer;
    private JColorChooser chooser = new JColorChooser();
    public void mousePressed(MouseEvent e) {
    if(e.getModifiers() == MouseEvent.BUTTON3_MASK) {
    System.out.print("rowAtPoint(e.getPoint())=" +rowAtPoint(e.getPoint()));
    System.out.print( "columnAtPoint(e.getPoint()))=" + columnAtPoint(e.getPoint()));
    renderer = (ColorRenderer)getCellRenderer(rowAtPoint(e.getPoint()), columnAtPoint(e.getPoint()));
    // chooser.setColor(renderer.getColor());
    renderer.setColor(chooser.showDialog((Component)e.getSource(),"Choose Cell Color",chooser.getColor()));
    class ColorRenderer extends DefaultTableCellRenderer {
    private Color cellColor;
    public ColorRenderer(Color color) { cellColor = color; }
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
    System.out.print("row= " + row + "\n");
    System.out.print("column= " + column + "\n");
    System.out.print("OBJECT VALUE=" + value.toString());
    //Component comp = super.getTableCellRendererComponent(table,value,isSelected,hasFocus,row,column);
    super.getTableCellRendererComponent(table,value,isSelected,hasFocus,row,column);
    if (isSelected) {
    setOpaque(true);
    setBackground(cellColor);
    else {
    setBackground(Color.white);
    setForeground(Color.black);
    return this;
    public void setColor(Color color)
    cellColor = color;
    ColorTable.this.repaint();
    public Color getColor() { return cellColor; }
    public static void main(String[] args) {
    JFrame frame = new JFrame();
    JPanel panel = new JPanel();
    ColorTable table = new ColorTable();
    panel.add(table);
    frame.getContentPane().add(panel);
    frame.setSize(500,250);
    frame.setVisible(true);

  • Not work tablet UI on Prestigio 5080 PRO tablet

    I read that browser.ui.layout.tablet = "1" can fix this problem. But it not works. I can work only in pnone interface that is not good for my 8'' tablet.

    Would it be possible for you to share the problematic pdf and OS information  with us at [email protected] so that we may investigate?
    Thanks,
    Adobe Reader Team

Maybe you are looking for

  • IMAP and Duplicate messages in Sent

    I have set up Mail to work with AOL mail using IMAP. I would like to have me Sent emails synced, just like the rest of my folders. Unfortunately when I do that and I send an email from Mail it always gets included twice in the Sent folder. What do I

  • Multiple Email Address per contact

    I have more than one email address for many of my contacts. I do I compose an email to all of the contact's emails?

  • Links from Excel to Project

    So I am trying to link an existing excel worksheet to MS Project.  The desired functionality would be for users to keep updating information in excel, which would update MSP. Problems are, -I cant seem to get the mapping wizard to select the cells I

  • Spry Tabbed Panel Question

    Anybody know how to hide/display a panel. I want to be able to hide certain panels/tabs with dynamic data.

  • How do i find out what my skpe number is

    I don't remember my skpe number How can i find out what it is.