Shweta Shaw
Shweta Shaw

Reputation: 53

Adjustable circle in GUI

I am trying to write an applet program in which a circle is drawn. The size of circle will increase if i press L and decrease if I press S.

import java.applet.Applet; 
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

public class oval extends Applet implements KeyListener{

    private int d=10;
    @Override
    public void init() {
        setSize(500,500);
        addKeyListener(this);
    }
    @Override
    public void paint(Graphics g) {
        super.paint(g);
        g.drawOval(100, 100, d, d);
    }
    @Override
    public void keyTyped(KeyEvent e) {   
    }
    @Override
    public void keyPressed(KeyEvent e) {
        if(e.getKeyChar()=='L')
            d=d+5;    
        else if(e.getKeyChar()=='S')
            d=d-5;
        repaint();
    }
    @Override
    public void keyReleased(KeyEvent e) {
        throw new UnsupportedOperationException("Not supported yet.");
    }
}

Upvotes: 0

Views: 302

Answers (1)

user2494817
user2494817

Reputation: 697

EDIT: Sorry, i didn't read your code completely... You were infact using KeyEvent right but when you are comparing the chars you need to do lowercase l not uppercase:

if(e.getKeyChar() == 'l')

not

if(e.getKeyChar() == 'L')  //this will work if the user presses Shift+l

I just showed you another way of doing it, the way i have it set up will work for both lowercase l and uppercase l. So it isn't case sensitive.

You were not properly using KeyEvent to trigger the certain key. Here is your code tested and working:

import java.applet.Applet;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

public class oval extends Applet implements KeyListener
{
    private int d=10;

    @Override
    public void init() 
    {
        setSize(500,500);
        addKeyListener(this);
    }

    @Override
    public void paint(Graphics g) 
    {
        super.paint(g);
        g.drawOval(100, 100, d, d);
    }

    @Override
    public void keyTyped(KeyEvent e) 
    {
    }

    @Override
    public void keyPressed(KeyEvent e) 
    {
        if(e.getKeyCode()==KeyEvent.VK_L)
            d=d+5;    
        else if(e.getKeyCode()==KeyEvent.VK_S)
            d=d-5;
        repaint();
    }

    @Override
    public void keyReleased(KeyEvent e) 
    {

    }
}

I removed the error you were throwing through keyReleased event because i have no idea why that was there...

Upvotes: 1

Related Questions