Results 1 to 8 of 8
  1. #1
    rmabrey is offline Member
    Join Date
    Sep 2008
    Posts
    3
    Rep Power
    0

    Default Jbutton not working??

    Hi my question is pretty simple. I cannot figure out why my JButton is not working and I will be honest this is the first time I have ever used one in a program. I would like to know either what is wrong or the area where I need to narrow my focus. Any help is greatly appreciated.
    import java.awt.Color;
    import java.awt.Event;
    import java.awt.Graphics;
    import java.awt.Rectangle;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.awt.event.MouseMotionListener;
    import javax.swing.JApplet;
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.util.Random;

    public class Doodle extends JApplet
    implements MouseListener, MouseMotionListener, ActionListener {

    private int myLastX; // previous mouse location
    private int myLastY;

    private Color myCurrentColor; // current drawing color

    private Rectangle myRedPalette; // palette
    private Rectangle myYellowPalette;
    private Rectangle myBluePalette;
    private Rectangle myGreenPalette; // palette
    private Rectangle myMagentaPalette;
    private Rectangle myBrownPalette;
    private Rectangle myOrangePalette;
    private Rectangle myCyanPalette;
    private Rectangle myRandomPalette;
    JButton clearButton;

    Random rand = new java.util.Random();



    //---------- init ---------------------------------------------
    // Initialize the mouse pointer and create the palette.

    public void init ()
    {
    setBackground(Color.white);
    Container pane = getContentPane();

    setSize(400,300);

    clearButton = new JButton("Clear");
    pane.setLocation(0,0);
    clearButton.setBounds(0,0,100,20);
    pane.add(clearButton);
    clearButton.setLocation(300,0);
    setVisible(true);
    clearButton.addActionListener(this);

    pane.setLayout(new GridLayout(200,200));
    pane.setLayout(null);


    // set last mouse position
    myLastX = 0;
    myLastY = 0;

    // initialize drawing color
    myCurrentColor = Color.black;

    // create palette
    myRedPalette = new Rectangle (0,0, 25, 30);
    myYellowPalette = new Rectangle ( 25,0, 25, 30);
    myBluePalette = new Rectangle (50,0,25,30);
    myGreenPalette = new Rectangle ( 75, 0, 25, 30);
    myMagentaPalette = new Rectangle ( 100, 0, 25, 30);
    myBrownPalette = new Rectangle (125,0,25,30);
    myOrangePalette = new Rectangle ( 150, 0, 25, 30);
    myCyanPalette = new Rectangle (175, 0, 25,30);
    myRandomPalette = new Rectangle (200,0, 25, 30);
    addMouseListener(this);
    addMouseMotionListener(this);
    }

    //---------- paint --------------------------------------------
    // Draw the palette
    //
    // Note: when the drawing window is resized or covered, the
    // image may be lost because paint cannot redraw it.

    int red=(int)(Math.random()*255);
    int green=(int)(Math.random()*255);
    int blue=(int)(Math.random()*255);


    public void paint (Graphics g) {
    g.setColor(Color.red);
    g.fillRect(myRedPalette.x, myRedPalette.y,
    myRedPalette.width, myRedPalette.height);
    g.setColor(Color.yellow);
    g.fillRect(myYellowPalette.x, myYellowPalette.y,
    myYellowPalette.width, myYellowPalette.height);
    g.setColor(Color.blue);
    g.fillRect(myBluePalette.x, myBluePalette.y,
    myBluePalette.width, myBluePalette.height);
    g.setColor(Color.green);
    g.fillRect(myGreenPalette.x, myGreenPalette.y,
    myGreenPalette.width, myGreenPalette.height);
    g.setColor(Color.magenta);
    g.fillRect(myMagentaPalette.x, myMagentaPalette.y,
    myMagentaPalette.width, myMagentaPalette.height);
    g.setColor(Color.lightGray);
    g.fillRect(myBrownPalette.x, myBrownPalette.y,
    myBrownPalette.width, myBrownPalette.height);
    g.setColor(Color.orange);
    g.fillRect(myOrangePalette.x, myOrangePalette.y,
    myOrangePalette.width, myOrangePalette.height);
    g.setColor(Color.cyan);
    g.fillRect(myCyanPalette.x, myCyanPalette.y,
    myCyanPalette.width, myCyanPalette.height);
    g.setColor(Color.black);
    g.fillRect(myRandomPalette.x,myRandomPalette.y,
    myRandomPalette.width,myRandomPalette.height);

    }

    //---------- mousePressed ---------------------------------------
    // Reset the mouse location and select a color from the
    // palette.

    public void mousePressed(MouseEvent e)
    {
    int x = e.getX();
    int y = e.getY();

    // reset last mouse position
    myLastX = x;
    myLastY = y;


    // select a color
    if (myRedPalette.contains(x,y))
    myCurrentColor = Color.red;
    if (myYellowPalette.contains(x,y))
    myCurrentColor = Color.yellow;
    if (myBluePalette.contains(x,y))
    myCurrentColor = Color.blue;
    if (myGreenPalette.contains(x,y))
    myCurrentColor = Color.green;
    if (myMagentaPalette.contains(x,y))
    myCurrentColor = Color.magenta;
    if (myBrownPalette.contains(x,y))
    myCurrentColor = Color.lightGray;
    if (myOrangePalette.contains(x,y))
    myCurrentColor = Color.orange;
    if (myCyanPalette.contains(x,y))
    myCurrentColor = Color.cyan;
    if (myRandomPalette.contains(x,y))
    myCurrentColor = new Color(rand.nextInt(255), rand.nextInt(255), rand.nextInt(255));

    }

    //---------- mouseDragged --------------------------------------
    // Draw the doodle.

    public void mouseDragged(MouseEvent e)
    {
    int x = e.getX();
    int y = e.getY();
    if (y >35&&y<280){
    Graphics g = getGraphics();
    g.setColor(myCurrentColor);
    g.drawLine (myLastX, myLastY, x, y);
    g.drawLine(400-myLastX,320-myLastY,400-x,320-y);
    g.drawLine(myLastX,320-myLastY,x,320-y);
    g.drawLine(400-myLastX, myLastY,400-x,y);
    myLastX = x;
    myLastY = y;
    }
    }
    //Unused methods
    public void mouseMoved(MouseEvent e) {}
    public void mouseExited(MouseEvent e) {}
    public void mouseReleased(MouseEvent e) {}
    public void mouseEntered(MouseEvent e) {}

    //Draw a 10x10 pixel square if mouse is double clicked
    public void mouseClicked(MouseEvent e)
    {
    if(e.getClickCount()==2)
    {
    int x = e.getX();
    int y = e.getY();

    Graphics g = getGraphics();
    g.setColor(myCurrentColor);
    g.drawRect (x, y, 10, 10);
    }
    }
    public void actionPerformed(ActionEvent e)
    {
    if(e.getSource()==clearButton)
    {
    setBackground(Color.white);

    }


    }
    }

  2. #2
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    16,576
    Rep Power
    23

    Default

    JButton is not working
    There are a lot of ways to not work. Which one are you seeing?
    Compiler errors, execution errors, invalid output, no response, ends suddenly, ....

    Add a println() method call to show what is happening and what the values of variables are.

  3. #3
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default

    Your problem isn't with your JButton, it's with the way you're trying to do graphics. A few recommendations for ya:

    1) Don't draw in the JApplet, but rather draw in another JComponent that is held by the JApplet. Often a JPanel or JComponent work nicely here.

    2) Override the paintComponent method of the component that you are drawing in, and do your drawing here.

    3) Don't get the graphics object in the mouselistener code, don't call getGraphics. Instead, in the mouselistener code, update an ArrayList that contains drawing information, then call repaint and have your paintComponent method iterate through the list and do the actual drawing.

    4) Use the graphics object that is passed as a parameter to the paintComponent object and draw with it. Do not try to save the Graphics object as it may change later in your program.

    5) Call super.paintComponent(g) as the first method of your paintComponent method (assuming that the Graphics object parameter is named "g").

    6) Have your clear button clear the ArrayList that is used for drawing. Then call repaint on the drawing JPanel, and most importantly...

    7) Read on how to do 2-D graphics in Swing in the Sun tutorials.

    Good luck!

  4. #4
    rmabrey is offline Member
    Join Date
    Sep 2008
    Posts
    3
    Rep Power
    0

    Default

    Sorry i forget to calrify sometimes. By not work I mean it shows up but when i click it, it does not clear the window. As for the suggestions, I appreciate them but i was given partial code. i,e, MouseListener, two colors etc. All i had to do was add more colors, the clear buttn, kaliedescope effect, and a random color.

  5. #5
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default

    Well, whoever gave you this code isn't doing you any favors. It will clear itself if you simply minimize the applet and then restore it to view.

    Nevertheless, live by the sword, die by the sword. To clear your little prog, you have to grab your Graphics object again and then paint a rectangle over the applet.

  6. #6
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default

    I couldn't help myself. I doubt that you can use this for your current program, as it doesn't fit your assigned limitations (use code given as basis, etc...) which is why I'm posting this, but feel free to ask questions about this or critiques:

    PaintPanelLine.java -- holds data placed in ArrayList within PaintPanel and used to draw
    Java Code:
    import java.awt.Color;
    import java.awt.Point;
    
    public class PaintPanelLine
    {
      private Color color;
      private Point p0, p1;
    
      public PaintPanelLine(Color color, Point p0, Point p1)
      {
        this.color = color;
        this.p0 = p0;
        this.p1 = p1;
      }
    
      public Color getColor()
      {
        return color;
      }
    
      public Point getP0()
      {
        return p0;
      }
      
      public Point getP1()
      {
        return p1;
      }
      
    }
    PaintPanel.java -- holds a JPanel that is painted in.
    Java Code:
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.RenderingHints;
    import java.awt.event.MouseListener;
    import java.awt.event.MouseMotionListener;
    import java.util.ArrayList;
    import java.util.List;
    
    import javax.swing.JComponent;
    import javax.swing.JPanel;
    
    public class PaintPanel
    {
      private JPanel mainPanel = new JPanel()
      {
        protected void paintComponent(Graphics g)
        {
          super.paintComponent(g);
          myPaint(g);
        }
      };
      private List<PaintPanelLine> lines = new ArrayList<PaintPanelLine>();
    
      public PaintPanel()
      {
        
      }
      
      public void setPreferredSize(Dimension preferredSize)
      {
        mainPanel.setPreferredSize(preferredSize);
      }
    
      public void addLine(PaintPanelLine line)
      {
        lines.add(line);
        mainPanel.repaint();
      }
      
      public void clear()
      {
        lines.clear();
        mainPanel.repaint();
      }
      
      private void myPaint(Graphics g)
      {
        int width = mainPanel.getSize().width;
        int height = mainPanel.getSize().height;
        Graphics2D g2d = (Graphics2D)g;
        RenderingHints rh = new RenderingHints(
            RenderingHints.KEY_ANTIALIASING, 
            RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.setRenderingHints(rh);
        for (PaintPanelLine line : lines)
        {
          g.setColor(line.getColor());
          int x0 = line.getP0().x;
          int y0 = line.getP0().y;
          int x1 = line.getP1().x;
          int y1 = line.getP1().y;
          g.drawLine(x0, y0, x1, y1);
          g.drawLine(width - x0, y0, width - x1, y1);
          g.drawLine(x0, height - y0, x1, height - y1);
          g.drawLine(width - x0, height - y0, width - x1, height - y1);
        }
      }
    
      public JComponent getComponent()
      {
        return mainPanel;
      }
    
      public void addMouseListener(MouseListener mouseListener)
      {
        mainPanel.addMouseListener(mouseListener);
      }
    
      public void addMouseMotionListener(MouseMotionListener mouseMotionListener)
      {
        mainPanel.addMouseMotionListener(mouseMotionListener);
      }
    }
    PaintPanelColorGrid.java -- a Grid of colored JLabels. Allows use selection of drawing color
    Java Code:
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.GridLayout;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.util.ArrayList;
    import java.util.List;
    
    import javax.swing.BorderFactory;
    import javax.swing.JComponent;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.event.ChangeEvent;
    import javax.swing.event.ChangeListener;
    
    public class PaintPanelColorGrid
    {
      private JPanel mainPanel = new JPanel();
      private Color[] colors =
      {
        Color.black, Color.red, Color.orange, Color.yellow, Color.green,
        Color.blue, Color.magenta, Color.pink, Color.cyan
      };
      private Color selectedColor = Color.black;
      private List<ChangeListener> changeListeners = new ArrayList<ChangeListener>();
      private JLabel selectedLabel = null;
    
      public PaintPanelColorGrid()
      {
        mainPanel.setLayout(new GridLayout(1, 0));
        LabelMouseListener labelListener = new LabelMouseListener();
        for (int i = 0; i < colors.length; i++)
        {
          JLabel label = new JLabel();
          label.setOpaque(true);
          label.setBackground(colors[i]);
          label.addMouseListener(labelListener);
          mainPanel.add(label);
        }
      }
    
      public JComponent getComponent()
      {
        return mainPanel;
      }
      
      public Color getSelectedColor()
      {
        return selectedColor;
      }
      
      public void setPreferredSize(Dimension preferredSize)
      {
        mainPanel.setPreferredSize(preferredSize);
      }
      
      public void addChangeListener(ChangeListener cl)
      {
        changeListeners.add(cl);
      }
      
      private class LabelMouseListener extends MouseAdapter
      {
        public void mousePressed(MouseEvent e)
        {
          JLabel label = (JLabel)e.getSource();
          if (selectedLabel != null)
          {
            selectedLabel.setBorder(null);
          }
          label.setBorder(BorderFactory.createLineBorder(Color.lightGray, 5));
          selectedLabel = label;
          selectedColor = label.getBackground();
          ChangeEvent ce = new ChangeEvent(PaintPanelColorGrid.this);
          for (ChangeListener cl : changeListeners)
          {
            cl.stateChanged(ce);
          }
        }
      }
    }
    PaintPanelTest.java -- main program
    Java Code:
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Point;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.event.ChangeEvent;
    import javax.swing.event.ChangeListener;
    
    public class PaintPanelTest
    {
      private static final Dimension PANEL_SIZE = new Dimension(400, 400);
      private static final Dimension COLOR_GRID_SIZE = new Dimension(400, 50);
      private JPanel mainPanel = new JPanel();
      private PaintPanel paintPanel = new PaintPanel();
      private PaintPanelColorGrid colorGrid = new PaintPanelColorGrid();
      private Color selectedColor = Color.black;
    
      public PaintPanelTest()
      {
        paintPanel.setPreferredSize(PANEL_SIZE);
        MyMouseAdapter myMouseAdapter = new MyMouseAdapter();
        paintPanel.addMouseListener(myMouseAdapter);
        paintPanel.addMouseMotionListener(myMouseAdapter);
        JButton clearButton = new JButton("Clear");
        clearButton.addActionListener(new ActionListener()
        {
          public void actionPerformed(ActionEvent e)
          {
            paintPanel.clear();
          }
        });
        JPanel clearBtnPanel = new JPanel();
        clearBtnPanel.add(clearButton);
        
        colorGrid.setPreferredSize(COLOR_GRID_SIZE);
        colorGrid.addChangeListener(new ChangeListener()
        {
          public void stateChanged(ChangeEvent e)
          {
            selectedColor = colorGrid.getSelectedColor();
          }
        });
        
        mainPanel.setLayout(new BorderLayout());
        mainPanel.add(paintPanel.getComponent(), BorderLayout.CENTER);
        mainPanel.add(clearBtnPanel, BorderLayout.SOUTH);
        mainPanel.add(colorGrid.getComponent(), BorderLayout.NORTH);
      }
    
      public JPanel getMainPanel()
      {
        return mainPanel;
      }
      
      private class MyMouseAdapter extends MouseAdapter
      {
        private int x0 = 0;
        private int y0 = 0;
        
        public void mousePressed(MouseEvent e)
        {
          x0 = e.getX();
          y0 = e.getY();
        }
        
        public void mouseDragged(MouseEvent e)
        {
          int x1 = e.getX();
          int y1 = e.getY();
          paintPanel.addLine(new PaintPanelLine(selectedColor, 
              new Point(x0, y0), new Point(x1, y1)));
          x0 = x1;
          y0 = y1;
        }
      }
    
      private static void createAndShowUI()
      {
        JFrame frame = new JFrame("PaintPanelTest");
        frame.getContentPane().add(new PaintPanelTest().getMainPanel());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
      }
    
      public static void main(String[] args)
      {
        java.awt.EventQueue.invokeLater(new Runnable()
        {
          public void run()
          {
            createAndShowUI();
          }
        });
      }
    }

  7. #7
    satu is offline Member
    Join Date
    Aug 2008
    Posts
    12
    Rep Power
    0

    Default

    your code for JButton looks fine just use some print statements
    in actionPerformed method with or without if condition.

  8. #8
    rmabrey is offline Member
    Join Date
    Sep 2008
    Posts
    3
    Rep Power
    0

    Default

    That person not doing me any favors is my professor and yeah i know he isn't. I appreciate everyones input. I realized it was working all the time it just was doing what i expected because of the way i phrased the condition in my if statement. Instead of
    if(e.getSource()==clearButton)
    {
    setBackground(Color.white);

    }
    I changed it to
    if(e.getSource()==clearButton)
    {
    setForeground(Color.white);

    }
    I realized that i was drawing in the foreground and not the background so i made the change and it worked. Although it only works one time, but thats all i need it for.
    Last edited by rmabrey; 09-24-2008 at 05:36 PM.

Similar Threads

  1. Replies: 8
    Last Post: 05-28-2008, 07:00 AM
  2. Help with JButton
    By geoffreybarwise in forum New To Java
    Replies: 4
    Last Post: 05-21-2008, 10:48 AM
  3. Need help with JButton event
    By adlb1300 in forum New To Java
    Replies: 2
    Last Post: 11-19-2007, 01:15 AM
  4. mouse over on JButton
    By gradon in forum Java Applets
    Replies: 1
    Last Post: 08-04-2007, 05:50 AM
  5. Problem with JButton
    By Marcus in forum AWT / Swing
    Replies: 1
    Last Post: 07-05-2007, 05:56 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •