Showing posts with label draw circle. Show all posts
Showing posts with label draw circle. Show all posts

Friday, 21 June 2013

Creat Menu bar in Java Swing and draw various shapes




// TO create Menu Bar

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

class menu extends JFrame implements ActionListener
{
    JMenuBar mb;
    JMenu draw;
    JMenuItem rect,line,oval;
    //Container c;
    menu()
    {
        //c=getContentPane();
        setLayout(null);
        mb=new JMenuBar();

        draw=new JMenu("draw");
        draw.setMnemonic('d');
        mb.add(draw);

        rect=new JMenuItem("rect");
        rect.addActionListener(this);
        rect.setMnemonic('r');
        draw.add(rect);

        line=new JMenuItem("line");
        line.addActionListener(this);
        line.setMnemonic('l');
        draw.add(line);

        oval=new JMenuItem("oval");
        oval.addActionListener(this);
        oval.setMnemonic('o');
        draw.add(oval);

        setJMenuBar(mb);
    }

    public void actionPerformed(ActionEvent ae)
    {
        String str=ae.getActionCommand();
        Graphics g=getGraphics();

        if(str=="rect")
        g.drawRect(100,100,50,50);

        if(str=="line")
        g.drawLine(300,50,400,350);

        if(str=="oval")
        g.drawOval(400,50,50,50);
    }

    public static void main(String args[])
    {
        menu f=new menu();
        f.setTitle("my frame");
        f.setSize(500,500);
        f.setVisible(true);
    }
}

Monday, 17 June 2013

Program for key event to draw various shapes


import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

class keydraw extends JFrame implements KeyListener
{
    Label lbl_title;

    int ch;
    int a;

    keydraw()
    {
        a=0;
        addKeyListener(this);
    }

    public void keyPressed(KeyEvent ke)
    {
        ch=ke.getKeyCode();

    }
    public void keyTyped(KeyEvent ke)
    {

    }
    public void keyReleased(KeyEvent ke)
    {
        if(ch==ke.VK_LEFT)
           a=1;

        if(ch==ke.VK_RIGHT)
           a=2;

        if(ch==ke.VK_UP)
           a=3;

        if(ch==ke.VK_DOWN)
           a=4;

        repaint();
    }

    public void paint(Graphics g)
    {
        super.paint(g);

        if(a==1)
        g.drawLine(200,100,300,200);

        if(a==2)
        g.drawOval(200,100,200,100);

        if(a==3)
        g.drawRoundRect(200,100,50,50,20,20);

        if(a==4)
        g.drawRect(300,200,50,50);
    }

    public static void main(String arge[])
    {
        keydraw f=new keydraw();
        f.setTitle("Press direction keys");
        f.setVisible(true);
        f.setSize(400,400);
    }
}