Scrollbars and Mouse monitoring in a JFrame

class Akim extends JFrame
     public Akim()
          super("Drawing lines");
          pack();
          setSize(640,640);
          setVisible(true);
     public void paint(Graphics g)
          super.paint(g);
          g.setColor(new Color(200,200,250));
          g.fillRect(40,40,400,400);
          g.setColor(new Color(255,255,255));
          for(int i = 2; i<=22; i++)
               g.drawLine(20*i,40,20*i,440);
          for (int i=1;i<=22;i++)
               g.drawLine(40,20*i,440,20*i);
class blah
     public static void main(String[] args)
          Akim me = new Akim();
          me.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}I am keeping the size down because if it gets bigger it goes off the screen. I would like to know how to add scrollbars.
I would also like to display something whenever someone clicks in one of the squares. How do I get the location where the mouse was pressed?
I only started working with JFrames yesterday so please keep it simple(if possible).
Thanks for any help.

Here is an example with a little of everything I mentioned:import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.net.URL;
import javax.imageio.*;
import java.io.IOException;
public class SwingExample extends JFrame implements MouseListener {
    public SwingExample() {
        super("This is an example");
        try {
            Image largeImage = ImageIO.read(new URL("http://today.java.net/jag/bio/JagHeadshot.jpg"));
            // ImagePanel is a JComponent subclass (see below)
            ImagePanel displayPanel = new ImagePanel(largeImage);
            // by addint a mouse listener to it, we can listen for clicks on the image
            displayPanel.addMouseListener(this);
            // content pane is the main container for the frame
            Container cp = getContentPane();
            // wraps the image panel in a scroll pane
            JScrollPane scroller = new JScrollPane(displayPanel);
            // tell the scrollbar what size you would like it to be, otherwise
            // it will try to be as large as the viewport component
            scroller.setPreferredSize(new Dimension(100, 100));
            // add the scrollpane to our frame here
            cp.add(scroller);
        catch (IOException ioe) {
            ioe.printStackTrace();
        // swing components use layout managers to help with resizing frames.
        // pack() tries to resize all components to their preferred size using
        // the layout managers. By setting the layout of a component to null,
        // you can use setBounds or setSize to explicitly tell components how
        // big they should be, but they won't automatically resize.
        pack();
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    // since we said we implement the MouseListener interface, we must include
    // all the methods. Of course, you can leave the body blank if you are not
    // interested in an event
    public void mousePressed(MouseEvent evt) {
        System.out.println("Pressed at " + evt.getX() + "," + evt.getY());
    public void mouseReleased(MouseEvent evt) {
        System.out.println("Released at " + evt.getX() + "," + evt.getY());
    public void mouseClicked(MouseEvent evt) {
        System.out.println("Clicked at " + evt.getX() + "," + evt.getY());
    public void mouseEntered(MouseEvent evt) {
        System.out.println("Entered at " + evt.getX() + "," + evt.getY());
    public void mouseExited(MouseEvent evt) {
        System.out.println("Exited at " + evt.getX() + "," + evt.getY());
    // simple overwritten component to display an image
   class ImagePanel extends JComponent {
       private Image drawImage;
       public ImagePanel(Image image) {
          setImage(image);
       public void setImage(Image image) {
          if (image == null) {
             this.drawImage = null;
             return;
          int width = image.getWidth(this);
          // if the image is not fully loaded, it's width will
          // return 0
          if (width <= 0) {
             MediaTracker tracker = new MediaTracker(this);
             tracker.addImage(image, 0);
             try {
                tracker.waitForID(0);
             catch (InterruptedException ie) {}
             width = image.getWidth(this);
          int height = image.getHeight(this);
          this.setPreferredSize(new Dimension(width, height));
          this.drawImage = image;
       // overwrite paintComponent here instead of paint
       public void paintComponent(Graphics g) {
          g.drawImage(drawImage, 0, 0, this);
    public static void main(String[] args) {
        JFrame frame = new SwingExample();
        frame.setVisible(true);
}

Similar Messages

  • Cover flow Scrollbar and mouse wheel issue?

    When I scroll my podcasts in cover flow view using the mouse wheel it skips some of the podcast album art.
    What I mean is when moving the scrollbar left or right with the mouse wheel the scrollbar skips like half way instead of being able to scroll every single album art one after the other.
    Is this normal and if so why is it designed this way?

    Hi..
    Might be help for you here >  OS X Lion: Vanishing Scroll Bars & How to Get Them Back | Apartment Therapy Unplggd

  • HT1752 I have an old iMac (the rounded type with monitor).  I need a new keyboard and mouse.  Will any work?  thanks for any help!

    I have an old iMac for 2002....it's the rounded type that has an attached monitor.  The software is way outdated (OS X 10) and I only really use now to access 3,000 plus songs and old video of the family.  Both the keyboard and mouse no longer work.  Am I able to use any keyboard/mouse and plug in using USB?  Thanks for any help!

    Most any USB mouse or keyboard should work. Borrow one if you can and just plug it in.
    If the USB circuits are at fault then you can access via Firewire Target Mode with another Mac in order to get at the files.
    http://support.apple.com/kb/HT1661
    Another alternative would be to remove the hard drive and use a USB adapter to access it as an external  drive.
    http://eshop.macsales.com/item/NewerTech/U3NVSPATA/

  • Since my G5 died I was thinking about getting a Mac Mini, but I have a ViewSonic Monitor (from 2004) and a USB keyboard and mouse - I also have the external drive tha downloaded my files on to. Do you think the monitor, keyboard and mouse will work on it?

    Since my G5 died I was thinking about getting a Mac Mini, but I have a ViewSonic Monitor (from 2004) and a USB keyboard and mouse - I also have the external drive that I downloaded my files on to. Do you think the monitor, keyboard and mouse will work on it? Would I have to get a hub so I could use the stuff I already have? Is that viewsonic too old to work on it?
    What else would I need? Please advise...

    Yes for keyboard and mouse.
    The monitor will work if it has an HDMI, VGA ir DVI input. If it only has a VGA input you will need this adopter
    http://store.apple.com/us/browse/home/shop_mac/mac_accessories/cables/cable_choo ser#selected-step1=MINI-DISPLAY-PORT&selected-step2=VGA&step=3

  • Want to run my PC on my G5 monitor, using one keyboard and mouse?

    I have a IMAC G5 (pre-intel) and would like to hook my PC tower to the G5's monitor. It would also be great to use only one keyboard and mouse to operate both systems.
    In this forum, I found a reference to the "Gefen SL Switcher". This looks like the solution, except my G5 has a wireless mouse and keyboard. The Gefen manual on line does not have much content.
    Does anyone know of a solution for running my PC tower into my G5 with wireless mouse and keyboard?

    The cordless keyboard and mouse are going to be problematic.
    What kind of work do you plan to do on the PC?
    if it isn't anything graphics intensive, you could set up a vncserver on the PC, and use "chicken of vnc" viewer.
    Both are free:
    http://www.tightvnc.com/
    and
    http://sourceforge.net/projects/cotvnc/
    MacBook 2.0GHz (white)   Mac OS X (10.4.8)  

  • Is there anyway to have an 11 inch mac air connected to an external monitor with lid closed and still be able to see content. I have a wireless ketboard and mouse and have tried everything. Only works when plugged in.

    Is there anyway to have an 11 inch mac air connected to an external monitor with lid closed and still be able to see content. I have a wireless ketboard and mouse and have tried everything. Only works when plugged in.

    You are referring to a feature called Clamshell Mode, please read Clamshell Mode setup for instructions.
    BTW when posting when you use generalities such as "have tried everything" this tells us nothing. When posting please be specific and try to paint a complete picture. It just makes things easier for those trying to help you.

  • Sharing 1 monitor, keyboard and mouse

    I have a brand new macbook (bought March 1, 2007). I additionally own a Dell tower running Windows XP. Is it possible to have the macbook and Dell PC share 1 monitor, keyboard and mouse via a KVM switch? How do I do it? What cables do I need?
    MacBook MA700LL/A   Mac OS X (10.4.8)  

    USB for the Keyboard/Mouse
    Mini-DVI to DVI or VGA (whichever your KVM switch uses) adapter for the video.

  • Is it possible to connect an older Power Mac (running OS 10.5.8) to an iMac running 10.9.5. I want to share the monitor, keyboard and mouse and switch between the two computers.

    Is it possible to connect an older Power Mac (running OS 10.5.8) to an iMac running 10.9.5. I want to share the monitor, keyboard and mouse and switch between the two computers.

    as far as I know then the target display mode is not an option with such an old mac

  • Monitor, Keyboard and Mouse sometimes stop Working

    I'm having an issue with my computer, it is a new build on a MSI 890FXA-GD65 motherboard. Sometimes randomly while i play a game, my monitor goes to sleep and wont wake up (monitor is connected via VGA port to my Radeon HD 5670 GPU), my keyboard and mouse turn off(both usb, mouse is Logitech, the red light on the bottom turns off), the computer still runs all the lights are on. Also, the front panel reset and power buttons wont work, the only way to shut it off is by the power switch on my power supply. Any ideas as to what might be the problem?

    Quote from: Svet on 21-July-11, 03:02:11
    Run CPU-Z http://www.cpuid.com/downloads/cpu-z/1.58-setup-en.exe
    and show screenshots from memory and spd pages
    Quote from: romie_rome on 29-July-11, 10:09:27
    It was set to 1333 by default, everything in BIOS regarding memory is on auto.
    By romie_rome at 2011-07-28
    By romie_rome at 2011-07-28
    Switch command rate to 2T in BIOS Setup,
    then retest

  • Mouse skip imac 27 (ATI Radeon HD 5750) and second monitor

    Hi
    Yesterday i bought a new mousepad and a second monitor
    I noticed that i had some trouble with my mouse skipping around the monitor, and my first thought was for my mousepad texture, but is not that
    this morning i tried:
    - with different surfaces, but with no luck - still skipping around
    - try different mouse: a small laptop mouse - still skipping around
    - try different mouse: old mighty mouse (USB) - still skipping around (it is also very slow even a top speed)
    - then i try different USB ports - still skipping around
    after that i thought at yesterday changes... since the mac is new, i did install some different software and A NEW MONITOR
    so i tried to unplug the new monitor and the mouse works fine.... i actually got a little worried
    i did plug the monitor again, turn it back on and everything worked... turn monitor off and mouse skips around
    SO.. the problem is that with a second monitor pluged in but turned off, mouse get crazy
    CAN'T MOVE THIS DISCUSSION OR DELETE? WRONG CATEGORY

    https://discussions.apple.com/message/15340928#15340928

  • MBP and 24" monitor

    Hi,
    I am getting a 15" MBP and a 24" glossy monitor. When I connect the MBP to the monitor what happens? Where do I type and what do I use as a mouse? Does the $999 monitor come with a mouse and keyboard or are those extra? Do I just plug the MBP into the monitor close the MBP and put it off to the side, then attach a keyboard and mouse to the monitor,or does the MBP need to remain open and if so isn't it going to be distracting? Also would I need to use the MBP as a mouse and keyboard?
    Sorry for the stupid question...
    Thanks

    Where do I type and what do I use as a mouse?
    The keyboard and trackpad on the computer, or one connected to any USB port. The display needs to be connected to the computer through USB to use any of the display's USB ports.
    are those extra?
    Yes.
    Do I just plug the MBP into the monitor close the MBP and put it off to the side, then attach a keyboard and mouse to the monitor
    Yes. See the note about USB above.
    (48593)

  • Want Mac mini and G4 to share Display and USB keyboard and mouse

    I bought a KVM switch at a local electronics store. I got the only one that claimed Mac compatibility (PPA Int'l). I can't plug the switch into the G4 Cube. No such ports. With the adapter that accompanied my brand new Mac Mini, I can plug the KVM monitor port into the mini's monitor port, BUT that port is currently being used by the Apple DVI-to-ADC adapter I bought so I can connect my Cinema Display to the Mac mini.
    The KVM switch wants 3 ports on each computer: a VGA (monitor) port, the keyboard port, and the mouse port; but the keyboard/mouse connectors are not USB.
    As things stand--without the switch--I can shut down whatever computer I'm working on (mini or Cube), unplug the display from one, connect it to the other, power up and everything's fine. I suppose the only advantage with the KVM switch is being able to power off, switch, then power on without having to move the display plug.
    My QUESTION is, does anybody manufacture a KVM switch I can use between two Macintosh computers to share use of my USB keyboard powered from a USB port on the display, and my USB mouse powered from a USB port on the keyboard?
    Or is the answer NOT to go for the convenience of a KVM switch?
    Does it matter that the mini OS is Leopard, and the Cube OS is Tiger?
    I am heartily impressed with the mini. Setup was over in 5 minutes, and I must say it's fast. Appreciate any help from the experts. --Spot

    I had the same problem, and finally came up with two other alternative solutions.
    First, if you have a recent LCD monitor, it is fairly simple and cheap. The Mini has a digital connection for the monitor. My G4 400 MHz has both digital and analog connections. I have a Samsung 19 inch widescreen monitor that has both a digital and an analog input. I connected the G4 to the monitor using the analog input with my old cable, and connected the Mini using the digital input. The Samsung has a switch that will use either the digital or analog input - very easy.
    Now the keyboard and mouse. I got a 6 foot USB cable with the A plug on one end and B plug on the other, plugged the A plug end into the G4, and ran the cable with the B plug up near the Mini. It helps to keep it close. You already have the keyboard/mouse plugged into the Mini. You simply unplug the keyboard cable from the Mini, and plug it into the B plug from the G4. Switch the monitor from digital to analog, and you have the G4 (remember to start it up). Once you have run the cables, it takes about 10 seconds to make the switch.
    Second, and I use both ways, is to get an inexpensive wired router. I bought a Belkin 4 port router (about $30, I think), got a couple Cat 5 cables, hooked both the Mini and G4 up to the router, along with my internet connection, and have both computers available on one monitor with no physical switching involved. You will need to go to System Preferences/Sharing and turn on Personal File Sharing (there may be another change, but I can't remember it right now).
    When all is hooked up, you go to GO in the Finder Menu Bar (make sure the G4 is booted before doing this) click on either NETWORK or CONNECT TO SERVER, find your G4 and connect. It may be confusing the first few times, but it works great because you have access to both computers at once, along with your internet connection - the best of both worlds!
    I did this in January of this year, so please forgive me if I have forgotten a step somewhere. Ask me and I'll be glad to try to walk you through it. The first solution is the simplest to do, and the second in the most versatile. It's your choice.
    Hope this helps. Just don't be intimidated by it - if I can figure it out, we can get you connected. Good luck!

  • Lost keypresses and mouse clicks:  Hardware problem?

    I recently bought an Intel MBP, and I've been noticing strange behaviors with regard to keypresses and mouse (touchpad) clicks getting lost sometimes. The problems I'm having are hard to reproduce intentionally, but I can hear the keypresses and mouse button clicks when I do them, yet nothing happens. While it's possible, that I sometimes am hitting the wrong key, I have been paying closer attention lately to this problem, and of course, the mouse button kinda hard to hit incorrectly. Here are some examples of weird things I encounter:
    If I click in a text field in Safari, sometimes the first keypress (and only the first) will get lost.
    Sometimes, the first keypress I type right after clicking gets lost. For instance, just now, I noticed a typo in the above sentence, so I clicked on the character and hit the Delete key. The cursor was in the right place, but the delete didn't happen. I had to press the key again.
    Sometimes, even when the window for sure has focus and the pointer is squarely pointing to a link, the first click on the link won't take. I have to click it again. Since Safari doesn't have adequate feedback for when you click something, that can get particularly frustrating. Similar things happen with buttons in applications or on the title bar.
    If I'm using an X11 app, and I copy/paste with the clipboard, the touchpad won't respond to movement for 2 or 3 seconds afterward. This is particularly visible with "nedit". I don't think this is an "ignore accidental touchpad input" issue, because this only happens with clipboard actions; other keys don't have this effect. I haven't noticed this with native apps.
    However, I have noticed in X11 and native apps, sometimes, Ctrl/Cmd-C and Ctrl/Cmd-V will be ignored. They're never ignored if I selected the text using the keyboard (shift+arrows), but if I select the text with the mouse and then use the shortcut to copy, the copy/paste sometimes doesn't happen.
    I have noticed that if I am more deliberate about clicks (make sure to hold the button down longer), the probability of losing the event SEEMS to be reduced, but not eliminated. Is there a debounce circuit involved that's causing me trouble?
    This kind of loss of input is unusual to me. I have a number of Windows and Linux PCs, and I've never experienced this sort of thing. I've also used a few Macs at school before I got this one and didn't notice anything weird.
    Can anyone shed some light on this for me? It would seem odd that I should have to modify my keyboard/mouse using behavior when switching to the Mac. If the problem is hardware, how can I prove it? (Perhaps I could boot Knoppix from a CD and mess around a bit.) If the problem is software, is this a case of MacOS trying to second-guess user input?
    Thanks!

    Theosib,
    Apple regularly monitors these boards, but you may never see a response from Apple directly. Assume this is a user to user forum. If you are having a problem with the computer and need a response from Apple call 1-800-APLCARE and speak to customer relations at that office if the technician is not able to satisfy your needs.
    Your problem while not unheard of, is more uncommon than the boards may make you believe.
    Remember, Spotlight is constantly indexing. If your hard drive is overfull, it may take longer for Spotlight to index, thus cause a multitasking delay. If you have many Dashboard widgets, they may all be trying to access the net for updates at once, and again, a delay might happen. I've written a FAQ* about several other factors which may affect Mac OS X speed, which could in theory also affect keyboard input:
    http://www.macmaps.com/Macosxspeed.html
    And of course, you should always check Apple menu -> System Preferences -> Keyboard and Mouse to make sure your input settings are the ones most comfortable for you when using the keyboard. It is possible a repeat rate could cause a delay.
    Edit: I attempted to answer another of your questions here recently with an update:
    http://discussions.apple.com/click.jspa?searchID=-1&messageID=3988468
    Please take a look and see if it answers your question.
    * Links to my FAQs may give me some compensation.

  • Keyboard and mouse randomly don't work after boot

    Hello there, I have been having a problem lately  with the keyboard. Some times after the booting process it doesn't work, forcing me to restart my laptop even 3 or 4 times before getting it to work properly.
    Here is the keyboard boot process. wich has actually a problem that I can't understand clearly.
    dmesg |grep keyboard
    [    2.308714] atkbd serio0: Failed to deactivate keyboard on isa0060/serio0
    [    2.959550] input: AT Translated Set 2 keyboard as /devices/platform/i8042/serio0/input/input0
    I noticed this error during the boot preocess, how should it be interpreted?
    I'm sure in the kernel, the device atkbd is selected.
    The synaptics mouse instead, doesn't work properly in X
    My mouse is a synaptic touchpad and when I start x, instead of loading the synaptic device, xfce simply see it as ps/2. Also this happens randomly.
    dmesg |grep mouse
    [    2.098008] mousedev: PS/2 mouse device common for all mice
    [    4.836233] psmouse serio1: synaptics: Touchpad model: 1, fw: 7.4, id: 0x1e0b1, caps: 0xd04773/0xe40000/0x5a0400, board id: 3655, fw id: 631163
    [    6.696381] psmouse serio1: synaptics: Touchpad model: 1, fw: 7.4, id: 0x1e0b1, caps: 0xd04773/0xe40000/0x5a0400, board id: 3655, fw id: 631163
    Xorg conf:
    Section "inputdevice"
       identifier "synaptics touchpad"
       driver "synaptics"
        Option "TapButton1" "1"
        Option "TapButton2" "2"
        Option "TapButton3" "3"
    Endsection
    Any suggestion?

    Welcome to Apple Discussions!
    Has your keyboard and mouse quit working altogether or just when the computer is hot? And do I understand that an external keyboard and mouse will work with no problems?
    And I am wondering about your computer running unusually hot. Are your fans operating properly? You might want to run the extended version of the Apple Hardware test to be sure that the fans and thermal sensors are working properly. If they are not, you will get one or more error codes.
    Another thing to do to check when your Mac is unusually hot is the Activity Monitor. Select "All Processes" at the top right and check for any process running that should not be which is using lots of CPU.
    I don't know if the keyboard problem is related to the heat problem or not, but I would want to know what is causing the heat problem too. Over time, excessive heat can cause damage to the logic board. It could also conceivably damage the ribbon cable which connects the keyboard and I would guess that the trackpad could also be affected. So it is important to see what is going on here. If you have been experiencing excessive heat on a regular basis, this might be the underlying cause of your keyboard and trackpad problems. If so, the heat problem will have to be fixed or the other problem will recur over time.
    Try the AHT and post back with any results. Also, use iStatPro to check on your fans and make sure both are running at roughly equal speeds and that they run faster when the computer gets hot.
    Good luck!

  • External keyboard and mouse not working in closed clamshell mode

    Hi - can someone help with this strange issue.  Yesterday in closed clamshall everything was working fine. Today I cannot use my external keyboard and mouse.  Note the external monitor does show the screen (after the blue flicker etc), but keyboard and mouse is just not detected.
    Using Mac OS X (10.7.5).  Tried fiddling the "mirror" settings etc in the display preferences but nothing seems to help.  Really annoying....please help

    don't worry - figured it out !

Maybe you are looking for