Different colors on mouse click

Hi,
Can anyone tell me know how to change the color of the applet on click of a mouse. Different color for each click.
Any examples or sample code will be helpful.
Thanks in advance

How is this for a start:
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class Ncolor extends Applet
public void init()
     addMouseListener(new MouseAdapter()
          public void mousePressed(MouseEvent event)
               if (getBackground() == Color.red) setBackground(Color.orange);
                  else                       setBackground(Color.red);
public void paint(Graphics gb)
     gb.drawString("Test",50,50);}
Noah

Similar Messages

  • Change Color on mouse click

    Hi Guys.  I have followed Ned's code from another post, whereby if a text button is clicked, the color will change.  The code is like
    var clicked:Boolean = false;
    var clicked2:Boolean = false;
    btn1.addEventListener(MouseEvent.CLICK, btn1click);
    function btn1click(event:MouseEvent):void {
        clicked = true;
        var newColorTransform:ColorTransform = btn1.transform.colorTransform;
        if(clicked){
        newColorTransform.color = 0xc97f22;
        } else {
        newColorTransform.color = 0x000000;
        btn1.transform.colorTransform = newColorTransform;
        gotoAndStop(5);
    btn2.addEventListener(MouseEvent.CLICK, btn2click);
    function btn2click(event:MouseEvent):void {
        clicked2 = true;
        var newColorTransform:ColorTransform = btn2.transform.colorTransform;
        if(clicked2){
        newColorTransform.color = 0xc97f22;
        } else {
        newColorTransform.color = 0x000000;
        btn2.transform.colorTransform = newColorTransform;
        gotoAndStop(6);
    Now if I click on the first button, it changes color and stays like that, which is perfect.  If I click on btn2, this changes color and stays like it.  The problem is that if btn2 is pressed, it should change color and stay like it (as it is doing), but btn1 should return back to its normal color (black).  I am not sure how to achieve this.
    Any advise appreciated
    Cheers

    When you mention something is from another post it is helpful if you provide a link so that the context of the code offered can be understood. What you choose as a solution might not be the optimum choice.
    Use the following instead:
    var newColorTransform:ColorTransform = new ColorTransform();
    var btns:Array = new Array({btn:btn1, frameNum:5},{btn:btn2, frameNum:6});
    for(var i:uint=0; i< btns.length; i++){
        btns[i].btn.addEventListener(MouseEvent.CLICK, btnclick);
    function btnclick(evt:MouseEvent):void {
        var frameToGoTo:uint;
        for(var i:uint=0; i< btns.length; i++){
            if(evt.currentTarget == btns[i].btn){
                newColorTransform.color = 0xc97f22;
                frameToGoTo = btns[i].frameNum;
            } else {
                newColorTransform.color = 0x000000;
            btns[i].btn.transform.colorTransform = newColorTransform;

  • Change color with mouse click

    I have a textfield that has a red background color. How do i make it white by just clicking the textfield?

    See
    Component.setBackground
    MouseListener / MouseAdapter
    java.awt.Color

  • Mouse Click VS ListSelectionListener

    Dear All,
    As a new to JAVA GUI, I am asking the following questions. It could be a stupid questions. I am implementing a table which allows multiple selection.
    1.What's the different between the mouse click and ListSelectionListener for a table, which allows selection?
    2.If my table don't need to be modified or selected by the keyboard, will the ListSelectionListener brings any special benefit?
    3.Is ListSelectionListener more stable than the mouse click?
    Thank you very much for your help!

    Dear Hyayan,
    MouseEvent (to clicking) is a low level event. That means that each time you click the mouse on the component a mouse event will be fired even if the selected item was not changed.
    ListSelectionListener listens to ListSelectionEvent which is an event of a highter level. Whenever the selection was changed in the list this event will be fired.
    The advantages in ListSelectionEvent are:
    1. It is more specific for the list selection. If the user clicks inside the list but the selection was not changed the event will not be fired.
    2. It reactes to selection changes no matter what caused the change: mouse, keyboard or selections inside the code.
    It is usually better to use high level events rather than low level events. Use lower level events only when there is no high level event that satisfy you. Always check in which listeners a component supports in order to use the highest level events as possible.
    Best regards,
    Shai

  • Different mouse clicks & speed up mouse movements?

    Hello,
    Does Adobe Captivate recognise different mouse clicks better
    to say if it can record on RMB LMB and MMB clicks different
    effects? For example I wish to record Software Simulation project
    were on different mouse clicks (RMB, LMB, MMB) would have custom
    effects like "OrangeRing" for RMB " "GreenRing" for LMB etc?
    One more question plz: I found Published movie mouse
    movements are very slow can I make it move more fast without
    editing every slide separatelly?
    Thanks
    Ton

    Hello Tony,
    Whilst Captivate does recognize different mouse clicks (in so
    much as the application will capture a right-click menu) you cannot
    specify what type of mouse effect the application will use when you
    capture.
    What you can do is change the mouse click effect post
    capture. To do this and with a just captured project open carry out
    these steps:
    1. Select the slide that has a mouse pointer where you would
    like need to show a right-click action.
    2. Choose Slide > Mouse > Properties...
    3. In the Mouse Properties dialog make sure that the option
    "show mouse click" is selected and then show either the color or
    the custom effect you would like to use to represent the
    right-click operation.
    Naturally, at the very start of your movie/project you would
    need to inform the learner that each time they see the one of the
    effect you want them to right-click. You could also include some
    audio as well which would be important if you need to adhere to
    accessibility standards.
    In regard to your second question, in most cases you will
    find that you get the best result if you adjust the mouse timing
    using the Timeline.
    That said if you own a copy of Adobe Captivate 2 you can
    change the mouse Display and Appear After settings globally via the
    Mouse Properties dialog. Personally, for mouse movement I would not
    recommend this. Anyway here are the steps to carry that out.
    1. Select any slide that has a mouse pointer present.
    2. Choose Slide > Mouse > Properties...
    3. Click the Timing tab
    4. Change the Display time and Appear After values
    5. Click the Settings button
    6. Choose the appropriate options from both Which properties
    and which slide categories
    7. Click OK.
    Note : You can also show the Mouse properties dialog by left
    clicking on mouse icon on any of the slides in the Filmstrip
    Regards,
    Mark

  • Need a shortcut to "Allow pages to choose their own colors, instead of my selections above option preference" I know where it is and how to use it but I have to go through 7 mouse clicks to change it, then a few minutes later change it back. I also k

    Need a shortcut to "Allow pages to choose their own colors, instead of my selections above option preference" I know where it is and how to use it but I have to go through 7 mouse clicks to change it, then a few minutes later change it back. I also know the sequnce is alt t, alt o, alt c, alt a, then ok, ok. Got to be a way to make a one key short cut for this. I use a black background to reduce eye strain, but about 10% of the webpage I go to can't be send with black so I have to go into tools and hit 6 or 7 things to chnage it then after through with webpage have to do it all over at Not allow webpages to have own color. Very very cumbersome.
    == This happened ==
    A few times a week
    == made that way

    https://addons.mozilla.org/en-US/firefox/addon/toggledocumentcolors-198916/
    The above addon will solve your problem.
    Shortcut to toggle user color/page color :- Ctr+Shift+C

  • My Apple TV 2 is slow when trying to move through different menu selections. It is like a slow computer trying to catch up to mouse clicks. It eventually remembers the buttons that were pushed on the remote, but it freezes and takes a minute to catch up.

    My Apple TV 2 is slow when trying to move through different menu selections. It is like a slow computer trying to catch up to mouse clicks. It eventually remembers the buttons that were pushed on the remote, but it freezes and takes a minute to catch up.

    I had something similar a couple of week ago, it would scroll then stop, scroll then stop.
    At some point the porblem went away.
    Try unpowering and restarting your AppleTV.  Rsetart iTunes too.

  • Get the active cell in a table on a mouse click, so I can change its color

    Hi guys,
    I am looking at a small application.
    I  have a table. When a user clicks on a particular cell, I need the cell coordinates so that I can change its attributes (e.g. color change) by clicking a button.
    Edit position property of the table gives me the current cell coordinates, but when I click on a button, the previously clicked cell position is lost. How can I fix this problem?
    Is there a way to solve this problem?
    Thanks
    Ravi
    Solved!
    Go to Solution.

    rpula wrote:
    Thanks for the reply. But, Iam trying to avoid using event structures for someother reason in my code. Is there a way, this could be done without event structures.
    Please look at the code attached. Whenever the value in the table goes beyond 100, i want to click on the corresponding cell and then suspend it by using the suspend button, in which case the backgroud color should change to red.
    Thanks
    Saverio's suggestion to use an event structure is a good one so rather than exploring less efficient methods, could you please explain why you are avoiding teh use of an event structure? This will help us help you.
    Just trying to help,
    Ben
    Ben Rayner
    I am currently active on.. MainStream Preppers
    Rayner's Ridge is under construction

  • Mouse clicks in Safari sometimes unresponsive

    Hello all. I am having an infuriating issue with Safari 4.0.3. When I click near (but just miss) a button in the Safari toolbar (like the "home" button), then when I move my mouse and actually hit the button, the click will not register. I can sit there and click away merrily and it will not work. The button will not change colors and the click will not register. What I need to do is move the mouse far away from what I'm trying to click (like I have to "reset" it), then move it back and click to get the mouseclick to register.
    It also happens with bookmark bar links and tab close buttons.
    It is infuriating to just miss a button, click, move the mouse to the right place, and not be able to click the button (or bookmarks bar item or tab close X). Has anyone else had this problem? (P.S.: Now that it's so noticeable, it happens WAY more often than I thought!)
    I tend to doubt it is a mouse or driver issue since it only occurs in Safari, no other program.
    Thanks in advance for any help or ideas.

    Here is some more info that might help (and is 100% reproducible):
    If I click on a folder in the Bookmarks Bar, the links in that folder come up. Now, if I don't select anything, but instead mouse over a different item on the Bookmarks Bar, I can not select that item. What should happen is that the first click makes the links from the original folder disappear, and the second click should actually click the new link. But no amount of clicks will work. I have to click somewhere else to change the focus, then come back and click on the link.
    This also happens if I open a folder in the Bookmarks Bar, and then try to click on a button (like the Home button) or a tab.

  • DUAL MONITOR BUG: One Picture – One Monitor – Different Colors!

    There have been several threads discussing that Photoshop CS4 and OS 10.6. show wrong colors in dual monitor setups.
    The first one to prove this with a screen capture was jb510-LJ0JJQ in August 2009: http://forums.adobe.com/message/2207312#2207312
    Eight months and three OS updates later the problem is still there and makes professional work with more than one monitor a nuisance.
    Here's another actual example: A picture and its 100% identical copy showing different colors on one screen!
    Here's how to repeat it – try this at home ;-)
    1) In the finder make a copy of a rgb picture.
    2) Open one of the two identical pics in photoshop.
    3) Drag it to the other monitor.
    When releasing the mouse button you may see the bug already: the colors will "switch".
    4) To verify this go to system presets - monitors - and change the primary monitor (by dragging the menu bar to the other)
    5) Now open the identical copy you made in step 1) and see the difference!
    Here's a synopsis of suggested workarounds:
    1) disable open GL (which seem to makes no difference on my setup)
    2) click "desaturate monitor colors" but set desaturation to 0 (which prevents visual switching in step 3) (only if openGL is ON) but also leads to a wrong display in step 4+5
    3) make the hardware calibrated monitor your default monitor and strictly avoid changes or dragging pics to the other monitor (which seems to be the only reliable method)
    4) some guys even force both monitors to use the profile of their hardware-calibrated monitor (using color sync) to make sure they see what they should see on at least that one monitor. What a stone-age workaround for the the world's leading imaging program!
    Considering that reliable colors in professional (=multi monitor) settings should be the most basic function of photoshop this mayor malfunction should be solved with CS5! Otherwise we might have to live with it for some more years...
    Have Adobe and Apple realized this bug and on their agenda? Will it be gone with OS 10.6.3? Can anyone explain the reasons for this bad bug? Is there a "officially" recommended workaround?
    Thanks, regards,
    Eric

    There have been several threads dealing with this malfunction. But most faded out in silence or acceptance of the workarounds.
    http://forums.adobe.com/message/2207312#2207312
    http://forums.adobe.com/thread/521483
    http://forums.adobe.com/message/2272192#2272192
    http://forums.adobe.com/thread/311761?start=0&tstart=0
    http://forums.adobe.com/thread/618927?tstart=60
    http://forums.adobe.com/thread/603992?tstart=90
    http://www.wetcanvas.com/forums/showthread.php?t=552977
    http://www.hilfdirselbst.ch/gforum/gforum.cgi?post=368889?search_string=zwei%20monitor#368 889
    But man, this is no minor bug! Consistent colors are the by far most important basic function of photoshop. If you cannot rely on the colors in photoshop you can as well use "Preview" and "Word" for print production ;-)
    Carson, how did Apple react to your complaint? What do you mean with "they don't get it". Do they not see it? Or can't they get it right?
    Shall we open a thread at apple forums to point out that it's not the problem of a single user?

  • Is there a way to change the color of the Bezier Curves and points to a different color other than black  I find it perplexing while setting points and curves working on a photo that needs to be separated from it's background for placement on transparent

    Is there a way to change the color of the Bezier Curves and points to a different color other than black  I find it perplexing while setting points and curves working on a photo that needs to be separated from it's background for placement on transparent backgrounds. Any thoughts?

    Yes. Well, sort of: instead of a "path", set the pen tool to "shape" in the tool properties. Then set the fill colour to transparent, and the stroke colour to the colour you want. You can also set the stroke width.
    Not perfect, but at least you can see the path more clearly - the anchor points and handles still remain the default colour. Open the path panel, and right-mouse click the path shape to create a selection based on that shape. The Paths panel menu also allows you to create work paths based on that shape.
    Unfortunately when you try to move the handles the black thin outline appears again until you release the mouse button.
    This is one of several things that works better in Photoline: in Photoline, once the path is set to a specific colour, editing the path uses the actual colour and stroke width. which is extremely handy for creating path based selection with awkward background colours and/or a high resolution screen. In Photoline the handles and bezier points are also much, much larger, which makes it rather simpler to work with as well - especially on a higher resolution screen. And when selected the handles and points are a clear red with a black outline - again easier to spot and identify. I just works better, in my opinion.

  • Mouse clicking amd Dragging

    Hi, I have the following code so far, and when run in conjunction with other classes it creates a carousel feature.
    When you click and hold on the carousel and drag up or down, the carousel moves in the relevant direction.
    I am trying to change this click and drag, so instead when you click one of the polygons (which represent up and down arrows), the carousel moves up or down depending on which you click.
    Can anyone help with this?!
    Thanks very much!
    class ScheduleBarCanvas extends Canvas implements MouseListener,
    MouseMotionListener, ActionListener
    * CONSTANTS *
    /** Width of a slot, in pixels. */
    static final int SLOT_WIDTH = 2;
    /** Width of an entire day schedule bar, in pixels. */
    static final int BAR_WIDTH = Slot.SLOTS_PER_DAY * SLOT_WIDTH;
    /** Half of the height of a day schedule bar, in pixels. */
    static final int BAR_HALF_HEIGHT = 20;
    /** The width of an hour within a day schedule bar, in pixels. */
    static final double HOUR_WIDTH = BAR_WIDTH / 24;
    * The schedule day bars are represented as a rotatable 'wheel'. This value
    * defines the 'angle' allocated to a single day bar.
    private static final float DEGREES_PER_DAY_BAR = 10;
    * For convenience, this value represents the number of day bars that occupy
    * a 90-degree 'slice' of the schedule wheel.
    private static final int DAY_BARS_PER_90_DEGREES = (int) 9;
    * The maximum number of day bars that can be represented in the wheel.
    private static final int MAX_BARS = 9*2-1;
    * FIELDS *
    * Popup menu to use for right click menu. The right click menu allows users
    * to perform actions such as changing the climate for a selected period of
    * time.
    private final JPopupMenu rightClickMenu = new JPopupMenu();
    * Determines whether 'paste day schedule' is an available option in the
    * right click menu. 'Paste day schedule' should remain unavailable until
    * the user has copied a day schedule bar.
    private boolean allowPaste = false;
    * When the user has chosen to copy a day schedule, it will be stored here.
    private DaySchedule copiedDaySchedule;
    * A day schedule with the default period allocations.
    private final DaySchedule defaultDaySchedule;
    /** X coordinate of the left end of the schedule bars. */
    private int barLeftX;
    /** Y coordinate of centre of schedule bar display. */
    private int centreY;
    /** Width of canvas, pixels. */
    private int width;
    /** Height of canvas, pixels. */
    private int height;
    /** X coordinate of last mouse click. */
    private int lastMouseClickPositionX = 0;
    /** Y coordinate of last mouse click. */
    private int lastMouseClickPositionY = 0;
    /** X coordinate of last right mouse button click. */
    private int lastRightClickPositionX = 0;
    /** Y coordinate of last right mouse button click. */
    private int lastRightClickPositionY = 0;
    /** Start time of last selected period. */
    private Slot periodStartTime = new Slot(0);
    /** End time of last selected period. */
    private Slot periodEndTime = new Slot(0);
    /** Last-pressed mouse button. */
    private int pressedButton;
    * While clicking and dragging to modify the end time of a period, this
    * field stores the 'old' end time of the period.
    private int currentPeriodEnd;
    * While clicking and dragging to modify the end time of a period, this
    * field stores the width of the current period. At other times, this field
    * has the value 0.
    private int currentPeriodWidth = 0;
    * Rather than directly manipulating the window's canvas, a buffer is used.
    * All updates to the display are computed 'out of sight', by writing to
    * this buffer's Graphics object (see 'graphicsBuffer') and then copied to
    * the canvas in one go.
    private Image imageBuffer;
    private Image imageBuffer2;
    /** Graphics object buffer to use when updating the display. */
    private Graphics graphicsBuffer;
    private double animationSpeed = 0;
    private double simTimeInc;
    private double simTime = 0; // simulated time, HOURS from start
    /** Collection of days */
    private Schedule schedule;
    * The set of day schedule bars visible on screen at present. As the user
    * scrolls through different days, schedule bars will come in and out of
    * sight, and hence will enter and leave this array.
    private DayBar[] visibleScheduleBars;
    /** Stores the available schedulables */
    private List<Schedulable> palette;
    private int barZeroDay;
    /** Currently highlighted period - not currently used */
    private Period selection;
    /** Previously highlighted selection - not currently used */
    private Period oldSelection; // button 3 selections
    private Period dayDrag; // button 1 drag region
    private DaySchedule daySched; // schedule affected by drag
    * When clicking and dragging to change the duration of a Period, this value
    * is used to store the number of the slot being dragged.
    * If this is a new Period, and hence no prior boundary existed, this value
    * will be -1.
    private int draggedSlotBoundary;
    * When you right click on a Period, the system fills this value with the
    * number of the first slot in that Period. For instance, if 13:00 to 16:00
    * is set to 'away', and you right click at 14:40 (or any other slot inside
    * the 'away' Period), then this value will be set to the index of the slot
    * 13:00.
    private int firstSlotNumber;
    * When you right click on a Period, the system fills this value with the
    * number of the last slot in that Period. For instance, if 13:00 to 16:00
    * is set to 'away', and you right click at 14:40 (or any other slot inside
    * the 'away' Period), then this value will be set to the index of the slot
    * 16:00.
    private int lastSlotNumber;
    private DaySchedule selectedDaySchedule;
    private boolean createPeriods = true;
    * CONSTRUCTORS *
    * Setting various schedules that can be displayed
    * Initialises the display of the scheduler
    * Setting right click menu
    ScheduleBarCanvas()
    int delay = 0; // milliseconds
    int period = 40; // milliseconds
    final double updateFreq = 1000.0 / period; // H
    visibleScheduleBars = new DayBar[20];
    palette = new ArrayList<Schedulable>();
    palette.add(new Schedulable(new Color(50, 50, 220))); // away
    palette.add(new Schedulable(new Color(100, 180, 160))); // sleep
    palette.add(new Schedulable(new Color(150, 150, 120))); // busy
    palette.add(new Schedulable(new Color(200, 100, 20))); // relax
    defaultDaySchedule = new DaySchedule(palette);
    schedule = new Schedule(palette);
    Timer timer = new Timer();
    // Inner class construction for a java.util.Timer object with a
    // defined TimerTask to run processes. See the java.util library
    // in the Java API for details. Also refer to other java utility
    // assistance classes which may be useful to you in the future.
    timer.schedule(new TimerTask()
    public void run()
    simTimeInc = getAnimationSpeed() / (updateFreq * 200.0);
    if (simTimeInc > 0.0)
    { // Advance simulation time at
    simTime += simTimeInc; // current rate
    repaint(); // then update the display ASAP.
    }, delay, period); // schedule's init delay & repeat-call period
    JMenuItem menuItem1 = new JMenuItem(
    "Set climate to 'Away'", new ImageIcon("away.png")),
    menuItem2 = new JMenuItem(
    "Set climate to 'Sleeping'", new ImageIcon("sleep.png")),
    menuItem3 = new JMenuItem(
    "Set climate to 'Relaxing'", new ImageIcon("relax.png")),
    menuItem4 = new JMenuItem(
    "Set climate to 'Busy'", new ImageIcon("busy.png")),
    menuItem5 = new JMenuItem(
    "Reset day schedule", new ImageIcon("refresh.png")),
    menuItem6 = new JMenuItem(
    "Copy day schedule", new ImageIcon("copy.png"));
    menuItem1.addActionListener(this);
    menuItem2.addActionListener(this);
    menuItem3.addActionListener(this);
    menuItem4.addActionListener(this);
    menuItem5.addActionListener(this);
    menuItem6.addActionListener(this);
    rightClickMenu.add(menuItem2);
    rightClickMenu.add(menuItem4);
    rightClickMenu.add(menuItem1);
    rightClickMenu.add(menuItem3);
    rightClickMenu.add(menuItem5);
    rightClickMenu.add(menuItem6);
    addMouseListener(this);
    addMouseMotionListener(this);
    * GRAPHICS METHODS *
    * Updates the GUI.
    * @param g graphics object to draw to.
    public void update(Graphics g)
    // NB: repaint() above automatically calls update(Graphics g) ASAP.
    paint(g);
    * Updates the display.
    * @param g canvas to draw on.
    public void paint(Graphics g)
    float carouselRadius = 100; // Carousel radius in pixels
    float degreesPerPixel = (float) (57.29 / carouselRadius);
    if (currentPeriodWidth != 0)
    simTime += currentPeriodWidth * (degreesPerPixel / DEGREES_PER_DAY_BAR) * 24;
    currentPeriodEnd += currentPeriodWidth;
    currentPeriodWidth = 0;
    barZeroDay = (int) simTime / 24; // treat 1 sim sec as 1 hour
    int maxDayNo = barZeroDay + MAX_BARS;
    if (barZeroDay < 0 || maxDayNo >= Schedule.N_SCHEDULES)
    return; // invalid day number; do nothing
    Dimension dim = getSize();
    int maxX = dim.width - 1, maxY = dim.height - 1;
    barLeftX = maxX / 7;
    centreY = maxY / 2;
    if (width != dim.width || height != dim.height)
    width = dim.width;
    height = dim.height;
    imageBuffer = createImage(width, height);
    graphicsBuffer = imageBuffer.getGraphics();
    graphicsBuffer.clearRect(0, 0, width, height);
    graphicsBuffer.setColor(new Color(0, 0, 0));
    int hour = (int) simTime - barZeroDay * 24;
    float dayZeroOffsetAngle = (float) (((hour - 12) / 24.0) * DEGREES_PER_DAY_BAR);
    for (int barNo = 0; barNo <= MAX_BARS; barNo++)
    int dayNo = barZeroDay + barNo;
    int daysEarlier = DAY_BARS_PER_90_DEGREES - barNo;
    float dayAngle = daysEarlier * DEGREES_PER_DAY_BAR
    + dayZeroOffsetAngle;
    float z = carouselRadius * (float) Math.cos(0);
    float y = carouselRadius * (float) Math.sin(dayAngle / 57.3);
    float x = z / 20;
    DayBar dayBar = new DayBar(dayNo, schedule.getDaySchedule(dayNo),
    graphicsBuffer, barLeftX, centreY, x, y);
    visibleScheduleBars[barNo] = dayBar;
    for (int barNo = 0; barNo <= MAX_BARS; barNo++)
    visibleScheduleBars[barNo].paintBar(oldSelection, selection);
    g.drawImage(imageBuffer, 20, 0, null);
    g.setColor(Color.WHITE);
    g.drawRect(40,25,375,50);
    g.fillRect(40,25,375,50);
    g.drawRect(40,205,375,65);
    g.fillRect(40,205,375,65);
    Point bigArrowPoint1 = new Point(0,0);
    Point bigArrowPoint2 = new Point(0,0);
    Point bigArrowPoint3 = new Point(0,0);
    Point smallArrowPoint1 = new Point(0,0);
    Point smallArrowPoint2 = new Point(0,0);
    Point smallArrowPoint3 = new Point(0,0);
    bigArrowPoint1 = new Point(100,100); //top left
    bigArrowPoint2 = new Point(100,100); //middle right
    bigArrowPoint3 = new Point(100,100); //bottom left
    smallArrowPoint1 = new Point(100,100); //top left
    smallArrowPoint2 = new Point(100,100); //middle right
    smallArrowPoint3 = new Point(100,100); //bottom left
    Polygon bigArrow = new Polygon();
    bigArrow.addPoint(bigArrowPoint1.x+310,bigArrowPoint1.y-25);
    bigArrow.addPoint(bigArrowPoint2.x+320,bigArrowPoint2.y-25);
    bigArrow.addPoint(bigArrowPoint3.x+315,bigArrowPoint3.y-30);
    Polygon smallArrow = new Polygon();
    smallArrow.addPoint(smallArrowPoint1.x+310,smallArrowPoint1.y+105);
    smallArrow.addPoint(smallArrowPoint2.x+320,smallArrowPoint2.y+105);
    smallArrow.addPoint(smallArrowPoint3.x+315,smallArrowPoint3.y+110);
    g.setColor(Color.black);
    g.fillPolygon(bigArrow);
    g.drawPolygon(bigArrow);
    g.setColor(Color.black);
    g.fillPolygon(smallArrow);
    g.drawPolygon(smallArrow);
    addMouseListener(this);
    addMouseMotionListener(this);
    * Sets a new percentage value for the animation speed of the application.
    * @param animationSpeed desired animation speed.
    void setAnimationSpeed(double animationSpeed)
    this.animationSpeed = animationSpeed;
    * Returns the current speed of the animation, as a percentage.
    * @return the current speed of the animation, as a percentage.
    private double getAnimationSpeed()
    return animationSpeed;
    * Finds and returns a slot based upon the specified mouse position
    * coordinates.
    * @param x x coordinate of selection, relative to centre-left of schedule
    * bar display.
    * @param y y coordinate of selection, relative to centre-left of schedule
    * bar display.
    * @return a Slot value corresponding to the selected slot if available. If
    * no slot was selected, null is returned.
    private Slot findSlot(int x, int y)
    int barNumber = findDayBarNumber(x, y);
    if (barNumber == -1)
    return null;
    int foo = (x - (int) visibleScheduleBars[barNumber].getLeftAngleX());
    int bar = (barNumber * Slot.SLOTS_PER_DAY + foo / SLOT_WIDTH);
    return new Slot(bar + barZeroDay * Slot.SLOTS_PER_DAY);
    * Finds the day bar specified by the provided mouse coordinates, and then
    * returns its number.
    * @param x x coordinate of mouse position.
    * @param y y coordinate of mouse position.
    * @return the number of the day bar, or -1 if no day bar was found at the
    * specified mouse coordinates.
    private int findDayBarNumber(int x, int y)
    for (int barNo = MAX_BARS - 1; barNo >= 0; barNo--)
    DayBar dayBar = visibleScheduleBars[barNo];
    if (x >= dayBar.getLeftAngleX() && x <= dayBar.getBarRightAngleX()
    && y >= dayBar.getBarBottomAngleY()
    && y <= dayBar.getBarTopAngleY())
    return barNo;
    return -1;
    * EVENT HANDLER METHODS *
    * This event handler is unused.
    * @param evt ignored.
    public void mouseClicked(MouseEvent evt)
    * This event handler is unused.
    * @param evt ignored.
    public void mouseExited(MouseEvent evt)
    * This event handler is unused.
    * @param evt ignored.
    public void mouseEntered(MouseEvent evt)
    * This event handler is unused.
    * @param evt ignored.
    public void mouseMoved(MouseEvent evt)
    * Called when the mouse button is released.
    * 1. Displays the right click menu if the right mouse button was clicked 2.
    * Updates 'last click position' fields 3. Modifies end time of current
    * selection
    * @param evt mouse event information.
    public void mouseReleased(MouseEvent evt)
    if (evt.isPopupTrigger()) // was the menu requested?
    displayRightClickMenu(evt);
    // Update 'last click position' fields
    lastMouseClickPositionX = evt.getX();
    lastMouseClickPositionY = evt.getY();
    if (pressedButton == MouseEvent.BUTTON3)
    { // selecting
    int barPositionX = lastMouseClickPositionX - barLeftX;
    int barPositionY = centreY - lastMouseClickPositionY;
    periodEndTime = findSlot(barPositionX, barPositionY);
    selection.setEnd(periodEndTime);
    * Called when mouse button is pressed. Updates slot with schedulable.
    * @param evt mouse event information.
    public void mousePressed(MouseEvent evt)
    if (evt.isPopupTrigger()) // was the menu requested?
    displayRightClickMenu(evt);
    lastMouseClickPositionX = evt.getX();
    int barPositionX = lastMouseClickPositionX - barLeftX;
    lastMouseClickPositionY = evt.getY();
    int barPositionY = centreY - lastMouseClickPositionY;
    periodStartTime = findSlot(barPositionX, barPositionY);
    if (periodStartTime == null)
    return;
    if (periodStartTime.getDayNumber() < 0
    || periodStartTime.getDayNumber() >= Schedule.N_SCHEDULES)
    return; // boundary case.
    pressedButton = evt.getButton(); // 1=left, 2=mid or wheel 3= right
    if (pressedButton == MouseEvent.BUTTON1)
    { // dragging
    // but maybe creating new selection too so...
    oldSelection = selection;
    currentPeriodEnd = barPositionY;
    currentPeriodWidth = 0;
    dayDrag = new Period(periodStartTime, periodStartTime);
    int s = periodStartTime.getSlotNumber();
    if (!createPeriods)
    return;
    daySched = schedule.getDaySchedule(periodStartTime.getDayNumber());
    draggedSlotBoundary = daySched.findNearBoundary(s, 3);
    if (draggedSlotBoundary < 0)
    if (s < 0 || s >= Slot.SLOTS_PER_DAY)
    return; // boundary case
    // Not near a boundary, so create seed slot for new
    // period
    if (daySched.getSlot(s) == palette.get(0))
    daySched.setSlot(s, palette.get(1));
    else
    daySched.setSlot(s, palette.get(0));
    draggedSlotBoundary = s;
    } else
    Schedulable SS = daySched.getSlot(draggedSlotBoundary);
    if (draggedSlotBoundary < s)
    daySched.insert(SS, draggedSlotBoundary, s);
    else
    daySched.insert(SS, s, draggedSlotBoundary);
    else if (pressedButton == MouseEvent.BUTTON3)
    { // selecting
    oldSelection = selection;
    periodStartTime = findSlot(barPositionX, barPositionY);
    selection = new Period(periodStartTime, periodStartTime);
    * Called when the mouse is moved while a button on it is held down.
    * Changes the end time of the selected Period.
    * @param evt information about the current mouse cursor state, e.g.
    * position.
    public void mouseDragged(MouseEvent evt)
    lastMouseClickPositionX = evt.getX();
    int barPositionX = lastMouseClickPositionX - barLeftX;
    lastMouseClickPositionY = evt.getY();
    int barPositionY = centreY - lastMouseClickPositionY;
    if (pressedButton == MouseEvent.BUTTON1)
    { // dragging
    Slot selectedSlot = findSlot(barPositionX, barPositionY);
    currentPeriodWidth = barPositionY - currentPeriodEnd;
    if (draggedSlotBoundary < 0 || selectedSlot == null)
    return; // out of bounds
    if (!createPeriods)
    return;
    for (int s = draggedSlotBoundary + 1; s < selectedSlot.getSlotNumber(); s++)
    daySched.setSlot(s, daySched.getSlot(draggedSlotBoundary));
    dayDrag.setEnd(selectedSlot); // or could use Selection instead
    if (pressedButton == MouseEvent.BUTTON3)
    { // selecting
    Slot selectedSlot = findSlot(barPositionX, barPositionY);
    selection.setEnd(selectedSlot);
    * Displays the right click menu.
    * @param evt information about the current mouse cursor state, e.g.
    * position.
    private void displayRightClickMenu(MouseEvent evt)
    // Calculate positions of mouse click relative to centre-left of
    // schedule bars display.
    lastRightClickPositionX = evt.getX() - barLeftX;
    lastRightClickPositionY = centreY - evt.getY();
    // identify bar to modify
    DayBar db = null;
    for (int barNo = MAX_BARS - 1; barNo >= 0; barNo--)
    DayBar currentBar = visibleScheduleBars[barNo];
    if (lastRightClickPositionX >= currentBar.getLeftAngleX()
    && lastRightClickPositionX <= currentBar.getBarRightAngleX()
    && lastRightClickPositionY >= currentBar.getBarBottomAngleY()
    && lastRightClickPositionY <= currentBar.getBarTopAngleY())
    db = currentBar;
    break;
    if (db == null)
    return;
    // identify 'selected' section/setting
    Slot t = findSlot(lastRightClickPositionX, lastRightClickPositionY);
    int slot = t.getSlotNumber();
    if (slot < 0)
    return; // out of bounds
    // find out colour of selected section
    selectedDaySchedule = db.getDaySchedule();
    Color colour = selectedDaySchedule.getSlot(slot).colour;
    // go left/back; find earliest section with this colour
    firstSlotNumber = slot;
    while (true)
    Color currentSlotColour = selectedDaySchedule
    .getSlot(firstSlotNumber).colour;
    if (!currentSlotColour.equals(colour))
    firstSlotNumber++;
    break;
    if (firstSlotNumber > 0) // lower boundary case
    firstSlotNumber--;
    else
    break;
    // go right/forwards; find latest section with this colour
    lastSlotNumber = slot;
    while (true)
    Color currentSlotColour = selectedDaySchedule
    .getSlot(lastSlotNumber).colour;
    if (!currentSlotColour.equals(colour))
    break;
    if (lastSlotNumber < Slot.SLOTS_PER_DAY - 1) // upper bound case
    lastSlotNumber++;
    else
    break;
    rightClickMenu.show(evt.getComponent(), evt.getX(), evt.getY());
    * Called when the user selects an item from the right click menu. Changes
    * the Schedulable for the selected Period to the requested value.
    * @param evt an ActionEvent, providing information about the command that
    * was selected from the menu.
    public void actionPerformed(ActionEvent evt)
    String command = evt.getActionCommand();
    if (command.equals("Copy day schedule"))
    if (!allowPaste) {
    * If the user copies a day schedule, we must enable
    * the paste option in the menu.
    JMenuItem menuItem7 = new JMenuItem("Paste day schedule",
    new ImageIcon("paste.png"));
    menuItem7.addActionListener(this);
    rightClickMenu.add(menuItem7);
    allowPaste = true; // only do this once
    int barNo = findDayBarNumber(
    lastRightClickPositionX, lastRightClickPositionY);
    DayBar db = visibleScheduleBars[barNo];
    /* It's important that we copy the day schedule by value, not by
    * reference. If we just copy a reference, then if we 'copy' a bar,
    * changing the source bar after the copy operation will change what
    * is ultimately 'pasted'.
    copiedDaySchedule = db.getDaySchedule().clone();
    else if (command.equals("Paste day schedule"))
    int barNo = findDayBarNumber(
    lastRightClickPositionX, lastRightClickPositionY);
    DayBar db = visibleScheduleBars[barNo];
    db.getDaySchedule().insert(
    copiedDaySchedule, 0, Slot.SLOTS_PER_DAY-1);
    else if (command.equals("Reset day schedule"))
    int barNo = findDayBarNumber(
    lastRightClickPositionX, lastRightClickPositionY);
    DayBar db = visibleScheduleBars[barNo];
    db.getDaySchedule().insert(
    defaultDaySchedule, 0, Slot.SLOTS_PER_DAY-1);
    else
    * Identifies which new Schedulable was requested. This Schedulable
    * will replace the selected Period's Schedulable value.
    * For instance, if "Away" was selected from the menu, then we must
    * fetch the "Away" Schedulable.
    Schedulable schedulable;
    if (evt.getActionCommand().equals("Set climate to 'Away'"))
    schedulable = palette.get(2); // the 'away' Schedulable
    else if (evt.getActionCommand().equals("Set climate to 'Sleeping'"))
    schedulable = palette.get(0); // the 'sleeping' Schedulable
    else if (evt.getActionCommand().equals("Set climate to 'Busy'"))
    schedulable = palette.get(1);
    else if (evt.getActionCommand().equals("Set climate to 'Relaxing'"))
    schedulable = palette.get(3);
    else
    // Should never occur
    throw new Error("Unrecognised command.");
    // Now fill the selected Period with the requested Schedulable.
    selectedDaySchedule.insert(
    schedulable, firstSlotNumber, lastSlotNumber);
    * User is able to edit schedule when boolean is set to true
    * @param createPeriods sets state of interaction with day schedules
    void setCreatePeriods(boolean createPeriods) {
    this.createPeriods = createPeriods;
    }

    Here is the Apple document covering Magic Mouse faults.  Symptom number 6 seems the one to check out.  Is this a longstanding or a recently developed fault?
    And, of course, is it still under the 12 month warranty.
    One thing to pay particular attention to is the proximity of electronic items such as cradles for phones and the like which if active, can interfere with the signal.
    Troubleshooting wireless mouse and keyboard issues

  • A New Thread With Each Mouse Click

    Dear Java Programmers,
    The following code gives a bouncing ball inside of a panel. With each click, I need to have a different ball added and the previous ball to keep on bouncing. This part is a larger question of multitreading. When I have an action listener for mouse clicks, and I need to have a new thread with each click, how do I do this and where do I put it?
    Thank you in advance.
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import java.awt.BorderLayout;
    import java.awt.Graphics;
    import java.awt.*;
    import java.awt.Color;
    import java.awt.event.MouseListener;
    import java.awt.event.MouseEvent;
    public class Multiball extends JPanel implements Runnable, MouseListener {
    Thread blueBall;
    boolean xUp, yUp;
    int x= -10, y= -10, xDx, yDy;
    public Multiball()
    xUp = false;
    yUp = false;
    xDx = 1;
    yDy = 1;
    addMouseListener( this );
    public void mousePressed( MouseEvent e )
    x = e.getX();
    y = e.getY();
    blueBall = new Thread( this );
    blueBall.start();
    public void paint( Graphics g )
    super.paint( g );
    g.setColor( Color.blue );
    g.fillOval( x, y, 10, 10 );
    public void run()
    while ( true ) {
    try {
    blueBall.sleep( 10 );
    catch ( Exception e ) {
    System.err.println( "Exception: " + e.toString() );
    if ( xUp == true )
    x += xDx;
    else
    x -= xDx;
    if ( yUp == true )
    y += yDy;
    else
    y -= yDy;
    if ( y <= 0 ) {
    yUp = true;
    yDy = ( int ) ( Math.random() * 1 + 2 );
    else if ( y >= 183 ) {
    yDy = ( int ) ( Math.random() * 1 + 2 );
    yUp = false;
    if ( x <= 0 ) {
    xUp = true;
    xDx = ( int ) ( Math.random() * 1 + 2 );
    else if ( x >= 220 ) {
    xUp = false;
    xDx = ( int ) ( Math.random() * 1 + 2 );
    repaint();
    public void mouseExited( MouseEvent e ) {}
    public void mouseClicked( MouseEvent e ) {}
    public void mouseReleased( MouseEvent e ) {}
    public void mouseEntered( MouseEvent e ) {}
    public static void main(String args[])
    JFrame a = new JFrame("Ball Bounce");
    a.add(new Multiball(), BorderLayout.CENTER);
    a.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    a.setSize(240,230);
    a.setVisible(true);
    }

    Thank you very much for your replies. As for the multithreading, I have created 20 threads in the main method. With each click, one of these 20 threads starts in order. Now, how do I get a ball to paint with each one? How do I reference them in the paintComponent method?
       public void mousePressed( MouseEvent e )
             x = e.getX();
             y = e.getY();
             blueBall = new Thread( this );
             blueBall.start();
             count ++;
             System.out.print ("count is " + count);
          MyThread[] threads = new MyThread[20];
                for ( int ball = 0;ball < count; ball ++){
                threads[ball] = new MyThread ("" + ball);
                threads[ball].start ();
       }

  • Mouse clicks send app to crazy land

    I have a multi-threaded app with two main windows. One is the data display / main user interface event handler. The other is a seperate window with nothing but the menu bar--basically categorized commands that may be executed independent of what the main user interface is doing. This way I can move the commands around, hide them, etc--they are seperate.
    From the user interface I am running a script. At first the sub-vi that ran scripts was a modal 'Cancel' button to end the script and return to the user interface. The modal property kept the user from doing anything with the user-interface while the script was executing. Perfect. The problem is, it also kept the user from accessing the command window. So I changed the scri
    pt from a modal dialog box to a non-modal pop-up window that i set to Always-on-Top. This allows access to the command window and keeps the 'Cancel' button on top so it won't disappear behind the user interface if the main window gets clicked. Also, the user interface remains locked out because the script sub-vi is called from the user interface event handler.
    The problem I have is that clicking on the main user interface (for example, selecting a different tab to view) while the 'Cancel' button dialog box is visible, does nothing. When the dialog box exits however, all of the clicks done previously (which you'd think would have been forgotten), get propogated. The application goes haywire momentarily trying to change and update things. If you clicked five different tabs while the dialog box was open, it would do nothing, then all of a sudden (when the dialog box exits), flip rapidly between the five different tabs selected, as fast as possible.
    Is there any way to cancel
    or ignore these mouse click events that get sent to the main user interface? Is this a problem with the windows Always-on-Top setting?

    This is certainly occuring because of the "Always on Top" selection. However, there is one option you have here. You could try using Dynamic Events. They're new to LabVIEW 7.0. You can actually unregister a particular event (tab changed) and have it only trigger when you want. For instance, you could unregister this right before the cancel window comes up. Then, if the user clicks the tabs, since this event is unregistered, they will not be tallied. Then, when you get back to that window, there will be no events stored up so nothing should happen.
    J.R. Allen

  • Mouse clicks not recognized?

    I have a 20" iMac w/ the most recent updates. In the past couple of days I have a problem with mouse clicks not being recognized. It seems to happen when I begin to fill in a text field either in Safari or the Finder (like trying to enter username/password, to authenticate in the finder, etc) The wierd thing is that this only happens on one of the two user accounts on this computer. I have also created a new user account and it is fine. I've looked for applications that are different, but can't find any. I have repaired permissions and repaired the disk through disk utility.
    I am at the end of my rope! Please help!

    I somehow managed to fix it, for now. I think I ended up resetting the PRAM. I gave up trying software solutions and unplugged everything, including the iMac's power cable, and cleaned up the mess of cables behind my desk because I needed some time to think. After starting up the computer, everything seems to be fine. If the problem comes back, I'll post here again. Thanks for the suggestion!

Maybe you are looking for