Draw triangle in console

How can I draw a triangle or other figures in the console mode?

import java.awt.*;
import java.awt.geom.*;
import java.awt.image.*;
public class Test {
     public static void main(String args[]) {
          Polygon triangle = new Polygon();
          triangle.addPoint(0,25);
          triangle.addPoint(25,0);
          triangle.addPoint(50,25);
          Rectangle rect = triangle.getBounds();
          BufferedImage img = new BufferedImage(rect.width,rect.height,BufferedImage.TYPE_INT_RGB);
          Graphics2D g = img.createGraphics();
          g.setColor(Color.white);
          g.fill(rect);
          g.setColor(Color.black);
          g.fill(triangle);
          int x,y;
          for (y = 0;y < img.getHeight();y++) {
               for (x = 0;x < img.getWidth();x++) {
                    if (img.getRGB(x,y) == 0xffffffff) System.out.print(" ");
                    else System.out.print("X");
               System.out.println("");
}

Similar Messages

  • Drawing triangles in Applet

    hi Friends,
    I need to draw some triangles in sequence in an applet.I have drawn two triangles to start with,the code for which is:
    public class triangle extends Applet {
      public void paint (Graphics g)
        g.drawLine(50,50,25,100);
        g.drawLine(25,100,75,100);
        g.drawLine(50,50,75,100);
        g.drawLine(100,50,125,100);
        g.drawLine(75,100,100,50);
        g.drawLine(75,100,125,100);
    }But,I dont think this is the right way .. can you please tell me how can i use a method where I can send the 3 points and it returns me with a triangle and in the end i merge all those triangles.Please help me guys.
    Thanks
    Mick

    java.awt.Polygon

  • NEED HELP IN LABELLING A TRIANGLE _ VERTICES

    PLEASE HELP ______
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.text.NumberFormat;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.DefaultTableCellRenderer;
    import java.lang.*;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseMotionListener;
    import java.awt.FileDialog;
    import java.io.*;
    import java.awt.BorderLayout;
    import java.awt.Container;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseMotionListener;
    import javax.swing.JFrame;
    public class Geometry {
        CardLayout cards;
        JPanel panel;
        public Geometry() {
            cards = new CardLayout();
            panel = new JPanel(cards);
            addCards();
            JFrame f = new JFrame("Geometry");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.setJMenuBar(getMenuBar());
            f.getContentPane().add(panel);
            f.setSize(500,500);
            f.setLocation(0,0);
            f.setVisible(true);
            f.addMouseMotionListener(
            new MouseMotionListener() { //anonymous inner class
                //handle mouse drag event
                public void mouseMoved(MouseEvent e) {
                   System.out.println("Mouse  " + e.getX() +","  + e.getY());
                public void mouseDragged(MouseEvent e) {
                    System.out.println("Draggg: x=" + e.getX() + "; y=" + e.getY());
            //            public void mouseMoved(MouseEvent me) {
            //                System.out.println("Moving: x=" + me.getX() + "; y=" + me.getY());
            //        panel.addMouseMotionListener(
            //        new MouseMotionListener() { //anonymous inner class
            //            //handle mouse drag event
            //           public void mouseDragged(MouseEvent me) {
            //               setTitle("Dragging: x=" + me.getX() + "; y=" + me.getY());
            //            public void mouseMoved(MouseEvent me) {
            //                setTitle("Moving: x=" + me.getX() + "; y=" + me.getY());
        private void addCards() {
            // card one
            TriangleModel tri = new TriangleModel(175,100,175,250,325,250);
            TriangleView view  = new TriangleView(tri);
            JPanel panelOne = new JPanel(new BorderLayout());
            panelOne.add(view.getUIPanel(), "North");
            panelOne.add(view);
            panelOne.add(view.getTablePanel(), "South");
            panelOne.setName("Pythagoras's Theorem");
            panel.add("Pythagoras's Theorem", panelOne);
                  view.addMouseMotionListener(
            new MouseMotionListener() { //anonymous inner class
                //handle mouse drag event
                 public void mouseMoved(MouseEvent e) {
                    System.out.println("Mouse at " + e.getX() +","  + e.getY());
               public void mouseDragged(MouseEvent e) {
                   System.out.println("Dragging: x=" + e.getX() + "; y=" + e.getY());
            // card two
            TestModel trin = new TestModel(175,100,175,250,325,250);
            TestView viewn  = new TestView(trin);
            JPanel panelTwo = new JPanel(new BorderLayout());
            panelTwo.add(viewn.getUIPanel(), "North");
          // panelTwo.setBackground(Color.blue);
            panelTwo.setName("Similar Triangles");
            panelTwo.add(viewn);
            panelTwo.add(viewn.getTablePanel(), "South");
                  viewn.addMouseMotionListener(
            new MouseMotionListener() { //anonymous inner class
                //handle mouse drag event
                 public void mouseMoved(MouseEvent e) {
                    System.out.println("Mouse at " + e.getX() +","  + e.getY());
               public void mouseDragged(MouseEvent e) {
                   System.out.println("Dragging: x=" + e.getX() + "; y=" + e.getY());
            panel.add("Similar Triangles", panelTwo);
            JPanel panelThree = new JPanel();
            panelThree.setBackground(Color.white);
            panelThree.setName("Circle Theorem1");
            panel.add("Circle Theorem1", panelThree);
        private JMenuBar getMenuBar() {
            JMenu File = new JMenu("File");
            JSeparator separator1 = new JSeparator();
            JMenuItem Open = new JMenuItem("Open");
    //         Open.addActionListener(new java.awt.event.ActionListener() {
    //            public void actionPerformed(java.awt.event.ActionEvent evt) {
    //                openActionPerformed(evt);
            JMenuItem Save = new JMenuItem("Save");
            JMenuItem Print = new JMenuItem("Print");
            JMenuItem Exit = new JMenuItem("Exit");
            Exit.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    ExitActionPerformed(evt);
            JMenu theorem = new JMenu("Theorem");
            ActionListener l = new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    JMenuItem item = (JMenuItem)e.getSource();
                    String name = item.getActionCommand();
                    cards.show(panel, name);
            Component[] c = panel.getComponents();
            for(int j = 0; j < panel.getComponentCount(); j++) {
                String name = c[j].getName();
                JMenuItem item = new JMenuItem(name);
                item.setActionCommand(name);
                item.addActionListener(l);
                theorem.add(item);
            JMenuBar menuBar = new JMenuBar();
            JMenuBar menuBar1 = new JMenuBar();
            menuBar.add(File);
            File.add(Open);
            File.add(separator1);
            File.add(Save);
            File.add(Print);       
            File.add(Exit);
            menuBar.add(theorem);
            return menuBar;
    //    private void openActionPerformed(java.awt.event.ActionEvent evt) {
    //        FileDialog fileDialog = new FileDialog(this, "Open...", FileDialog.LOAD);
    //        fileDialog.show();
    //        if (fileDialog.getFile() == null)
    //            return;
    //        fileName = fileDialog.getDirectory() + File.separator + fileDialog.getFile();
    //        FileInputStream fis = null;
    //        String str = null;
    //        try {
    //            fis = new FileInputStream(fileName);
    //            int size = fis.available();
    //            byte[] bytes = new byte [size];
    //            fis.read(bytes);
    //            str = new String(bytes);
    //        } catch (IOException e) {
    //        } finally {
    //            try {
    //                fis.close();
    //            } catch (IOException e2) {
    //        if (str != null)
    //            textBox.setText(str);
        private void ExitActionPerformed(java.awt.event.ActionEvent evt) {
            // TODO add your handling code here:
            System.exit(0);
        public static void main(String[] args) {
            new Geometry();
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.text.NumberFormat;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.DefaultTableCellRenderer;
    public class Triangle
    public Triangle()
    TriangleModel tri = new TriangleModel(175,100,175,250,325,250);
    TriangleView view = new TriangleView(tri);
    JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.getContentPane().add(view.getUIPanel(), "North");
    f.getContentPane().add(view);
    f.getContentPane().add(view.getTablePanel(), "South");
    f.setSize(500,500);
    f.setLocation(200,200);
    f.setVisible(true);
    import java.awt.Point;
    import java.awt.Rectangle;
    import java.awt.event.MouseEvent;
    import javax.swing.JTable;
    import javax.swing.event.MouseInputAdapter;
    * TriangleControl.java
    * Created on 06 February 2005, 01:19
    * @author  Rahindra Naidoo
    public class TriangleControl extends MouseInputAdapter
        TriangleView view;
        TriangleModel model;
        Point start;
        boolean dragging, altering;
        Rectangle lineLens;            // used for line selection
        public TriangleControl(TriangleView tv)
            view = tv;
            model = view.getModel();
            dragging = altering = false;
            lineLens = new Rectangle(0, 0, 6, 6);
        public void mousePressed(MouseEvent e)
            Point p = e.getPoint();
            lineLens.setLocation(p.x - 3, p.y - 3);
            // are we over a line
            if(model.isLineSelected(lineLens))
                start = p;
                altering = true;
            // or are we within the triangle
            else if(model.contains(p))
                start = p;
                dragging = true;
        public void mouseReleased(MouseEvent e)
            altering = false;
            dragging = false;
            view.getCentroidLabel().setText("centroid location: " +
                                             model.findCentroid());
            view.repaint();  // for the construction lines
        public void mouseDragged(MouseEvent e)
            Point p = e.getPoint();
            if(altering)
                int x = p.x - start.x;
                int y = p.y - start.y;
                model.moveSide(x, y, p);
                updateTable();
                view.repaint();
                start = p;
            else if(dragging)
                int x = p.x - start.x;
                int y = p.y - start.y;
                model.translate(x, y);
                view.repaint();
                start = p;
        private void updateTable()
            String[] lengths = model.getLengths();
            String[] squares = model.getSquares();
            String[] angles  = model.getAngles();
            JTable table = view.getTable();
            for(int j = 0; j < angles.length; j++)
                table.setValueAt(lengths[j], 1, j + 1);
                table.setValueAt(squares[j], 2, j + 1);
                table.setValueAt(angles[j],  3, j + 1);
            view.getCentroidLabel().setText("centroid location: " +
                                             model.findCentroid());
    * TriangleModel.java
    * Created on 06 February 2005, 01:18
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.text.NumberFormat;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.DefaultTableCellRenderer;
    * @author  Rahindra Naidoo
    public class TriangleModel                      //  (x1, y1)
    {                                         //      |\
        static final int SIDES = 3;         //      | \
        private int cx, cy;                  //      |  \
        Polygon triangle;                     //      |_ _\ (x3, y3)
        int selectedIndex;                   //  (x2, y2)
        NumberFormat nf;
        Line2D[] medians;
        Point2D centroid;
        public TriangleModel(int x1, int y1, int x2, int y2, int x3, int y3)
            int[] x = new int[] { x1, x2, x3 };
            int[] y = new int[] { y1, y2, y3 };
            triangle = new Polygon(x, y, SIDES);
            nf = NumberFormat.getNumberInstance();
            nf.setMaximumFractionDigits(1);
        public boolean contains(Point p)
            // Polygon.contains doesn't work well enough
            return (new Area(triangle)).contains(p);
        public boolean isLineSelected(Rectangle r)
            Line2D line = new Line2D.Double();
            for(int j = 0; j < SIDES; j++)
                int[] x = triangle.xpoints;
                int[] y = triangle.ypoints;
                int x1 = x[j];
                int y1 = y[j];
                int x2 = x[(j + 1) % SIDES];
                int y2 = y[(j + 1) % SIDES];
                line.setLine(x1, y1, x2, y2);
                if(line.intersects(r))
                    selectedIndex = j;
                    return true;
            selectedIndex = -1;
            return false;
         * Only works for right triangle with right angle at (x2, y2)
        public void moveSide(int dx, int dy, Point p)
            int[] x = triangle.xpoints;
            int[] y = triangle.ypoints;
            switch(selectedIndex)
                case 0:
                    x[0] += dx;
                    x[1] += dx;
                    break;
                case 1:
                    y[1] += dy;
                    y[2] += dy;
                    break;
                case 2:
                    double rise  = y[2] - y[0];
                    double run   = x[2] - x[0];
                    double slope = rise/run;
                    // rise / run == (y[2] - p.y) / (x[2] - p.x)
                    x[2] = p.x + (int)((y[2] - p.y) / slope);
                    // rise / run == (p.y - y[0]) / (p.x - x[0])
                    y[0] = p.y - (int)((p.x - x[0]) * slope);
        public void translate(int dx, int dy)
            triangle.translate(dx, dy);
        public Polygon getTriangle()
            return triangle;
        public String findCentroid()
            int[] x = triangle.xpoints;
            int[] y = triangle.ypoints;
            // construct the medians defined as the line from
            // any vertex to the midpoint of the opposite line
            medians = new Line2D[x.length];
            for(int j = 0; j < x.length; j++)
                int next = (j + 1) % x.length;
                int last = (j + 2) % x.length;
                Point2D vertex = new Point2D.Double(x[j], y[j]);
                // get midpoint of line opposite vertex
                double dx = ((double)x[last] - x[next])/2;
                double dy = ((double)y[last] - y[next])/2;
                Point2D oppLineCenter = new Point2D.Double(x[next] + dx,
                                                           y[next] + dy);
                medians[j] = new Line2D.Double(vertex, oppLineCenter);
            // centroid is located on any median 2/3 the way from the
            // vertex (P1) to the midpoint (P2) on the opposite side
            double[] lengths = getSideLengths();
            double dx = (medians[0].getX2() - medians[0].getX1())*2/3;
            double dy = (medians[0].getY2() - medians[0].getY1())*2/3;
            double px = medians[0].getX1() + dx;
            double py = medians[0].getY1() + dy;
            //System.out.println("px = " + nf.format(px) +
            //                 "\tpy = " + nf.format(py));
            centroid = new Point2D.Double(px, py);
            return "(" + nf.format(px) + ",  " + nf.format(py) + ")";
        public String[] getAngles()
            double[] lengths = getSideLengths();
            String[] vertices = new String[lengths.length];
            for(int j = 0; j < lengths.length; j++)
                int opp  = (j + 1) % lengths.length;
                int last = (j + 2) % lengths.length;
                double top = lengths[j] * lengths[j] +
                             lengths[last] * lengths[last] -
                             lengths[opp] * lengths[opp];
                double divisor = 2 * lengths[j] * lengths[last];
                double vertex = Math.acos(top / divisor);
                vertices[j] = nf.format(Math.toDegrees(vertex));
            return vertices;
        public String[] getLengths()
            double[] lengths = getSideLengths();
            String[] lengthStrs = new String[lengths.length];
            for(int j = 0; j < lengthStrs.length; j++)
                lengthStrs[j] = nf.format(lengths[j]);
            return lengthStrs;
        public String[] getSquares()
            double[] lengths = getSideLengths();
            String[] squareStrs = new String[lengths.length];
            for(int j = 0; j < squareStrs.length; j++)
                squareStrs[j] = nf.format(lengths[j] * lengths[j]);
            return squareStrs;
        private double[] getSideLengths()
            int[] x = triangle.xpoints;
            int[] y = triangle.ypoints;
            double[] lengths = new double[SIDES];
            for(int j = 0; j < SIDES; j++)
                int next = (j + 1) % SIDES;
                lengths[j] = Point.distance(x[j], y[j], x[next], y[next]);
            return lengths;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.text.NumberFormat;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.DefaultTableCellRenderer;
    * TriangleView.java
    * Created on 06 February 2005, 01:21
    public class TriangleView extends JPanel
        private TriangleModel model;
        private Polygon triangle;
        private JTable table;
        private JLabel centroidLabel;
        private boolean showConstruction;
        TriangleControl control;
        public TriangleView(TriangleModel model)
            this.model = model;
            triangle = model.getTriangle();
            showConstruction = false;
            control = new TriangleControl(this);
            addMouseListener(control);
            addMouseMotionListener(control);
        public void paintComponent(Graphics g)
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            g2.draw(triangle);
            if(model.medians == null)
                centroidLabel.setText("centroid location: " + model.findCentroid());
            // draw medians and centroid point
            if(showConstruction && !control.dragging)
                g2.setPaint(Color.red);
                for(int j = 0; j < 3; j++)
                    g2.draw(model.medians[j]);
                g2.setPaint(Color.blue);
                g2.fill(new Ellipse2D.Double(model.centroid.getX() - 2,
                                             model.centroid.getY() - 2, 4, 4));
        public TriangleModel getModel()
            return model;
        public JTable getTable()
            return table;
        public JLabel getCentroidLabel()
            return centroidLabel;
        public JPanel getUIPanel()
            JCheckBox showCon = new JCheckBox("show construction");
            showCon.addActionListener(new ActionListener()
                public void actionPerformed(ActionEvent e)
                    boolean state = ((JCheckBox)e.getSource()).isSelected();
                    showConstruction = state;
                    repaint();
            JPanel panel = new JPanel();
            panel.add(showCon);
            return panel;
        public JPanel getTablePanel()
            String[] headers = new String[] { "", "", "", "" };
            // row and column data labels
            String[] rowHeaders = {
                "sides", "lengths", "squares", "angles", "degrees"
            String[] sidesRow = { "vertical", "horizontal", "hypotenuse" };
            String[] anglesRow = { "hyp to ver", "ver to hor", "hor to hyp" };
            // collect data from model
            String[] angles  = model.getAngles();
            String[] lengths = model.getLengths();
            String[] squares = model.getSquares();
            String[][] allData = { sidesRow, lengths, squares, anglesRow, angles };
            int rows = 5;
            int cols = 4;
            Object[][] data = new Object[rows][cols];
            for(int row = 0; row < rows; row++)
                data[row][0] = rowHeaders[row];
                for(int col = 1; col < cols; col++)
                    data[row][col] = allData[row][col - 1];
            table = new JTable(data, headers)
                public boolean isCellEditable(int row, int col)
                    return false;
            DefaultTableCellRenderer renderer =
                (DefaultTableCellRenderer)table.getDefaultRenderer(String.class);
            renderer.setHorizontalAlignment(JLabel.CENTER);
            centroidLabel = new JLabel("centroid location:  ", JLabel.CENTER);
            Dimension d = centroidLabel.getPreferredSize();
            d.height = table.getRowHeight();
            centroidLabel.setPreferredSize(d);
            JPanel panel = new JPanel(new BorderLayout());
            panel.setBorder(BorderFactory.createTitledBorder("triangle data"));
            panel.add(table);
            panel.add(centroidLabel, "South");
            return panel;
    }PLEASE HELP ME TO LABEL THE TRIANGLE AND CHANGE THE VALUES OF THE JTABLE - to SHOW ASquare b Square and C square as well as a label on the bottom of the screen to show A^2 + B^2 = C^2 ...
    ThANKS

        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                    RenderingHints.VALUE_ANTIALIAS_ON);
            g2.drawPolygon(triangle);
            // label the triangle
            String[] lengths = model.getLengths();
            String[] squares = model.getSquares();
            String[] angles  = model.getAngles();
            int[] x = triangle.xpoints;
            int[] y = triangle.ypoints;
            for(int j = 0; j < x.length; j++) {
                Point2D vertex = new Point2D.Double(x[j], y[j]);
                int next = (j + 0) % x.length;
                int last = (j + 1) % x.length;
                double dx = ((double)x[last] - x[next])/2;
                double dy = ((double)y[last] - y[next])/2;
                Point2D center = new Point2D.Double(x[next] + dx, y[next] + dy);
                g2.drawString(angles[j],(int)vertex.getX(),(int)vertex.getY());
                g2.drawString(lengths[j],(int)center.getX(),(int)center.getY());
            g2.drawString(squares[0],100, getHeight());
            g2.drawString(" + "+squares[1],150, getHeight());
            g2.drawString(" = "+squares[2],200, getHeight());
            if(model.medians == null)
                centroidLabel.setText("centroid location: " + model.findCentroid());
            // draw medians and centroid point
            if(showConstruction && !control.dragging) {
                g2.setPaint(Color.red);
                for(int j = 0; j < 3; j++)
                    g2.draw(model.medians[j]);
                g2.setPaint(Color.blue);
                g2.fill(new Ellipse2D.Double(model.centroid.getX() - 2,
                        model.centroid.getY() - 2, 4, 4));
        }

  • Calculating and displaying the Length of the side of a triangle

    Hi everyone. I am currently working on Dragging and Stretching a triangle on screen. Ive got it working to a certain extent but the only problem is that whenever I go to the point from which i have to drag my triangle i.e. the Left hand Corner of the BAse at exactly 300,300 it redraws a new triangle below the existing one and then when i stretch it from the top and the right it leaves a trail of triangles everytime. But when i resize my window it clears the trail only to start agian when I drag or stretch it...
    All my code for wahtever I have done is displayed below. I would appreciate all the help that any one can offer.
    Secondly , as I stretch my triangle I would like to calculate My Length of the hypotenuse and the other 2 sides as they change and display it in System.out.println for now...
    PLEASE HELP
    the code is
    This is my Main Form --- Interactive Geometry.java
    import java.awt.BorderLayout;
    import java.awt.Container;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseMotionListener;
    import javax.swing.JFrame;
    * InteractiveGeometry.java
    * Created on 30 November 2004, 20:29
    * @author  Kripa Bhojwani
    public class InteractiveGeometry extends javax.swing.JFrame {
        public EastPanel eastpanel;
        public Container container;
        public GeomPanel gp;
        public boolean pressed = false;
        public boolean pressT = false;
        public boolean pressR = false;
        /** Creates new form InteractiveGeometry */
        public InteractiveGeometry() {
            initComponents();
            eastpanel = new EastPanel();
            container = new Container();
            Model model = new Model(300,150,450,300,300,300);
            gp = new GeomPanel(model);
            container = getContentPane();
            container.add(eastpanel,BorderLayout.EAST);
            container.add(gp,BorderLayout.CENTER);
            setSize(1400,9950);
            gp.addMouseMotionListener(
            new MouseMotionListener() { //anonymous inner class
                //handle mouse drag event
                public void mouseDragged(MouseEvent me) {
                    setTitle("Dragging: x=" + me.getX() + "; y=" + me.getY());
                public void mouseMoved(MouseEvent me) {
                    setTitle("Moving: x=" + me.getX() + "; y=" + me.getY());
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        private void initComponents() {
            jMenuBar2 = new javax.swing.JMenuBar();
            jMenu2 = new javax.swing.JMenu();
            jMenuItem1 = new javax.swing.JMenuItem();
            jMenu1 = new javax.swing.JMenu();
            jMenuItem2 = new javax.swing.JMenuItem();
            addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
                public void mouseDragged(java.awt.event.MouseEvent evt) {
                    formMouseDragged(evt);
                public void mouseMoved(java.awt.event.MouseEvent evt) {
                    formMouseMoved(evt);
            addWindowListener(new java.awt.event.WindowAdapter() {
                public void windowClosing(java.awt.event.WindowEvent evt) {
                    exitForm(evt);
            jMenuBar2.setBackground(new java.awt.Color(0, 102, 204));
            jMenu2.setBackground(new java.awt.Color(222, 222, 238));
            jMenu2.setText("File");
            jMenu2.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jMenu2ActionPerformed(evt);
            jMenuItem1.setBackground(new java.awt.Color(204, 255, 255));
            jMenuItem1.setText("Exit");
            jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jMenuItem1ActionPerformed(evt);
            jMenu2.add(jMenuItem1);
            jMenuBar2.add(jMenu2);
            jMenu1.setBackground(new java.awt.Color(199, 215, 255));
            jMenu1.setText("Theorem ");
            jMenuItem2.setText("Pythagoras Theorem");
            jMenuItem2.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jMenuItem2ActionPerformed(evt);
            jMenu1.add(jMenuItem2);
            jMenuBar2.add(jMenu1);
            setJMenuBar(jMenuBar2);
            pack();
        private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {
            // TODO add your handling code here:
        private void formMouseDragged(java.awt.event.MouseEvent evt) {
            // TODO add your handling code here:
        private void formMouseMoved(java.awt.event.MouseEvent evt) {
            // TODO add your handling code here:
        public void mouseDragged(MouseEvent me) {
            setTitle("Dragging: x=" + me.getX() + "; y=" + me.getY());
        private void jMenu2ActionPerformed(java.awt.event.ActionEvent evt) {
            // TODO add your handling code here:
        private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {
            // TODO add your handling code here:
            System.exit(0);
        /** Exit the Application */
        private void exitForm(java.awt.event.WindowEvent evt) {
            System.exit(0);
         * @param args the command line arguments
        public static void main(String args[]) {
            InteractiveGeometry ig = new InteractiveGeometry();
            ig.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            ig.show();
            // new InteractiveGeometry().show();
        // Variables declaration - do not modify
        private javax.swing.JMenu jMenu1;
        private javax.swing.JMenu jMenu2;
        private javax.swing.JMenuBar jMenuBar2;
        private javax.swing.JMenuItem jMenuItem1;
        private javax.swing.JMenuItem jMenuItem2;
        // End of variables declaration
    This is my Panel -- GeomPanel.java which draws everything -- /*
    * GeomPanel.java
    * Created on 30 November 2004, 20:29
    import java.awt.*;
    import java.util.*;
    import javax.swing.*;
    import java.awt.Graphics.*;
    import java.awt.event.MouseListener;
    import java.awt.event.MouseMotionListener;
    import java.awt.geom.Line2D;
    import java.awt.geom.Point2D;
    import java.awt.event.*;
    import java.awt.Graphics2D;
    import java.awt.geom.Ellipse2D;
    import javax.swing.event.TableModelListener;
    import javax.swing.JScrollPane;
    import javax.swing.event.*;
    import java.awt.Dimension;
    import java.awt.Container.*;
    * @author Kripa Bhojwani
    public class GeomPanel extends javax.swing.JPanel implements Observer, MouseMotionListener, MouseListener {
    private Model model;
    private boolean pressed = false;
    private boolean pressT = false;
    private boolean pressR = false;
    /** Creates new form GeomPanel */
    public GeomPanel(Model model) {
    this.model = model;
    model.addObserver(this);
    addMouseListener(this);
    addMouseMotionListener(this);
    initComponents();
    setBackground(Color.getHSBColor(6,600,660));
    public void paintComponent(Graphics gfx) {
    Graphics2D g = (Graphics2D) gfx;
    Point tc = model.getTop();
    Point lc = model.getLeft();
    Point rc = model.getRight();
    Point2D.Double p1 = new Point2D.Double(tc.getX(),tc.getY());
    Point2D.Double p2 = new Point2D.Double(lc.getX(),lc.getY());
    Point2D.Double p3 = new Point2D.Double(rc.getX(),rc.getY());
    Line2D.Double line = new Line2D.Double(p1, p2);
    Line2D.Double line1 = new Line2D.Double(p2, p3);
    Line2D.Double line2 = new Line2D.Double(p1, p3);
    g.setColor(Color.BLACK);
    g.draw(line);
    g.draw(line2);
    g.draw(line1);
    /** This method is called from within the constructor to
    * initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is
    * always regenerated by the Form Editor.
    private void initComponents() {
    setLayout(new java.awt.BorderLayout());
    addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
    public void mouseDragged(java.awt.event.MouseEvent evt) {
    formMouseDragged(evt);
    private void formMouseDragged(java.awt.event.MouseEvent evt) {
    // TODO add your handling code here:
    public void mouseClicked(MouseEvent e) {
    public void mouseDragged(MouseEvent e) {
    System.out.println("Dragged at "+ e.getX()+ "," + e.getY());
    if(pressed == true){
    model.setLeft(e.getX() , e.getY());
    else if(pressT == true){
    model.setTop(e.getX() , e.getY());
    else if (pressR == true){
    model.setRight(e.getX(), e.getY());
    else{
    pressed = false;
    pressT= false;
    pressR=false;
    repaint();
    public void mouseEntered(MouseEvent e) {
    public void mouseExited(MouseEvent e) {
    public void mouseMoved(MouseEvent e) {
    System.out.println("Mouse at " + e.getX() +"," + e.getY());
    public void mousePressed(MouseEvent e) {
    if (model.getLeft().getX()== e.getX() && model.getLeft().getY()== e.getY()){
    pressed = true;
    else if (model.getTop().getX()==e.getX() && model.getTop().getY()==e.getY()){
    pressT = true;
    else if(model.getRight().getX() == e.getX() && model.getRight().getY()==e.getY()){
    pressR = true;
    // else if(model.getCircle().getX() == e.getX() && model.getCircle().getY() == e.getY()){
    // inoval = true;
    else {
    pressed =false;
    pressT = false;
    pressR = false;
    } repaint();
    public void mouseReleased(MouseEvent e) {
    if(pressed == true){
    model.setLeft(e.getX(),e.getY());
    else if (pressT ==true ){
    model.setTop(e.getX(), e.getY());
    else if(pressR ==true){
    model.setRight(e.getX(),e.getY());
    else {
    pressed = false;
    pressT = false;
    pressR = false;
    repaint();
    public void update(Observable o, Object arg) {
    repaint();
    // Variables declaration - do not modify
    // End of variables declaration
    This is my Model class called Model.java which Holds all teh data for my triangle
    import java.awt.Point;
    import java.util.Observable;
    * Model.java
    * Created on 05 December 2004, 14:11
    * @author  Kripa Bhojwani
    public class Model extends Observable{
        private int  x1,x2,x3, y1,y2,y3;
        private int _transx;
        private int _transy;
        private int _c;
        private int _d;
        /** Creates a new instance of Model */
        public Model(int x1, int y1, int x2, int y2, int x3, int y3) {
            this.x1 = x1;
            this.y1 = y1;
            this.x2 = x2;
            this.y2 = y2;
            this.x3 = x3;
            this.y3 = y3;
            setChanged();
            notifyObservers();
        public void setTop(int x1, int y1){
            //this.x1 =x1;
            this.y1= y1;
            setChanged();
            notifyObservers();
        public void setRight(int x2, int y2){
            this.x2 = x2;
            // this.y2 =y2;
            setChanged();
            notifyObservers();
        public void setLeft(int x3, int y3){
            _transx = x3 - this.x3;
            _transy = y3 - this.y3;
            this.x3 += _transx;
            this.y3 += _transy;
            this.y2 += _transy;
            this.x2 += _transx;
            this.x1 += _transx;
            this.y1 += _transy;
            setChanged();
            notifyObservers();
        public Point getTop(){
            Point p = new Point(x1,y1);
            return p;
        public Point getRight(){
            Point p1 = new Point(x2,y2);
            return p1;
        public Point getLeft(){
            Point p3 = new Point(x3,y3);
            return p3;
        public void update() {
            setChanged();
            notifyObservers();
    This is my TableModel which is the JTable to display all the Cordinates and Lengths and other Measurements like angles etc./*
    * TableModel.java
    * Created on 03 December 2004, 15:08
    import javax.swing.JTable;
    import javax.swing.JScrollPane;
    import javax.swing.JPanel;
    import javax.swing.JFrame;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.Observer;
    import javax.swing.event.TableModelEvent;
    import javax.swing.table.AbstractTableModel;
    * @author Kripa Bhojwani
    public class TableModel extends AbstractTableModel implements Observer{
    private String[] columnNames = {"Point", "X Coordinate", "Y Coordinate"};
    private Object[][] data = {};
    private int rowCount;
    private int columnCount;
    /** Creates a new instance of TableModel */
    public TableModel() {
    rowCount = 0;
    columnCount = 3;
    public int getColumnCount() {
    return columnCount;
    public int getRowCount() {
    return rowCount;
    public String getColumnName(int col) {
    return columnNames[col];
    public void setColumnName (String[] name){
    columnNames = name;
    public void setValueAt(Object obj, int row, int col) {
    data[row][col] = obj;
    fireTableCellUpdated(row, col);
    TableModelEvent tme = new TableModelEvent(this);
    fireTableChanged(tme);
    public Object getValueAt(int row, int col) {
    return data[row][col];
    public void update(java.util.Observable o, Object arg) {
    This is the Panel on the east side of My Main application form which will display all the measurements and Cordinates ---EastPanel.java
    import java.awt.BorderLayout;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.event.TableModelListener;
    import java.awt.Dimension;
    * EastPanel.java
    * Created on 04 December 2004, 23:07
    * @author  Kripa Bhojwani
    public class EastPanel extends javax.swing.JPanel implements TableModelListener{
        private TableModel tm;
        /** Creates new form EastPanel */
        public EastPanel() {   
          initComponents();
            tm = new TableModel();
            JTable table1 = new JTable(tm);
            table1.setPreferredScrollableViewportSize(new Dimension(250,264));
            table1.getModel().addTableModelListener(this);
            JScrollPane sp = new JScrollPane(table1);
            add(sp,BorderLayout.EAST);
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        private void initComponents() {
            setLayout(new java.awt.BorderLayout());
        public void tableChanged(javax.swing.event.TableModelEvent e) {
        // Variables declaration - do not modify
        // End of variables declaration
    }                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    

    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.text.NumberFormat;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.DefaultTableCellRenderer;
    public class G
    public G()
    TriangleModel tri = new
    ri = new TriangleModel(175,100,175,250,325,250);
    TriangleView view = new TriangleView(tri);
    JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.getContentPane().add(view.getUIPanel(),
    Panel(), "North");
    f.getContentPane().add(view);
    f.getContentPane().add(view.getTablePanel(),
    Panel(), "South");
    f.setSize(500,500);
    f.setLocation(200,200);
    f.setVisible(true);
    public static void main(String[] args)
    new G();
    class TriangleModel // (x1,
    y1)
    {                                         //      |\
    static final int SIDES = 3; // | \
    private int cx, cy; // |
    | \
    Polygon triangle; // |_
    |_ _\ (x3, y3)
    int selectedIndex; // (x2,
    (x2, y2)
    NumberFormat nf;
    Line2D[] medians;
    Point2D centroid;
    public TriangleModel(int x1, int y1, int x2, int
    int y2, int x3, int y3)
    int[] x = new int[] { x1, x2, x3 };
    int[] y = new int[] { y1, y2, y3 };
    triangle = new Polygon(x, y, SIDES);
    nf = NumberFormat.getNumberInstance();
    nf.setMaximumFractionDigits(1);
    public boolean contains(Point p)
    // Polygon.contains doesn't work well enough
    return (new Area(triangle)).contains(p);
    public boolean isLineSelected(Rectangle r)
    Line2D line = new Line2D.Double();
    for(int j = 0; j < SIDES; j++)
    int[] x = triangle.xpoints;
    int[] y = triangle.ypoints;
    int x1 = x[j];
    int y1 = y[j];
    int x2 = x[(j + 1) % SIDES];
    int y2 = y[(j + 1) % SIDES];
    line.setLine(x1, y1, x2, y2);
    if(line.intersects(r))
    selectedIndex = j;
    return true;
    selectedIndex = -1;
    return false;
    * Only works for right triangle with right angle
    angle at (x2, y2)
    public void moveSide(int dx, int dy, Point p)
    int[] x = triangle.xpoints;
    int[] y = triangle.ypoints;
    switch(selectedIndex)
    case 0:
    x[0] += dx;
    x[1] += dx;
    break;
    case 1:
    y[1] += dy;
    y[2] += dy;
    break;
    case 2:
    double rise = y[2] - y[0];
    double run = x[2] - x[0];
    double slope = rise/run;
    // rise / run == (y[2] - p.y) / (x[2]
    ] - p.y) / (x[2] - p.x)
    x[2] = p.x + (int)((y[2] - p.y) /
    )((y[2] - p.y) / slope);
    // rise / run == (p.y - y[0]) / (p.x
    y - y[0]) / (p.x - x[0])
    y[0] = p.y - (int)((p.x - x[0]) *
    )((p.x - x[0]) * slope);
    public void translate(int dx, int dy)
    triangle.translate(dx, dy);
    public Polygon getTriangle()
    return triangle;
    public String findCentroid()
    int[] x = triangle.xpoints;
    int[] y = triangle.ypoints;
    // construct the medians defined as the line
    the line from
    // any vertex to the midpoint of the opposite
    opposite line
    medians = new Line2D[x.length];
    for(int j = 0; j < x.length; j++)
    int next = (j + 1) % x.length;
    int last = (j + 2) % x.length;
    Point2D vertex = new Point2D.Double(x[j],
    Double(x[j], y[j]);
    // get midpoint of line opposite vertex
    double dx = ((double)x[last] -
    le)x[last] - x[next])/2;
    double dy = ((double)y[last] -
    le)y[last] - y[next])/2;
    Point2D oppLineCenter = new
    Center = new Point2D.Double(x[next] + dx,
    y[next]
    y[next] + dy);
    medians[j] = new Line2D.Double(vertex,
    uble(vertex, oppLineCenter);
    // centroid is located on any median 2/3 the
    2/3 the way from the
    // vertex (P1) to the midpoint (P2) on the
    ) on the opposite side
    double[] lengths = getSideLengths();
    double dx = (medians[0].getX2() -
    etX2() - medians[0].getX1())*2/3;
    double dy = (medians[0].getY2() -
    etY2() - medians[0].getY1())*2/3;
    double px = medians[0].getX1() + dx;
    double py = medians[0].getY1() + dy;
    //System.out.println("px = " + nf.format(px)
    rmat(px) +
    // "\tpy = " +
    py = " + nf.format(py));
    centroid = new Point2D.Double(px, py);
    return "(" + nf.format(px) + ", " +
    ", " + nf.format(py) + ")";
    public String[] getAngles()
    double[] lengths = getSideLengths();
    String[] vertices = new
    es = new String[lengths.length];
    for(int j = 0; j < lengths.length; j++)
    int opp = (j + 1) % lengths.length;
    int last = (j + 2) % lengths.length;
    double top = lengths[j] * lengths[j] +
    lengths[last] *
    lengths[last] * lengths[last] -
    lengths[opp] *
    lengths[opp] * lengths[opp];
    double divisor = 2 * lengths[j] *
    lengths[j] * lengths[last];
    double vertex = Math.acos(top /
    h.acos(top / divisor);
    vertices[j] =
    ertices[j] = nf.format(Math.toDegrees(vertex));
    return vertices;
    public String[] getLengths()
    double[] lengths = getSideLengths();
    String[] lengthStrs = new
    rs = new String[lengths.length];
    for(int j = 0; j < lengthStrs.length; j++)
    lengthStrs[j] = nf.format(lengths[j]);
    return lengthStrs;
    public String[] getSquares()
    double[] lengths = getSideLengths();
    String[] squareStrs = new
    rs = new String[lengths.length];
    for(int j = 0; j < squareStrs.length; j++)
    squareStrs[j] = nf.format(lengths[j] *
    lengths[j] * lengths[j]);
    return squareStrs;
    private double[] getSideLengths()
    int[] x = triangle.xpoints;
    int[] y = triangle.ypoints;
    double[] lengths = new double[SIDES];
    for(int j = 0; j < SIDES; j++)
    int next = (j + 1) % SIDES;
    lengths[j] = Point.distance(x[j], y[j],
    (x[j], y[j], x[next], y[next]);
    return lengths;
    class TriangleView extends JPanel
    private TriangleModel model;
    private Polygon triangle;
    private JTable table;
    private JLabel centroidLabel;
    private boolean showConstruction;
    TriangleControl control;
    public TriangleView(TriangleModel model)
    this.model = model;
    triangle = model.getTriangle();
    showConstruction = false;
    control = new TriangleControl(this);
    addMouseListener(control);
    addMouseMotionListener(control);
    public void paintComponent(Graphics g)
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D)g;
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
    RenderingHints.VALUE_ANTIALIAS_ON);
    g2.draw(triangle);
    if(model.medians == null)
    centroidLabel.setText("centroid location:
    id location: " + model.findCentroid());
    // draw medians and centroid point
    if(showConstruction && !control.dragging)
    g2.setPaint(Color.red);
    for(int j = 0; j < 3; j++)
    g2.draw(model.medians[j]);
    g2.setPaint(Color.blue);
    g2.fill(new
    g2.fill(new Ellipse2D.Double(model.centroid.getX() -
    2,
    model.centroid.getY()
    model.centroid.getY() - 2, 4, 4));
    public TriangleModel getModel()
    return model;
    public JTable getTable()
    return table;
    public JLabel getCentroidLabel()
    return centroidLabel;
    public JPanel getUIPanel()
    JCheckBox showCon = new JCheckBox("show
    ox("show construction");
    showCon.addActionListener(new
    ener(new ActionListener()
    public void actionPerformed(ActionEvent
    (ActionEvent e)
    boolean state =
    boolean state =
    ((JCheckBox)e.getSource()).isSelected();
    showConstruction = state;
    repaint();
    JPanel panel = new JPanel();
    panel.add(showCon);
    return panel;
    public JPanel getTablePanel()
    String[] headers = new String[] { "", "", "",
    // row and column data labels
    String[] rowHeaders = {
    "sides", "lengths", "squares", "angles",
    ", "angles", "degrees"
    String[] sidesRow = { "vertical",
    rtical", "horizontal", "hypotenuse" };
    String[] anglesRow = { "hyp to ver", "ver to
    "ver to hor", "hor to hyp" };
    // collect data from model
    String[] angles = model.getAngles();
    String[] lengths = model.getLengths();
    String[] squares = model.getSquares();
    String[][] allData = { sidesRow, lengths,
    lengths, squares, anglesRow, angles };
    int rows = 5;
    int cols = 4;
    Object[][] data = new Object[rows][cols];
    for(int row = 0; row < rows; row++)
    data[row][0] = rowHeaders[row];
    for(int col = 1; col < cols; col++)
    data[row][col] = allData[row][col -
    lData[row][col - 1];
    table = new JTable(data, headers)
    public boolean isCellEditable(int row,
    ble(int row, int col)
    return false;
    DefaultTableCellRenderer renderer =
    (DefaultTableCellRenderer)table.getDefaultRenderer(St
    ring.class);
    renderer.setHorizontalAlignment(JLabel.CENTER);
    centroidLabel = new JLabel("centroid
    centroid location: ", JLabel.CENTER);
    Dimension d =
    sion d = centroidLabel.getPreferredSize();
    d.height = table.getRowHeight();
    centroidLabel.setPreferredSize(d);
    JPanel panel = new JPanel(new
    anel(new BorderLayout());
    panel.setBorder(BorderFactory.createTitledBorder("tri
    angle data"));
    panel.add(table);
    panel.add(centroidLabel, "South");
    return panel;
    class TriangleControl extends MouseInputAdapter
    TriangleView view;
    TriangleModel model;
    Point start;
    boolean dragging, altering;
    Rectangle lineLens; // used for line
    line selection
    public TriangleControl(TriangleView tv)
    view = tv;
    model = view.getModel();
    dragging = altering = false;
    lineLens = new Rectangle(0, 0, 6, 6);
    public void mousePressed(MouseEvent e)
    Point p = e.getPoint();
    lineLens.setLocation(p.x - 3, p.y - 3);
    // are we over a line
    if(model.isLineSelected(lineLens))
    start = p;
    altering = true;
    // or are we within the triangle
    else if(model.contains(p))
    start = p;
    dragging = true;
    public void mouseReleased(MouseEvent e)
    altering = false;
    dragging = false;
    view.getCentroidLabel().setText("centroid
    centroid location: " +
    model.findCentroid());
    view.repaint(); // for the construction
    truction lines
    public void mouseDragged(MouseEvent e)
    Point p = e.getPoint();
    if(altering)
    int x = p.x - start.x;
    int y = p.y - start.y;
    model.moveSide(x, y, p);
    updateTable();
    view.repaint();
    start = p;
    else if(dragging)
    int x = p.x - start.x;
    int y = p.y - start.y;
    model.translate(x, y);
    view.repaint();
    start = p;
    private void updateTable()
    String[] lengths = model.getLengths();
    String[] squares = model.getSquares();
    String[] angles = model.getAngles();
    JTable table = view.getTable();
    for(int j = 0; j < angles.length; j++)
    table.setValueAt(lengths[j], 1, j + 1);
    table.setValueAt(squares[j], 2, j + 1);
    table.setValueAt(angles[j], 4, j + 1);
    view.getCentroidLabel().setText("centroid
    centroid location: " +
    model.findCentroid());
    Hey sorry mate.. ive got a nother problem.
    I need to add loads of theorems to this tool. so i need a JMenu Bar called File with all the normal things. then another Menu called Theorems where i can have a list of JMenuItems with the theorem names --- Like when they click on Pythagoras Theorem it opens up all the triangle and the traingle data that u helped me with.
    The thing is im using netbeans and in netbeans i can do it coz its there and all you got to do is put the components together.
    Please Help
    Thanks...
    Sharan

  • URGENT HELP REQUIRED _ Creating Labels for Triangle

    Hi everyone... the code below is my application - Pythagoras Theorem.. or rather displaying it.. But i have not been able to get the Vertex of the triangle Labelled as A B C... I need to do that and change the Triangle Table data to A B C insted of Horizontal Vertical and Hypotenuise and as the triangle is stretched on screen A B And C keep moving as well ...
    Besides i need to Show this in the tabel
    - Values of A ^ 2 , B^2 and C ^2 as welll as a row showing A^2+B^2 = C^2
    the code is as follows..
    This is the main class called Geometry
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.text.NumberFormat;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.DefaultTableCellRenderer;
    import java.lang.*;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseMotionListener;
    import java.awt.FileDialog;
    import java.io.*;
    import java.awt.BorderLayout;
    import java.awt.Container;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseMotionListener;
    import javax.swing.JFrame;
    public class Geometry {
        CardLayout cards;
        JPanel panel;
        public Geometry() {
            cards = new CardLayout();
            panel = new JPanel(cards);
            addCards();
            JFrame f = new JFrame("Geometry");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.setJMenuBar(getMenuBar());
            f.getContentPane().add(panel);
            f.setSize(500,500);
            f.setLocation(0,0);
            f.setVisible(true);
            f.addMouseMotionListener(
            new MouseMotionListener() { //anonymous inner class
                //handle mouse drag event
                public void mouseMoved(MouseEvent e) {
                   System.out.println("Mouse  " + e.getX() +","  + e.getY());
                public void mouseDragged(MouseEvent e) {
                    System.out.println("Draggg: x=" + e.getX() + "; y=" + e.getY());
            //            public void mouseMoved(MouseEvent me) {
            //                System.out.println("Moving: x=" + me.getX() + "; y=" + me.getY());
            //        panel.addMouseMotionListener(
            //        new MouseMotionListener() { //anonymous inner class
            //            //handle mouse drag event
            //           public void mouseDragged(MouseEvent me) {
            //               setTitle("Dragging: x=" + me.getX() + "; y=" + me.getY());
            //            public void mouseMoved(MouseEvent me) {
            //                setTitle("Moving: x=" + me.getX() + "; y=" + me.getY());
        private void addCards() {
            // card one
            TriangleModel tri = new TriangleModel(175,100,175,250,325,250);
            TriangleView view  = new TriangleView(tri);
            JPanel panelOne = new JPanel(new BorderLayout());
            panelOne.add(view.getUIPanel(), "North");
            panelOne.add(view);
            panelOne.add(view.getTablePanel(), "South");
            panelOne.setName("Pythagoras's Theorem");
            panel.add("Pythagoras's Theorem", panelOne);
                  view.addMouseMotionListener(
            new MouseMotionListener() { //anonymous inner class
                //handle mouse drag event
                 public void mouseMoved(MouseEvent e) {
                    System.out.println("Mouse at " + e.getX() +","  + e.getY());
               public void mouseDragged(MouseEvent e) {
                   System.out.println("Dragging: x=" + e.getX() + "; y=" + e.getY());
            // card two
            TestModel trin = new TestModel(175,100,175,250,325,250);
            TestView viewn  = new TestView(trin);
            JPanel panelTwo = new JPanel(new BorderLayout());
            panelTwo.add(viewn.getUIPanel(), "North");
          // panelTwo.setBackground(Color.blue);
            panelTwo.setName("Similar Triangles");
            panelTwo.add(viewn);
            panelTwo.add(viewn.getTablePanel(), "South");
                  viewn.addMouseMotionListener(
            new MouseMotionListener() { //anonymous inner class
                //handle mouse drag event
                 public void mouseMoved(MouseEvent e) {
                    System.out.println("Mouse at " + e.getX() +","  + e.getY());
               public void mouseDragged(MouseEvent e) {
                   System.out.println("Dragging: x=" + e.getX() + "; y=" + e.getY());
            panel.add("Similar Triangles", panelTwo);
            JPanel panelThree = new JPanel();
            panelThree.setBackground(Color.white);
            panelThree.setName("Circle Theorem1");
            panel.add("Circle Theorem1", panelThree);
        private JMenuBar getMenuBar() {
            JMenu File = new JMenu("File");
            JSeparator separator1 = new JSeparator();
            JMenuItem Open = new JMenuItem("Open");
    //         Open.addActionListener(new java.awt.event.ActionListener() {
    //            public void actionPerformed(java.awt.event.ActionEvent evt) {
    //                openActionPerformed(evt);
            JMenuItem Save = new JMenuItem("Save");
            JMenuItem Print = new JMenuItem("Print");
            JMenuItem Exit = new JMenuItem("Exit");
            Exit.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    ExitActionPerformed(evt);
            JMenu theorem = new JMenu("Theorem");
            ActionListener l = new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    JMenuItem item = (JMenuItem)e.getSource();
                    String name = item.getActionCommand();
                    cards.show(panel, name);
            Component[] c = panel.getComponents();
            for(int j = 0; j < panel.getComponentCount(); j++) {
                String name = c[j].getName();
                JMenuItem item = new JMenuItem(name);
                item.setActionCommand(name);
                item.addActionListener(l);
                theorem.add(item);
            JMenuBar menuBar = new JMenuBar();
            JMenuBar menuBar1 = new JMenuBar();
            menuBar.add(File);
            File.add(Open);
            File.add(separator1);
            File.add(Save);
            File.add(Print);       
            File.add(Exit);
            menuBar.add(theorem);
            return menuBar;
    //    private void openActionPerformed(java.awt.event.ActionEvent evt) {
    //        FileDialog fileDialog = new FileDialog(this, "Open...", FileDialog.LOAD);
    //        fileDialog.show();
    //        if (fileDialog.getFile() == null)
    //            return;
    //        fileName = fileDialog.getDirectory() + File.separator + fileDialog.getFile();
    //        FileInputStream fis = null;
    //        String str = null;
    //        try {
    //            fis = new FileInputStream(fileName);
    //            int size = fis.available();
    //            byte[] bytes = new byte [size];
    //            fis.read(bytes);
    //            str = new String(bytes);
    //        } catch (IOException e) {
    //        } finally {
    //            try {
    //                fis.close();
    //            } catch (IOException e2) {
    //        if (str != null)
    //            textBox.setText(str);
        private void ExitActionPerformed(java.awt.event.ActionEvent evt) {
            // TODO add your handling code here:
            System.exit(0);
        public static void main(String[] args) {
            new Geometry();
    }import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.text.NumberFormat;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.DefaultTableCellRenderer;
    public class Triangle
    public Triangle()
    TriangleModel tri = new TriangleModel(175,100,175,250,325,250);
    TriangleView view = new TriangleView(tri);
    JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.getContentPane().add(view.getUIPanel(), "North");
    f.getContentPane().add(view);
    f.getContentPane().add(view.getTablePanel(), "South");
    f.setSize(500,500);
    f.setLocation(200,200);
    f.setVisible(true);
    import java.awt.Point;
    import java.awt.Rectangle;
    import java.awt.event.MouseEvent;
    import javax.swing.JTable;
    import javax.swing.event.MouseInputAdapter;
    * TriangleControl.java
    * Created on 06 February 2005, 01:19
    * @author  Rahindra Naidoo
    public class TriangleControl extends MouseInputAdapter
        TriangleView view;
        TriangleModel model;
        Point start;
        boolean dragging, altering;
        Rectangle lineLens;            // used for line selection
        public TriangleControl(TriangleView tv)
            view = tv;
            model = view.getModel();
            dragging = altering = false;
            lineLens = new Rectangle(0, 0, 6, 6);
        public void mousePressed(MouseEvent e)
            Point p = e.getPoint();
            lineLens.setLocation(p.x - 3, p.y - 3);
            // are we over a line
            if(model.isLineSelected(lineLens))
                start = p;
                altering = true;
            // or are we within the triangle
            else if(model.contains(p))
                start = p;
                dragging = true;
        public void mouseReleased(MouseEvent e)
            altering = false;
            dragging = false;
            view.getCentroidLabel().setText("centroid location: " +
                                             model.findCentroid());
            view.repaint();  // for the construction lines
        public void mouseDragged(MouseEvent e)
            Point p = e.getPoint();
            if(altering)
                int x = p.x - start.x;
                int y = p.y - start.y;
                model.moveSide(x, y, p);
                updateTable();
                view.repaint();
                start = p;
            else if(dragging)
                int x = p.x - start.x;
                int y = p.y - start.y;
                model.translate(x, y);
                view.repaint();
                start = p;
        private void updateTable()
            String[] lengths = model.getLengths();
            String[] squares = model.getSquares();
            String[] angles  = model.getAngles();
            JTable table = view.getTable();
            for(int j = 0; j < angles.length; j++)
                table.setValueAt(lengths[j], 1, j + 1);
                table.setValueAt(squares[j], 2, j + 1);
                table.setValueAt(angles[j],  3, j + 1);
            view.getCentroidLabel().setText("centroid location: " +
                                             model.findCentroid());
    * TriangleModel.java
    * Created on 06 February 2005, 01:18
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.text.NumberFormat;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.DefaultTableCellRenderer;
    * @author  Rahindra Naidoo
    public class TriangleModel                      //  (x1, y1)
    {                                         //      |\
        static final int SIDES = 3;         //      | \
        private int cx, cy;                  //      |  \
        Polygon triangle;                     //      |_ _\ (x3, y3)
        int selectedIndex;                   //  (x2, y2)
        NumberFormat nf;
        Line2D[] medians;
        Point2D centroid;
        public TriangleModel(int x1, int y1, int x2, int y2, int x3, int y3)
            int[] x = new int[] { x1, x2, x3 };
            int[] y = new int[] { y1, y2, y3 };
            triangle = new Polygon(x, y, SIDES);
            nf = NumberFormat.getNumberInstance();
            nf.setMaximumFractionDigits(1);
        public boolean contains(Point p)
            // Polygon.contains doesn't work well enough
            return (new Area(triangle)).contains(p);
        public boolean isLineSelected(Rectangle r)
            Line2D line = new Line2D.Double();
            for(int j = 0; j < SIDES; j++)
                int[] x = triangle.xpoints;
                int[] y = triangle.ypoints;
                int x1 = x[j];
                int y1 = y[j];
                int x2 = x[(j + 1) % SIDES];
                int y2 = y[(j + 1) % SIDES];
                line.setLine(x1, y1, x2, y2);
                if(line.intersects(r))
                    selectedIndex = j;
                    return true;
            selectedIndex = -1;
            return false;
         * Only works for right triangle with right angle at (x2, y2)
        public void moveSide(int dx, int dy, Point p)
            int[] x = triangle.xpoints;
            int[] y = triangle.ypoints;
            switch(selectedIndex)
                case 0:
                    x[0] += dx;
                    x[1] += dx;
                    break;
                case 1:
                    y[1] += dy;
                    y[2] += dy;
                    break;
                case 2:
                    double rise  = y[2] - y[0];
                    double run   = x[2] - x[0];
                    double slope = rise/run;
                    // rise / run == (y[2] - p.y) / (x[2] - p.x)
                    x[2] = p.x + (int)((y[2] - p.y) / slope);
                    // rise / run == (p.y - y[0]) / (p.x - x[0])
                    y[0] = p.y - (int)((p.x - x[0]) * slope);
        public void translate(int dx, int dy)
            triangle.translate(dx, dy);
        public Polygon getTriangle()
            return triangle;
        public String findCentroid()
            int[] x = triangle.xpoints;
            int[] y = triangle.ypoints;
            // construct the medians defined as the line from
            // any vertex to the midpoint of the opposite line
            medians = new Line2D[x.length];
            for(int j = 0; j < x.length; j++)
                int next = (j + 1) % x.length;
                int last = (j + 2) % x.length;
                Point2D vertex = new Point2D.Double(x[j], y[j]);
                // get midpoint of line opposite vertex
                double dx = ((double)x[last] - x[next])/2;
                double dy = ((double)y[last] - y[next])/2;
                Point2D oppLineCenter = new Point2D.Double(x[next] + dx,
                                                           y[next] + dy);
                medians[j] = new Line2D.Double(vertex, oppLineCenter);
            // centroid is located on any median 2/3 the way from the
            // vertex (P1) to the midpoint (P2) on the opposite side
            double[] lengths = getSideLengths();
            double dx = (medians[0].getX2() - medians[0].getX1())*2/3;
            double dy = (medians[0].getY2() - medians[0].getY1())*2/3;
            double px = medians[0].getX1() + dx;
            double py = medians[0].getY1() + dy;
            //System.out.println("px = " + nf.format(px) +
            //                 "\tpy = " + nf.format(py));
            centroid = new Point2D.Double(px, py);
            return "(" + nf.format(px) + ",  " + nf.format(py) + ")";
        public String[] getAngles()
            double[] lengths = getSideLengths();
            String[] vertices = new String[lengths.length];
            for(int j = 0; j < lengths.length; j++)
                int opp  = (j + 1) % lengths.length;
                int last = (j + 2) % lengths.length;
                double top = lengths[j] * lengths[j] +
                             lengths[last] * lengths[last] -
                             lengths[opp] * lengths[opp];
                double divisor = 2 * lengths[j] * lengths[last];
                double vertex = Math.acos(top / divisor);
                vertices[j] = nf.format(Math.toDegrees(vertex));
            return vertices;
        public String[] getLengths()
            double[] lengths = getSideLengths();
            String[] lengthStrs = new String[lengths.length];
            for(int j = 0; j < lengthStrs.length; j++)
                lengthStrs[j] = nf.format(lengths[j]);
            return lengthStrs;
        public String[] getSquares()
            double[] lengths = getSideLengths();
            String[] squareStrs = new String[lengths.length];
            for(int j = 0; j < squareStrs.length; j++)
                squareStrs[j] = nf.format(lengths[j] * lengths[j]);
            return squareStrs;
        private double[] getSideLengths()
            int[] x = triangle.xpoints;
            int[] y = triangle.ypoints;
            double[] lengths = new double[SIDES];
            for(int j = 0; j < SIDES; j++)
                int next = (j + 1) % SIDES;
                lengths[j] = Point.distance(x[j], y[j], x[next], y[next]);
            return lengths;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.text.NumberFormat;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.DefaultTableCellRenderer;
    * TriangleView.java
    * Created on 06 February 2005, 01:21
    public class TriangleView extends JPanel
        private TriangleModel model;
        private Polygon triangle;
        private JTable table;
        private JLabel centroidLabel;
        private boolean showConstruction;
        TriangleControl control;
        public TriangleView(TriangleModel model)
            this.model = model;
            triangle = model.getTriangle();
            showConstruction = false;
            control = new TriangleControl(this);
            addMouseListener(control);
            addMouseMotionListener(control);
        public void paintComponent(Graphics g)
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            g2.draw(triangle);
            if(model.medians == null)
                centroidLabel.setText("centroid location: " + model.findCentroid());
            // draw medians and centroid point
            if(showConstruction && !control.dragging)
                g2.setPaint(Color.red);
                for(int j = 0; j < 3; j++)
                    g2.draw(model.medians[j]);
                g2.setPaint(Color.blue);
                g2.fill(new Ellipse2D.Double(model.centroid.getX() - 2,
                                             model.centroid.getY() - 2, 4, 4));
        public TriangleModel getModel()
            return model;
        public JTable getTable()
            return table;
        public JLabel getCentroidLabel()
            return centroidLabel;
        public JPanel getUIPanel()
            JCheckBox showCon = new JCheckBox("show construction");
            showCon.addActionListener(new ActionListener()
                public void actionPerformed(ActionEvent e)
                    boolean state = ((JCheckBox)e.getSource()).isSelected();
                    showConstruction = state;
                    repaint();
            JPanel panel = new JPanel();
            panel.add(showCon);
            return panel;
        public JPanel getTablePanel()
            String[] headers = new String[] { "", "", "", "" };
            // row and column data labels
            String[] rowHeaders = {
                "sides", "lengths", "squares", "angles", "degrees"
            String[] sidesRow = { "vertical", "horizontal", "hypotenuse" };
            String[] anglesRow = { "hyp to ver", "ver to hor", "hor to hyp" };
            // collect data from model
            String[] angles  = model.getAngles();
            String[] lengths = model.getLengths();
            String[] squares = model.getSquares();
            String[][] allData = { sidesRow, lengths, squares, anglesRow, angles };
            int rows = 5;
            int cols = 4;
            Object[][] data = new Object[rows][cols];
            for(int row = 0; row < rows; row++)
                data[row][0] = rowHeaders[row];
                for(int col = 1; col < cols; col++)
                    data[row][col] = allData[row][col - 1];
            table = new JTable(data, headers)
                public boolean isCellEditable(int row, int col)
                    return false;
            DefaultTableCellRenderer renderer =
                (DefaultTableCellRenderer)table.getDefaultRenderer(String.class);
            renderer.setHorizontalAlignment(JLabel.CENTER);
            centroidLabel = new JLabel("centroid location:  ", JLabel.CENTER);
            Dimension d = centroidLabel.getPreferredSize();
            d.height = table.getRowHeight();
            centroidLabel.setPreferredSize(d);
            JPanel panel = new JPanel(new BorderLayout());
            panel.setBorder(BorderFactory.createTitledBorder("triangle data"));
            panel.add(table);
            panel.add(centroidLabel, "South");
            return panel;
    }PLEASE HELP ---- Also does any one know how to draw a Triangle on a screen which can be controlled by a JSlider such that as and whenits incremented the triangle increase and vice versa... I need to prove Similarity in triangles using A Jslider that controls one triangle while the other triangle is Still on screen

    Sharan,
    The code given was part of the assignment and you are supposed to make the changes for your part right?
    Please give details of what you have done so far and not expect us to do your assignment for you. We'll be glad to help answer questions and point to the right direction, but giving us the entire assignment and saying, very nicely I might add, "Please do it for me." Just seems to make a mockery of the hours, days, and years that many of us has spent earning our degrees and learning our skills.
    Work on it and ask specific questions with examples of what you have done and you'll get a much better response.

  • Global keyboard binds once again - actkbd? Or?

    Hello,
    I'm trying to fix some "not-only-x" binds, since I'm kind of forcing myself to learn more linux in not only clickable way. I'm looking for an app or a tip how and what. Read this great forums and wiki, but still I've got some questions.
    I liked actkdb a lot, but I can't figure out how to make it not to print pressed char into terminal when I use the shortcut. In this example mod+comma:
    This works, but draws comma to console.
    # <keys>:<event type>:<attributes>:<command>
    # (mpd previous song)
    51+125:::mpc prev
    So I've tried to use grab:
    # <keys>:<event type>:<attributes>:<command>
    # (mpd previous song)
    51+125:key:ungrabbed,grab:mpc prev
    51+125:rel:grabbed,ungrab,noexec:
    This somehow keeps printing comma, but keyboard is usable - that's really weird, cause it's based on example found in example actkbdrc.
    Help&daemon/app advice appreciated.

    Thanks folks...
    Well I cannot see a reason to get anything but a Mini at this point... I already have 2x 1TB USB drives... its only USB but should be fast enough for iTunes and iPhoto libraries. As I mentioned I already have a work station of PCs for most of my video and audio editing (http://photos-c.ak.fbcdn.net/hphotos-ak-snc1/hs252.snc1/9931180904165131_612955131_4357708_2408102n.jpg)
    I only need to place the Mini in my rack and plug it in to one of my 22" monitors (as they both have dual inputs). Would be nice to place my dock on my desk for my iPod as well... with the MacBook - the computer is always in a different place in the house
    Cheers!
    Chris

  • What's wrong on the superclass and subclass

    Dear all,
    The drawing panel cannot draw the figures, what's wrong?
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.*;
    public class CustomPanel1 extends JFrame { 
    private final String list[] = { "Circle", "Square", "Triangle"};
    private FlowLayout layout1, layout2, layout3;
    private DrawShape drawPanel;
    private JButton clearButton;
    public static JLabel label;
    private JComboBox shapeList;
    private JTextField textField1, textField2;
    public static int size;
    // set up GUI
    public CustomPanel1() {   
    // create custom drawing area
    drawPanel = new DrawShape(this);
    // set up ClearButton
    clearButton = new JButton( "Clear" );
    // add the ActionListeber
    clearButton.addActionListener(
    new ActionListener() { // anonymous inner class
    // handle action perform event
    public void actionPerformed( ActionEvent event ) {        
    // clear originList
    drawPanel.originList.clear();
    drawPanel.area = 0;
    drawPanel.perimeter = 0;
    label.setText("Area " + drawPanel.area +
    " Perimeter " + drawPanel.perimeter );
    repaint();
    }// end handle
    } // end anonymous inner class
    ); // end call to addActionListener
    //set up combox
    shapeList = new JComboBox(list);
    shapeList.setMaximumRowCount(3);
    //add ItemListener
    shapeList.addItemListener(
    new ItemListener(){
    // handle item state change event
    public void itemStateChanged (ItemEvent event) {                  
    if(event.getStateChange() == ItemEvent.SELECTED){
    // draw circle
    if( shapeList.getSelectedIndex() == 0){           
    DrawCircle.shape = 0;
    DrawCircle.draw(DrawCircle.Circle);
    } // end if
    // draw square
    else if ( shapeList.getSelectedIndex() == 1) {           
    DrawShape.shape = 1;
    DrawSquare.draw( DrawSquare.Square);
    } // end if
    // draw triangle
    else if ( shapeList.getSelectedIndex() == 2) {           
    DrawShape.shape = 2;
    DrawTriangle.draw( DrawTriangle.Triangle);
    } // end if
    } // end if
    } // end handle
    } // end anonymous inner class
    ); // end call to addActionListener
    // set up parameter panel containing parameter
    JPanel parameterPanel = new JPanel();
    layout1 = new FlowLayout();
    parameterPanel.setLayout(layout1);
    parameterPanel.setBackground( Color.PINK );
    layout1.setAlignment( FlowLayout.CENTER);
    parameterPanel.add( new JScrollPane(shapeList));
    parameterPanel.add( clearButton );
    // set up the text Panel and textfield
    JPanel textPanel = new JPanel();
    layout3 = new FlowLayout();
    parameterPanel.setLayout(layout3);
    textPanel.setBackground( Color.PINK );
    layout3.setAlignment( FlowLayout.CENTER);
    textField1 = new JTextField( "Size");
    textField1.setFont(new Font("Serif",Font.BOLD,14));
    textField1.setEditable (false);
    textField2 = new JTextField( "",6);
    textField2.setFont(new Font("Serif",Font.BOLD,14));
    // add ActionListener
    textField2.addActionListener(
    new ActionListener(){
    // handle action perform event
    public void actionPerformed (ActionEvent event) {         
    JTextField field = (JTextField)event.getSource();
    String entry = field.getText();
    size = Integer.parseInt(entry);
    } // end handle
    } // end anonymous inner class
    ); // end call to addActionListener
    textPanel.add(textField1, BorderLayout.NORTH);
    textPanel.add(textField2, BorderLayout.SOUTH);
    // set up the combine panel of parameterPanel and textPanel
    GridLayout gridLayout = new GridLayout();
    gridLayout.setRows(2);
    gridLayout.setColumns(1);
    JPanel combinPanel = new JPanel();
    combinPanel.setBackground( Color.PINK );
    combinPanel.setLayout(gridLayout);
    combinPanel.add(parameterPanel, BorderLayout.NORTH);
    combinPanel.add(textPanel, BorderLayout.SOUTH);
    // set up datapanel conaining data
    JPanel dataPanel = new JPanel();
    layout2 = new FlowLayout();
    dataPanel.setLayout(layout2);
    dataPanel.setBackground( Color.PINK );
    label = new JLabel ("Area " + drawPanel.area + "Perimeter " +
    drawPanel.perimeter, SwingConstants.CENTER);
    dataPanel.add( label);
    // attach button panel & custom drawing area to content pane
    Container container = getContentPane();
    container.add( combinPanel, BorderLayout.NORTH);
    container.add( drawPanel, BorderLayout.CENTER );
    container.add( dataPanel, BorderLayout.SOUTH );
    setSize( 500, 500 );
    setVisible( true );
    } // end constructor CustomPanelTest
    // main
    public static void main ( String args[] ) {   
    CustomPanel1 app = new CustomPanel1();
    app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    } // end main
    } // end class CustomPanelTest
    // A customized JPanel class.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.*;
    class DrawShape extends JPanel {
    public final static int Circle = 0, Square = 1, Triangle = 2;
    public static int shape;
    public int xPos,yPos;
    java.util.List originList;
    public int count = 0;
    public static double area ;
    public static double perimeter ;
    final double pi=3.141592;
    CustomPanel1 client;
    boolean shapeWasCreated = false;
    public DrawShape(CustomPanel1 customer){     
    this.client = customer;
    // set up the list of shape to draw
    originList = new ArrayList();
    // set up mouse listener
    addMouseListener(
    new MouseAdapter() {  // anonymous inner class
    // handle mouse press event
    public void mousePressed( MouseEvent event )
    xPos = event.getX();
    yPos = event.getY();
    originList.add(count, new String(
    shape + "." + xPos + "," + yPos + "*" + CustomPanel1.size ));
    // set to draw ready
    shapeWasCreated = true;
    repaint();
    } // end handle
    } // end anonymous inner class
    ); // end call to addMouseListener
    } // end method
    } // end class
    // A customized JPanel class.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.*;
    public class DrawCircle extends DrawShape {
    public static double circleArea, circlePerimeter;
    public DrawCircle(CustomPanel1 customer){
    super(customer);
    } // end method
    // use shape to draw an oval, rectangle or triangle
    public void paintComponent( Graphics g )
    super.paintComponent( g );
    initializeShapeVariables();
    for(int i = 0; i<originList.size(); i++){
    String XY =(String)originList.get(i);
    int star = XY.indexOf("*");
    int dot = XY.indexOf(".");
    int comma = XY.indexOf(",");
    int shapeToDraw = Integer.parseInt(XY.substring(0,dot));
    int pickedX = Integer.parseInt(XY.substring(dot + 1,comma));
    int pickedY = Integer.parseInt(XY.substring(comma + 1, star));
    int shapeSize = Integer.parseInt(XY.substring(star + 1));
    int x = pickedX-(shapeSize/2);
    int y = pickedY-(shapeSize/2);
    // draw a circle
    if ( shapeToDraw == Circle ) {        
    g.drawOval(x ,y , shapeSize, shapeSize );
    if(shapeWasCreated){
    circleArea = (pi * (((double)(shapeSize)/2) * (((double)shapeSize)/2)));
    area += circleArea;
    circlePerimeter = (pi * (shapeSize));
    perimeter += circlePerimeter;
    CustomPanel1.label.setText("Area " + area + "Perimeter " + perimeter);
    } //end if
    } //end if
    } // end for
    if(shapeWasCreated)
    shapeWasCreated = false;
    } // end if
    private void initializeShapeVariables(){
    area = 0;
    perimeter = 0;
    circleArea = 0;
    circlePerimeter = 0;
    } // end method
    // set shape value and repaint
    public static void draw( int shapeToDraw )
    shape = shapeToDraw;
    //repaint();
    } //end method
    } // end class
    // A customized JPanel class.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.*;
    public class DrawSquare extends DrawShape {
    public static double squareArea, squarePerimeter;
    public DrawSquare(CustomPanel1 customer){
    super(customer);
    } // end method
    // use shape to draw an oval, rectangle or triangle
    public void paintComponent( Graphics g )
    super.paintComponent( g );
    initializeShapeVariables();
    for(int i = 0; i<originList.size(); i++){
    String XY =(String)originList.get(i);
    int star = XY.indexOf("*");
    int dot = XY.indexOf(".");
    int comma = XY.indexOf(",");
    int shapeToDraw = Integer.parseInt(XY.substring(0,dot));
    int pickedX = Integer.parseInt(XY.substring(dot + 1,comma));
    int pickedY = Integer.parseInt(XY.substring(comma + 1, star));
    int shapeSize = Integer.parseInt(XY.substring(star + 1));
    int x = pickedX-(shapeSize/2);
    int y = pickedY-(shapeSize/2);
    if ( shapeToDraw == Square ){        
    g.drawRect( x, y, shapeSize, shapeSize );
    if(shapeWasCreated){
    squareArea = ( shapeSize * shapeSize);
    area += squareArea;
    squarePerimeter = (4 * shapeSize);
    perimeter += squarePerimeter;
    CustomPanel1.label.setText("Area " + area + "Perimeter " + perimeter);
    } //end if
    } //end if
    } // end for
    if(shapeWasCreated)
    shapeWasCreated = false;
    } // end if
    private void initializeShapeVariables(){
    area = 0;
    perimeter = 0;
    squareArea = 0;
    squarePerimeter = 0;
    } // end method
    // set shape value and repaint
    public static void draw( int shapeToDraw )
    shape = shapeToDraw;
    //repaint();
    } //end method
    } // end class
    // A customized JPanel class.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.*;
    public class DrawTriangle extends DrawShape {
    public static double triangleArea, trianglePerimeter;
    public DrawTriangle(CustomPanel1 customer){
    super(customer);
    } // end method
    // use shape to draw an oval, rectangle or triangle
    public void paintComponent( Graphics g )
    super.paintComponent( g );
    initializeShapeVariables();
    for(int i = 0; i<originList.size(); i++){
    String XY =(String)originList.get(i);
    int star = XY.indexOf("*");
    int dot = XY.indexOf(".");
    int comma = XY.indexOf(",");
    int shapeToDraw = Integer.parseInt(XY.substring(0,dot));
    int pickedX = Integer.parseInt(XY.substring(dot + 1,comma));
    int pickedY = Integer.parseInt(XY.substring(comma + 1, star));
    int shapeSize = Integer.parseInt(XY.substring(star + 1));
    int x1=pickedX-(shapeSize/2);
    int y1=pickedY+(shapeSize/2);
    int x2=pickedX+(shapeSize/2);
    int y2=y1;
    int x3=pickedX;
    int y3=pickedY-((int)(1.73205*shapeSize*0.33333));
    if (shapeToDraw == Triangle)
    g.drawLine(x1, y1, x2, y2);
    g.drawLine(x1, y1, x3, y3);
    g.drawLine(x3, y3, x2, y2);
    if(shapeWasCreated){
    triangleArea = (double)(shapeSize * shapeSize/2);
    area += triangleArea;
    trianglePerimeter = (3 * (shapeSize));
    perimeter += trianglePerimeter;
    CustomPanel1.label.setText("Area " + area + "Perimeter " + perimeter);
    } //end if
    } //end if
    } // end for
    if(shapeWasCreated)
    shapeWasCreated = false;
    } // end if
    private void initializeShapeVariables(){
    area = 0;
    perimeter = 0;
    triangleArea = 0;
    trianglePerimeter = 0;
    } // end method
    // set shape value and repaint
    public static void draw( int shapeToDraw )
    shape = shapeToDraw;
    //repaint();
    } //end method
    } // end class

    The drawing panel cannot draw the figures, what's
    wrong?You can't have written this much code and then suddenly detected it doesn't work at all. You must now restart from the point where you had a working program. Then you add code is small increments and see to it that it works in each step and you understand why it works. This method is called stepwise refinement and it does wonders.

  • Changing code to Drawings

    I am having problems coverting the code below so instead of entering the date and month and clicking update calendar there are arrows at the top so it looks like this:
    < (year) >
    < (month) >
    and then the calendar below. The user should be able to click on the arrows and move the calendar foward/backwards through the months and years. I am having a hard time trying to figure out how to draw triangles and add them to the applet with actionlisteners. I appreciate any help I can get.
    import java.applet.Applet;
    import java.awt.*;
    import java.util.Date;
    public class Calendar extends Applet
    static final int YTOP = 80; // y-size of margin above calendar box
    static final int YHEADER = 30; // y-size of horz strip with day names
    static final int NCELLX = 7; // number of cells across
    static final int CELLSIZE = 40; // size of each square cell
    static final int MARGIN = 8; // margin from number to cell top, right
    static final int FEBRUARY = 1; // special month during leap years
    // Data entry controls at top.
    Label yearLabel = new Label("Year:");
    TextField yearTextField = new TextField("1996", 5);
    Label monthLabel = new Label("Month:");
    Choice monthChoice = new Choice();
    Button newCalButton = new Button("New Calendar");
    // Date object to get current month and year.
    Date now = new Date();
    // Font for controls at top.
    Font smallArialFont = new Font("Arial", Font.PLAIN, 15);
    // Font for for month/year caption above calendar.
    Font largeArialFont = new Font("Arial", Font.BOLD, 25);
    String days[] = {"S", "M", "T", "W",
    "T", "F", "S"}; //Sun, Mon, Tues, Wed, Thurs, Fri, Sat
    String months[] = {"January", "February", "March", "April",
    "May", "June", "July", "August", "September",
    "October", "November", "December"};
    int DaysInMonth[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    // Month and year entered by user.
    int userMonth;
    int userYear;
    public void init()
    USE: Get current month and year, initialize controls.
    NOTE: Called automatically when applet starts.
    setBackground(Color.white);
    // Init month and year to current values.
    userMonth = now.getMonth();
    userYear = now.getYear() + 1900;
    // "Year:" label.
    yearLabel.setFont(smallArialFont);
    add(yearLabel);
    // Text field to get year from user.
    yearTextField.setFont(smallArialFont);
    yearTextField.setText(String.valueOf(userYear));
    add(yearTextField);
    // "Month:" label.
    monthLabel.setFont(smallArialFont);
    add(monthLabel);
    // Combo box to get month from user: add months, set default to now.
    monthChoice.setFont(smallArialFont);
    for (int i = 0; i < 12; i++)
    monthChoice.addItem(months);
    monthChoice.select(userMonth);
    add(monthChoice);
    // "New calendar" button.
    newCalButton.setFont(smallArialFont);
    add(newCalButton);
    } // init
    public void paint(Graphics g)
    USE: Draw calendar using globals userMonth and userYear.
    NOTE: Called automatically whenever surface needs to be redrawn;
    also when user clicks 'New Calendar' button, triggering repaint.
    FontMetrics fm; /* to get font info */
    int fontAscent; /* character height */
    int dayPos; /* y-position of day strings */
    int xSize, ySize; /* size of calendar body (cell table) */
    int numRows; /* number of rows in cell table (4, 5, 6) */
    int xNum, yNum; /* number position at top right of cells */
    int numDays; /* number of days in month */
    String dayStr; /* day of the week as a string */
    int marg; /* margin of month string baseline from cell table */
    String caption; /* month string at top center */
    // Get font info for number string positioning (default small font).
    fm = g.getFontMetrics();
    fontAscent = fm.getAscent();
    dayPos = YTOP + (YHEADER + fontAscent) / 2;
    // Get x-size of calendar body (cell table).
    xSize = NCELLX * CELLSIZE;
    // Header rectangle across top for day names.
    g.drawRect(0, YTOP, xSize, YHEADER);
    // Put days at top of each column, centered.
    for (int i = 0; i < NCELLX; i++)
    g.drawString(days[i], (CELLSIZE-fm.stringWidth(days[i]))/2 + i*CELLSIZE,
    dayPos);
    // Get number of calendar rows needed for this month.
    numRows = NumberRowsNeeded(userYear, userMonth);
    // Vertical lines of cell table.
    ySize = numRows * CELLSIZE;
    for (int i = 0; i <= xSize; i += CELLSIZE)
    g.drawLine(i, YTOP + YHEADER, i, YTOP + YHEADER + ySize);
    // Horizontal lines of cell table.
    for (int i = 0, j = YTOP + YHEADER; i <= numRows; i++, j += CELLSIZE)
    g.drawLine(0, j, xSize, j);
    // Init number positions (upper right of cell).
    xNum = (CalcFirstOfMonth(userYear, userMonth) + 1) * CELLSIZE - MARGIN;
    yNum = YTOP + YHEADER + MARGIN + fontAscent;
    // Get number of days in month, adding one if February of leap year.
    numDays = DaysInMonth[userMonth] +
    ((IsLeapYear(userYear) && (userMonth == FEBRUARY)) ? 1 : 0);
    // Show numbers at top right of each cell, right justified.
    for (int day = 1; day <= numDays; day++)
    dayStr = String.valueOf(day);
    g.drawString(dayStr, xNum - fm.stringWidth(dayStr), yNum);
    xNum += CELLSIZE;
    // If xNum to right of calendar, 'new line'.
    if (xNum > xSize)
    xNum = CELLSIZE - MARGIN;
    yNum += CELLSIZE;
    } // if
    } // for
    // Set large font for month/year caption.
    g.setFont(largeArialFont);
    // Get font info for string positioning (large font now current).
    fm = g.getFontMetrics();
    // Set margin for y-positioning of caption.
    marg = 2 * fm.getDescent();
    // Set caption to month string and center at top.
    caption = months[userMonth] + " " + String.valueOf(userYear);
    g.drawString(caption, (xSize-fm.stringWidth(caption))/2, YTOP - marg);
    } // paint
    public boolean action(Event e, Object o)
    USE: Update month and year globals, paint when user clicks button.
    int userYearInt;
    if (e.target instanceof Button)
    if ("New Calendar".equals((String)o))
    // Get month from combo box (Choice control).
    userMonth = monthChoice.getSelectedIndex();
    // Get year from TextField, update userYear only if year ok.
    userYearInt = Integer.parseInt(yearTextField.getText(), 10);
    if (userYearInt > 1581)
    userYear = userYearInt;
    // Call paint() to draw new calendar.
    repaint();
    return true;
    } // inner if
    } // outer if
    return false;
    } // action
    int NumberRowsNeeded(int year, int month)
    USE: Calculates number of rows needed for calendar.
    IN: year = given year after 1582 (start of the Gregorian calendar).
    month = 0 for January, 1 for February, etc.
    OUT: Number of rows: 5 or 6, except for a 28 day February with
    the first of the month on Sunday, requiring only four rows.
    int firstDay; /* day of week for first day of month */
    int numCells; /* number of cells needed by the month */
    /* Start at 1582, when modern calendar starts. */
    if (year < 1582) return (-1);
    /* Catch month out of range. */
    if ((month < 0) || (month > 11)) return (-1);
    /* Get first day of month. */
    firstDay = CalcFirstOfMonth(year, month);
    /* Non leap year February with 1st on Sunday: 4 rows. */
    if ((month == FEBRUARY) && (firstDay == 0) && !IsLeapYear(year))
    return (4);
    /* Number of cells needed = blanks on 1st row + days in month. */
    numCells = firstDay + DaysInMonth[month];
    /* One more cell needed for the Feb 29th in leap year. */
    if ((month == FEBRUARY) && (IsLeapYear(year))) numCells++;
    /* 35 cells or less is 5 rows; more is 6. */
    return ((numCells <= 35) ? 5 : 6);
    } // NumberRowsNeeded
    int CalcFirstOfMonth(int year, int month)
    USE: Calculates day of the week the first day of the month falls on.
    IN: year = given year after 1582 (start of the Gregorian calendar).
    month = 0 for January, 1 for February, etc.
    OUT: First day of month: 0 = Sunday, 1 = Monday, etc.
    int firstDay; /* day of week for Jan 1, then first day of month */
    int i; /* to traverse months before given month */
    /* Start at 1582, when modern calendar starts. */
    if (year < 1582) return (-1);
    /* Catch month out of range. */
    if ((month < 0) || (month > 11)) return (-1);
    /* Get day of week for Jan 1 of given year. */
    firstDay = CalcJanuaryFirst(year);
    /* Increase firstDay by days in year before given month to get first day
    * of month.
    for (i = 0; i < month; i++)
    firstDay += DaysInMonth[i];
    /* Increase by one if month after February and leap year. */
    if ((month > FEBRUARY) && IsLeapYear(year)) firstDay++;
    /* Convert to day of the week and return. */
    return (firstDay % 7);
    } // CalcFirstOfMonth
    boolean IsLeapYear(int year)
    USE: Determines if given year is a leap year.
    IN: year = given year after 1582 (start of the Gregorian calendar).
    OUT: TRUE if given year is leap year, FALSE if not.
    NOTE: Formulas capture definition of leap years; cf CalcLeapYears().
    /* If multiple of 100, leap year iff multiple of 400. */
    if ((year % 100) == 0) return((year % 400) == 0);
    /* Otherwise leap year iff multiple of 4. */
    return ((year % 4) == 0);
    } // IsLeapYear
    int CalcJanuaryFirst(int year)
    USE: Calculate day of the week on which January 1 falls for given year.
    IN: year = given year after 1582 (start of the Gregorian calendar).
    OUT: Day of week for January 1: 0 = Sunday, 1 = Monday, etc.
    NOTE: Formula starts with a 5, since January 1, 1582 was a Friday; then
    advances the day of the week by one for every year, adding the
    number of leap years intervening, because those years Jan 1
    advanced by two days. Calculate mod 7 to get the day of the week.
    /* Start at 1582, when modern calendar starts. */
    if (year < 1582) return (-1);
    /* Start Fri 01-01-1582; advance a day for each year, 2 for leap yrs. */
    return ((5 + (year - 1582) + CalcLeapYears(year)) % 7);
    } // CalcJanuaryFirst
    int CalcLeapYears(int year)
    USE: Calculate number of leap years since 1582.
    IN: year = given year after 1582 (start of the Gregorian calendar).
    OUT: number of leap years since the given year, -1 if year < 1582
    NOTE: Count doesn't include the given year if it is a leap year.
    In the Gregorian calendar, used since 1582, every fourth year
    is a leap year, except for years that are a multiple of a
    hundred, but not a multiple of 400, which are no longer leap
    years. Years that are a multiple of 400 are still leap years:
    1700, 1800, 1990 were not leap years, but 2000 will be.
    int leapYears; /* number of leap years to return */
    int hundreds; /* number of years multiple of a hundred */
    int fourHundreds; /* number of years multiple of four hundred */
    /* Start at 1582, when modern calendar starts. */
    if (year < 1582) return (-1);
    /* Calculate number of years in interval that are a multiple of 4. */
    leapYears = (year - 1581) / 4;
    /* Calculate number of years in interval that are a multiple of 100;
    * subtract, since they are not leap years.
    hundreds = (year - 1501) / 100;
    leapYears -= hundreds;
    /* Calculate number of years in interval that are a multiple of 400;
    * add back in, since they are still leap years.
    fourHundreds = (year - 1201) / 400;
    leapYears += fourHundreds;
    return (leapYears);
    } // CalcLeapYears
    } // class Calendar

    If you post code, please post only the relevant parts and use the code tags to maintain the formatting.
    http://java.sun.com/docs/books/tutorial/uiswing/
    My hint is to use JLabels and JButtons in a panel. One panel like:
    B L B
    B L B
    for navigation and one panel like
    L L L L L L L
    L L L L L L L
    L L L L L L L
    L L L L L L L
    L L L L L L L
    to show the calendar. Set the label's texts to whatever you need.

  • Help with JTextArea

    Hi,
    I am working on a GUI Application and need some hlep.
    1] When I click on Next Item button, it should clear the previously entered values of TextFields. How do I do this?
    2] How do I display text in a JTextArea which appears in a Pop-up window?
    I will appreciate your help and time.
    Here is what I have done so far:
    // FILE Name: ProductOrder.java
    // Purpose: This class contains the GUI part
    import javax.swing.*;
    import java.awt.*; //FlowLayout;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    public class ProductOrder extends JFrame //implements ActionListener
       private Product productArray[];  //array of Product objects
       private final int NUM_OF_PROD_ELEMENTS = 6;
       private JLabel label1;
       private JLabel label2;
       private JLabel label3;
       private JTextField textField1;
       private JTextField textField2;
       private JButton button1; // Next Item button
       private JButton button2; // Receipt button
       private JButton button3; // Summary button
       // Class constructor
       public ProductOrder()
          super( "Welcome!!!" );
          productArray = new Product[NUM_OF_PROD_ELEMENTS];
          productArray[0] = new Product(100, "White Bandana", 4.98F, 0F);
          productArray[1] = new Product(200, "Green License Plate", 5.99F, 3.5F);
          productArray[2] = new Product(300, "Green Sweat Shirt", 24.99F, 7.2F);
          productArray[3] = new Product(400, "Low Profile hat", 17.98F, 4F);
          productArray[4] = new Product(500, "Gym Short", 16.98F, 4.2F);
          productArray[5] = new Product(600, "Printed Golf Balls", 8.99F, 0F);
          //float i = productArray[0].Calculate(5);
          setLayout( new FlowLayout() );
          label1 = new JLabel( "USF Campus Store" );
          add(label1);
          label2 = new JLabel( "Product Code:                                " );
          label2.setToolTipText( "Enter Product Code");
          add(label2);
          textField1 = new JTextField(2);
          add( textField1 );
          label3 = new JLabel( "Quantity:                                          " );
          label3.setToolTipText( "Enter Quantity Number");
          add(label3);
          textField2 = new JTextField(2);
          add( textField2 );
          button1 = new JButton( "Next Item");
          add( button1 );  //add button1 to JFrame
          button2 = new JButton( "Receipt");
          add( button2 );  //add button1 to JFrame
          button3 = new JButton( "Summary");
          add( button3 );  //add button1 to JFrame
          // Register event handlers
          ProductHandler handler = new ProductHandler();
          textField1.addActionListener( handler ); // Product Code
          textField2.addActionListener( handler ); // Quantity
          button1.addActionListener( handler );    // Next Item
          button2.addActionListener( handler );    // Receipt
          button3.addActionListener( handler );    // Summary
       }//end of constrct
       // Private inner class for event handling
       private class ProductHandler implements ActionListener
          public void actionPerformed( ActionEvent event )
             String string , string1;
          int pCode = 000, quant = 000;
          if (event.getSource() == textField1 )
             string = event.getActionCommand();
             //pCode = Integer.parseInt( string );
             }//end of if1
             else if (event.getSource() == textField2 )
             string1 = event.getActionCommand();
             //quant = Integer.parseInt( string1 );
             else if ( event.getSource() == button1 )  // Next Item button
                JOptionPane.showMessageDialog(null, "product code: " + textField1.getText() + " " + "Quantity: " + textField2.getText() );
             else if ( event.getSource() == button2 )  // Receipt button
          //JOptionPane.showMessageDialog(null, "product code: " + pCode );
             //JOptionPane.showMessageDialog(null, "Quantity: " + quant );
          }//end of actionPerformed( ) method
       }//end of class ProductHandler
       /*public void showOrder()
         System.out.println("\nSuccess: this is ProductOrder class. ");
    } //end ProductOrder

    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.text.NumberFormat;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.DefaultTableCellRenderer;
    import java.lang.*;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseMotionListener;
    import java.awt.FileDialog;
    import java.io.*;
    import java.awt.BorderLayout;
    import java.awt.Container;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseMotionListener;
    import javax.swing.JFrame;
    public class Geometry {
    CardLayout cards;
    JPanel panel;
    public Geometry() {
    cards = new CardLayout();
    panel = new JPanel(cards);
    addCards();
    JFrame f = new JFrame("Geometry");
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setJMenuBar(getMenuBar());
    f.getContentPane().add(panel);
    f.setSize(500,500);
    f.setLocation(0,0);
    f.setVisible(true);
    f.addMouseMotionListener(
    new MouseMotionListener() { //anonymous inner class
    //handle mouse drag event
    public void mouseMoved(MouseEvent e) {
    System.out.println("Mouse " + e.getX() +"," + e.getY());
    public void mouseDragged(MouseEvent e) {
    System.out.println("Draggg: x=" + e.getX() + "; y=" + e.getY());
    // public void mouseMoved(MouseEvent me) {
    // System.out.println("Moving: x=" + me.getX() + "; y=" + me.getY());
    // panel.addMouseMotionListener(
    // new MouseMotionListener() { //anonymous inner class
    // //handle mouse drag event
    // public void mouseDragged(MouseEvent me) {
    // setTitle("Dragging: x=" + me.getX() + "; y=" + me.getY());
    // public void mouseMoved(MouseEvent me) {
    // setTitle("Moving: x=" + me.getX() + "; y=" + me.getY());
    private void addCards() {
    // card one
    TriangleModel tri = new TriangleModel(175,100,175,250,325,250);
    TriangleView view = new TriangleView(tri);
    JPanel panelOne = new JPanel(new BorderLayout());
    panelOne.add(view.getUIPanel(), "North");
    panelOne.add(view);
    panelOne.add(view.getTablePanel(), "South");
    panelOne.setName("Pythagoras's Theorem");
    panel.add("Pythagoras's Theorem", panelOne);
    view.addMouseMotionListener(
    new MouseMotionListener() { //anonymous inner class
    //handle mouse drag event
    public void mouseMoved(MouseEvent e) {
    System.out.println("Mouse at " + e.getX() +"," + e.getY());
    public void mouseDragged(MouseEvent e) {
    System.out.println("Dragging: x=" + e.getX() + "; y=" + e.getY());
    // card two
    TestModel trin = new TestModel(175,100,175,250,325,250);
    TestView viewn = new TestView(trin);
    JPanel panelTwo = new JPanel(new BorderLayout());
    panelTwo.add(viewn.getUIPanel(), "North");
    // panelTwo.setBackground(Color.blue);
    panelTwo.setName("Similar Triangles");
    panelTwo.add(viewn);
    panelTwo.add(viewn.getTablePanel(), "South");
    viewn.addMouseMotionListener(
    new MouseMotionListener() { //anonymous inner class
    //handle mouse drag event
    public void mouseMoved(MouseEvent e) {
    System.out.println("Mouse at " + e.getX() +"," + e.getY());
    public void mouseDragged(MouseEvent e) {
    System.out.println("Dragging: x=" + e.getX() + "; y=" + e.getY());
    panel.add("Similar Triangles", panelTwo);
    JPanel panelThree = new JPanel();
    panelThree.setBackground(Color.white);
    panelThree.setName("Circle Theorem1");
    panel.add("Circle Theorem1", panelThree);
    private JMenuBar getMenuBar() {
    JMenu File = new JMenu("File");
    JSeparator separator1 = new JSeparator();
    JMenuItem Open = new JMenuItem("Open");
    // Open.addActionListener(new java.awt.event.ActionListener() {
    // public void actionPerformed(java.awt.event.ActionEvent evt) {
    // openActionPerformed(evt);
    JMenuItem Save = new JMenuItem("Save");
    JMenuItem Print = new JMenuItem("Print");
    JMenuItem Exit = new JMenuItem("Exit");
    Exit.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    ExitActionPerformed(evt);
    JMenu theorem = new JMenu("Theorem");
    ActionListener l = new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    JMenuItem item = (JMenuItem)e.getSource();
    String name = item.getActionCommand();
    cards.show(panel, name);
    Component[] c = panel.getComponents();
    for(int j = 0; j < panel.getComponentCount(); j++) {
    String name = c[j].getName();
    JMenuItem item = new JMenuItem(name);
    item.setActionCommand(name);
    item.addActionListener(l);
    theorem.add(item);
    JMenuBar menuBar = new JMenuBar();
    JMenuBar menuBar1 = new JMenuBar();
    menuBar.add(File);
    File.add(Open);
    File.add(separator1);
    File.add(Save);
    File.add(Print);
    File.add(Exit);
    menuBar.add(theorem);
    return menuBar;
    // private void openActionPerformed(java.awt.event.ActionEvent evt) {
    // FileDialog fileDialog = new FileDialog(this, "Open...", FileDialog.LOAD);
    // fileDialog.show();
    // if (fileDialog.getFile() == null)
    // return;
    // fileName = fileDialog.getDirectory() + File.separator + fileDialog.getFile();
    // FileInputStream fis = null;
    // String str = null;
    // try {
    // fis = new FileInputStream(fileName);
    // int size = fis.available();
    // byte[] bytes = new byte [size];
    // fis.read(bytes);
    // str = new String(bytes);
    // } catch (IOException e) {
    // } finally {
    // try {
    // fis.close();
    // } catch (IOException e2) {
    // if (str != null)
    // textBox.setText(str);
    private void ExitActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:
    System.exit(0);
    public static void main(String[] args) {
    new Geometry();
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.text.NumberFormat;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.DefaultTableCellRenderer;
    public class Triangle
    public Triangle()
    TriangleModel tri = new TriangleModel(175,100,175,250,325,250);
    TriangleView view = new TriangleView(tri);
    JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.getContentPane().add(view.getUIPanel(), "North");
    f.getContentPane().add(view);
    f.getContentPane().add(view.getTablePanel(), "South");
    f.setSize(500,500);
    f.setLocation(200,200);
    f.setVisible(true);
    import java.awt.Point;
    import java.awt.Rectangle;
    import java.awt.event.MouseEvent;
    import javax.swing.JTable;
    import javax.swing.event.MouseInputAdapter;
    * TriangleControl.java
    * Created on 06 February 2005, 01:19
    * @author Rahindra Naidoo
    public class TriangleControl extends MouseInputAdapter
    TriangleView view;
    TriangleModel model;
    Point start;
    boolean dragging, altering;
    Rectangle lineLens; // used for line selection
    public TriangleControl(TriangleView tv)
    view = tv;
    model = view.getModel();
    dragging = altering = false;
    lineLens = new Rectangle(0, 0, 6, 6);
    public void mousePressed(MouseEvent e)
    Point p = e.getPoint();
    lineLens.setLocation(p.x - 3, p.y - 3);
    // are we over a line
    if(model.isLineSelected(lineLens))
    start = p;
    altering = true;
    // or are we within the triangle
    else if(model.contains(p))
    start = p;
    dragging = true;
    public void mouseReleased(MouseEvent e)
    altering = false;
    dragging = false;
    view.getCentroidLabel().setText("centroid location: " +
    model.findCentroid());
    view.repaint(); // for the construction lines
    public void mouseDragged(MouseEvent e)
    Point p = e.getPoint();
    if(altering)
    int x = p.x - start.x;
    int y = p.y - start.y;
    model.moveSide(x, y, p);
    updateTable();
    view.repaint();
    start = p;
    else if(dragging)
    int x = p.x - start.x;
    int y = p.y - start.y;
    model.translate(x, y);
    view.repaint();
    start = p;
    private void updateTable()
    String[] lengths = model.getLengths();
    String[] squares = model.getSquares();
    String[] angles = model.getAngles();
    JTable table = view.getTable();
    for(int j = 0; j < angles.length; j++)
    table.setValueAt(lengths[j], 1, j + 1);
    table.setValueAt(squares[j], 2, j + 1);
    table.setValueAt(angles[j], 3, j + 1);
    view.getCentroidLabel().setText("centroid location: " +
    model.findCentroid());
    * TriangleModel.java
    * Created on 06 February 2005, 01:18
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.text.NumberFormat;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.DefaultTableCellRenderer;
    * @author Rahindra Naidoo
    public class TriangleModel // (x1, y1)
    {                                         //      |\
    static final int SIDES = 3; // | \
    private int cx, cy; // | \
    Polygon triangle; // |_ _\ (x3, y3)
    int selectedIndex; // (x2, y2)
    NumberFormat nf;
    Line2D[] medians;
    Point2D centroid;
    public TriangleModel(int x1, int y1, int x2, int y2, int x3, int y3)
    int[] x = new int[] { x1, x2, x3 };
    int[] y = new int[] { y1, y2, y3 };
    triangle = new Polygon(x, y, SIDES);
    nf = NumberFormat.getNumberInstance();
    nf.setMaximumFractionDigits(1);
    public boolean contains(Point p)
    // Polygon.contains doesn't work well enough
    return (new Area(triangle)).contains(p);
    public boolean isLineSelected(Rectangle r)
    Line2D line = new Line2D.Double();
    for(int j = 0; j < SIDES; j++)
    int[] x = triangle.xpoints;
    int[] y = triangle.ypoints;
    int x1 = x[j];
    int y1 = y[j];
    int x2 = x[(j + 1) % SIDES];
    int y2 = y[(j + 1) % SIDES];
    line.setLine(x1, y1, x2, y2);
    if(line.intersects(r))
    selectedIndex = j;
    return true;
    selectedIndex = -1;
    return false;
    * Only works for right triangle with right angle at (x2, y2)
    public void moveSide(int dx, int dy, Point p)
    int[] x = triangle.xpoints;
    int[] y = triangle.ypoints;
    switch(selectedIndex)
    case 0:
    x[0] += dx;
    x[1] += dx;
    break;
    case 1:
    y[1] += dy;
    y[2] += dy;
    break;
    case 2:
    double rise = y[2] - y[0];
    double run = x[2] - x[0];
    double slope = rise/run;
    // rise / run == (y[2] - p.y) / (x[2] - p.x)
    x[2] = p.x + (int)((y[2] - p.y) / slope);
    // rise / run == (p.y - y[0]) / (p.x - x[0])
    y[0] = p.y - (int)((p.x - x[0]) * slope);
    public void translate(int dx, int dy)
    triangle.translate(dx, dy);
    public Polygon getTriangle()
    return triangle;
    public String findCentroid()
    int[] x = triangle.xpoints;
    int[] y = triangle.ypoints;
    // construct the medians defined as the line from
    // any vertex to the midpoint of the opposite line
    medians = new Line2D[x.length];
    for(int j = 0; j < x.length; j++)
    int next = (j + 1) % x.length;
    int last = (j + 2) % x.length;
    Point2D vertex = new Point2D.Double(x[j], y[j]);
    // get midpoint of line opposite vertex
    double dx = ((double)x[last] - x[next])/2;
    double dy = ((double)y[last] - y[next])/2;
    Point2D oppLineCenter = new Point2D.Double(x[next] + dx,
    y[next] + dy);
    medians[j] = new Line2D.Double(vertex, oppLineCenter);
    // centroid is located on any median 2/3 the way from the
    // vertex (P1) to the midpoint (P2) on the opposite side
    double[] lengths = getSideLengths();
    double dx = (medians[0].getX2() - medians[0].getX1())*2/3;
    double dy = (medians[0].getY2() - medians[0].getY1())*2/3;
    double px = medians[0].getX1() + dx;
    double py = medians[0].getY1() + dy;
    //System.out.println("px = " + nf.format(px) +
    // "\tpy = " + nf.format(py));
    centroid = new Point2D.Double(px, py);
    return "(" + nf.format(px) + ", " + nf.format(py) + ")";
    public String[] getAngles()
    double[] lengths = getSideLengths();
    String[] vertices = new String[lengths.length];
    for(int j = 0; j < lengths.length; j++)
    int opp = (j + 1) % lengths.length;
    int last = (j + 2) % lengths.length;
    double top = lengths[j] * lengths[j] +
    lengths[last] * lengths[last] -
    lengths[opp] * lengths[opp];
    double divisor = 2 * lengths[j] * lengths[last];
    double vertex = Math.acos(top / divisor);
    vertices[j] = nf.format(Math.toDegrees(vertex));
    return vertices;
    public String[] getLengths()
    double[] lengths = getSideLengths();
    String[] lengthStrs = new String[lengths.length];
    for(int j = 0; j < lengthStrs.length; j++)
    lengthStrs[j] = nf.format(lengths[j]);
    return lengthStrs;
    public String[] getSquares()
    double[] lengths = getSideLengths();
    String[] squareStrs = new String[lengths.length];
    for(int j = 0; j < squareStrs.length; j++)
    squareStrs[j] = nf.format(lengths[j] * lengths[j]);
    return squareStrs;
    private double[] getSideLengths()
    int[] x = triangle.xpoints;
    int[] y = triangle.ypoints;
    double[] lengths = new double[SIDES];
    for(int j = 0; j < SIDES; j++)
    int next = (j + 1) % SIDES;
    lengths[j] = Point.distance(x[j], y[j], x[next], y[next]);
    return lengths;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.text.NumberFormat;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.DefaultTableCellRenderer;
    * TriangleView.java
    * Created on 06 February 2005, 01:21
    public class TriangleView extends JPanel
    private TriangleModel model;
    private Polygon triangle;
    private JTable table;
    private JLabel centroidLabel;
    private boolean showConstruction;
    TriangleControl control;
    public TriangleView(TriangleModel model)
    this.model = model;
    triangle = model.getTriangle();
    showConstruction = false;
    control = new TriangleControl(this);
    addMouseListener(control);
    addMouseMotionListener(control);
    public void paintComponent(Graphics g)
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D)g;
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
    RenderingHints.VALUE_ANTIALIAS_ON);
    g2.draw(triangle);
    if(model.medians == null)
    centroidLabel.setText("centroid location: " + model.findCentroid());
    // draw medians and centroid point
    if(showConstruction && !control.dragging)
    g2.setPaint(Color.red);
    for(int j = 0; j < 3; j++)
    g2.draw(model.medians[j]);
    g2.setPaint(Color.blue);
    g2.fill(new Ellipse2D.Double(model.centroid.getX() - 2,
    model.centroid.getY() - 2, 4, 4));
    public TriangleModel getModel()
    return model;
    public JTable getTable()
    return table;
    public JLabel getCentroidLabel()
    return centroidLabel;
    public JPanel getUIPanel()
    JCheckBox showCon = new JCheckBox("show construction");
    showCon.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent e)
    boolean state = ((JCheckBox)e.getSource()).isSelected();
    showConstruction = state;
    repaint();
    JPanel panel = new JPanel();
    panel.add(showCon);
    return panel;
    public JPanel getTablePanel()
    String[] headers = new String[] { "", "", "", "" };
    // row and column data labels
    String[] rowHeaders = {
    "sides", "lengths", "squares", "angles", "degrees"
    String[] sidesRow = { "vertical", "horizontal", "hypotenuse" };
    String[] anglesRow = { "hyp to ver", "ver to hor", "hor to hyp" };
    // collect data from model
    String[] angles = model.getAngles();
    String[] lengths = model.getLengths();
    String[] squares = model.getSquares();
    String[][] allData = { sidesRow, lengths, squares, anglesRow, angles };
    int rows = 5;
    int cols = 4;
    Object[][] data = new Object[rows][cols];
    for(int row = 0; row < rows; row++)
    data[row][0] = rowHeaders[row];
    for(int col = 1; col < cols; col++)
    data[row][col] = allData[row][col - 1];
    table = new JTable(data, headers)
    public boolean isCellEditable(int row, int col)
    return false;
    DefaultTableCellRenderer renderer =
    (DefaultTableCellRenderer)table.getDefaultRenderer(String.class);
    renderer.setHorizontalAlignment(JLabel.CENTER);
    centroidLabel = new JLabel("centroid location: ", JLabel.CENTER);
    Dimension d = centroidLabel.getPreferredSize();
    d.height = table.getRowHeight();
    centroidLabel.setPreferredSize(d);
    JPanel panel = new JPanel(new BorderLayout());
    panel.setBorder(BorderFactory.createTitledBorder("triangle data"));
    panel.add(table);
    panel.add(centroidLabel, "South");
    return panel;
    PLEASE HELP ME TO LABEL THE TRIANGLE AND CHANGE THE VALUES OF THE JTABLE - to SHOW ASquare b Square and C square as well as a label on the bottom of the screen to show A^2 + B^2 = C^2 ...
    ThANKS

  • Generalpath

    could someone please help me with this program. I have to randomly draw triangles. I have pasted my code and it draws one triangle. I know I should use math.random but I dont know how. can someone should me how to write it in.
    thanks
    i
    ps I love this site. it has really been a great help to me, but sometimes I am not able to sign in. Is there a problem. does it only allow so many people to be signed in at one time?

    I don't know anything about general path... but I do know when dealing with random positions for drawing, most people use the int type. This little example should get you started a bit:
    import java.applet.*;
    import java.awt.*;
    // <applet code="Example.class" width=300 height=300></applet>
    public class Example extends Applet {
         Polygon[] tri; // triangles
         int[] xp, yp; // points
         int x,y,size; // position and size
         public void init() {
              tri = new Polygon[3]; // 3 triangles
              size = 20; // triangle size 20
         public void start() {
              for (int j = 0;j < tri.length;j++) { // for each triangle
                   x = (int)Math.round(Math.random()*(getSize().width-size)); // random X position
                   y = (int)Math.round(Math.random()*(getSize().height-size)); // random Y position
                   xp = new int[] {x+size/2,x,x+size,x+size/2}; // triangle X points
                   yp = new int[] {y,y+size,y+size,y}; // triangle Y points
                   tri[j] = new Polygon(xp,yp,xp.length); // make triangle
         public void paint(Graphics g) {
              Color[] random = new Color[]
              { // random colors for fun
                   Color.red,Color.green,Color.blue,
                   Color.orange,Color.yellow,Color.cyan,
                   Color.magenta
              for (int j = 0;j < tri.length;j++) {
                   g.setColor(random[(int)Math.round(Math.random()*(random.length-1))]); // random color
                   g.fillPolygon(tri[j]); // show triangle
    }Hope it helps.

  • Obfuscation error

    Hi,
    When i set obfuscation level off or high, i build successfully.
    But when i set obfuscation level from 1 to 8, i build fail.
    I want to set obfuscation level about 5-6 for an j2me midlet.
    Netbeans 6.5 show error information when obfuscation fail:
    Unexpected error while computing stack sizes:
    Class = [org/netbeans/microedition/lcdui/TableItem]
    Method = [paint(Ljavax/microedition/lcdui/Graphics;II)V]
    Exception = [java.lang.IllegalArgumentException] (Stack size becomes negative after instruction [126] ificmpge +6 (target=132) in [org/netbeans/microedition/lcdui/TableItem.paint(Ljavax/microedition/lcdui/Graphics;II)V])
    Error: Stack size becomes negative after instruction [126] ificmpge +6 (target=132) in [org/netbeans/microedition/lcdui/TableItem.paint(Ljavax/microedition/lcdui/Graphics;II)V]
    Plz let me why and how to solve this trouble.
    Thanks and regards.

        private boolean paintValues(Graphics g, int width, int y){
            boolean rightmostColumnFullyVisible = true;
            g.setColor(getColorSchema().getColor(Display.COLOR_FOREGROUND));
            g.setFont(getValuesFont());
            for (int i=0; (i < model.getRowCount()); i++) {
                int x = BORDER_LINE_WIDTH + CELL_PADDING;
                int gy = y + CELL_PADDING + BORDER_LINE_WIDTH; // actual y used to be draw the text (icludes padding)
                for (int j=viewCellX; j < model.getColumnCount(); j++) {
                    viewCellX2 = j;
                    Object value = model.getValue(j,i);
                    if (value != null) {
                        if ( cursorOn && (j==cursorCellX) && (i == cursorCellY)) {
                            g.setColor(getColorSchema().getColor(Display.COLOR_HIGHLIGHTED_FOREGROUND));
                            g.drawString(value.toString(), x, gy, Graphics.TOP | Graphics.LEFT);
                            g.setColor(getColorSchema().getColor(Display.COLOR_FOREGROUND));
                        } else {
                            g.drawString(value.toString(), x, gy, Graphics.TOP | Graphics.LEFT);
                    x += colWidths[j] + BORDER_LINE_WIDTH;
                    if (x > width) {
                        rightmostColumnFullyVisible = false;
                        break;
                y += defaultCellHeight + BORDER_LINE_WIDTH;
            return rightmostColumnFullyVisible;
        private int paintBorders(Graphics g, int titleHeight, int headersHeight, boolean rightmostColumnFullyVisible, int paintWidth, int width){
             int actualTableWidth = paintWidth;
             g.setColor(getColorSchema().getColor(Display.COLOR_BORDER));
             int currentStrokeStyle = g.getStrokeStyle();
             g.setStrokeStyle(display.getBorderStyle(false));
             int y = titleHeight;
             int totalTableHeight = tableRows * (defaultCellHeight + BORDER_LINE_WIDTH) + titleHeight; // total totalTableHeight
             if (usingHeaders) {
                 totalTableHeight += headersHeight + BORDER_LINE_WIDTH; // add it to total table height
             // vertical lines
             int x = 0;
             for (int i = viewCellX; (i < tableCols) && (x < width); i++) {
                 x += colWidths[i] + BORDER_LINE_WIDTH;
                 g.drawLine(x, titleHeight, x, totalTableHeight);
                 actualTableWidth = x; // getting value of the leftmost table line - out actualTableWidth
             if ((titleHeight > 0) && rightmostColumnFullyVisible) {
                 g.drawLine(x, 0, x, titleHeight);
             // horizontal lines
             // first line on the top
             g.drawLine(0, 0, actualTableWidth, 0);
             // draw header line
             if (usingHeaders) {
                 g.drawLine(0, y, actualTableWidth, y);
                 y += headersHeight + BORDER_LINE_WIDTH;
             // draw value lines
             for (int i = 0; (i <= tableRows) && (y <= totalTableHeight); i++, y += defaultCellHeight+BORDER_LINE_WIDTH) {
                 g.drawLine(0, y, actualTableWidth, y);
             // draw the remaining left and right line
             g.drawLine(0, 0,  0, totalTableHeight);     
             g.setStrokeStyle(currentStrokeStyle);
             return actualTableWidth;
        private void paintTitle(Graphics g, int titleHeight, boolean rightmostColumnFullyVisible, int actualTableWidth){
            g.setColor(getColorSchema().getColor(Display.COLOR_FOREGROUND));
            g.setFont(titleFont);
            // first is table title
            g.drawString(title, actualTableWidth/2, BORDER_LINE_WIDTH + CELL_PADDING, Graphics.TOP | Graphics.HCENTER);
            int half = titleHeight / 2;
            if (viewCellX > 0) {
                // draw triangle on the left
                g.drawLine(2, half, 5, half - 2);
                g.drawLine(2, half, 5, half + 2);
            if (! rightmostColumnFullyVisible) {
                // draw triangle on the right
                int rx = actualTableWidth - 2;
                g.drawLine(rx, half, rx - 3, half - 2);
                g.drawLine(rx, half, rx - 3, half + 2);
        }

  • Urgent, y does panel make my game disapear??

    Hi i have created a game whereby users click on the screen where a triangle apears corresponding to the location of the click. I have now added the panel functionality. When i display my game all i see is the
    Label titleLabel = new Label("THE TRIANGLE GAME!!!!!");
              Label textColourLabel = new Label("Select the colour you want your shapes to be");Which is displayed on the north, i.e the top.
    MainWindow() code
    MainWindow()
              setTitle("Drawing Triangles");
              m_bMouse = false;
              m_nTrianglesToDraw = 0;
              m_nTrianglesDrawn = 0;
              m_WndFont = new Font ("Helvetica", Font.BOLD, 20);
              m_polyTriangleArr = new Polygon[9];
              n = 3;
              setBackground(Color.yellow);
              Toolkit thisScreen = Toolkit.getDefaultToolkit();
              Dimension thisScreenSize = thisScreen.getScreenSize();
              m_nWndWidth = 2 * thisScreenSize.width / 3;
              m_nWndHeight = 2 * thisScreenSize.height / 3;
              setSize(m_nWndWidth, m_nWndHeight);
              Label titleLabel = new Label("THE TRIANGLE GAME!!!!!");
              Label textColourLabel = new Label("Select the colour you want your shapes to be");
              m_colour = new CheckboxGroup();
              m_red = new Checkbox("Red", m_colour, true);
              m_red.addItemListener(this);
              m_blue = new Checkbox("Blue", m_colour, false);
              m_blue.addItemListener(this);
              m_pink = new Checkbox("Pink", m_colour, false);
              m_pink.addItemListener(this);
              // Adding the panels
              Panel pTitle = new Panel();
              pTitle.add(titleLabel);
              Panel pButtons = new Panel();
              pButtons.add(m_red);
              pButtons.add(m_blue);
              pButtons.add(m_pink);
              Panel pRadioButtons = new Panel();
              pRadioButtons.add(textColourLabel);
              pRadioButtons.add(pButtons);
              // Create "Display Panel" for Radio Button to be placed in a panel with FlowLayout
              Panel pDisplayRadioButtons = new Panel();
              pDisplayRadioButtons.add(pRadioButtons);
              // Place pannel in appropriate area in a BorderLayout
              setLayout(new BorderLayout() );
              add(pTitle, BorderLayout.NORTH);
              add(pDisplayRadioButtons, BorderLayout.SOUTH);
              addKeyListener(new KeyCatcher() );
              addMouseListener(new MouseCatcher() );
              addWindowListener(new WindowCatcher() );
              setVisible(true);
         }Ideally, i would like to see the game with the available radio buttons at the bottoms, (south). Can som1 tell me why i am not able to see my game and how to resolve this.

    Sorry guys i have solved the problem.

  • Create another vertex buffer

    Hi, I have a problem with AGAL. If I create another vertex buffer, like this:
    _vertexBuffer = _context.createVertexBuffer(_cubeVertexes.length / 6, 6);
    _vertexBuffer.uploadFromVector(_cubeVertexes, 0, _cubeVertexes.length / 6);
    _context.setVertexBufferAt(0, _vertexBuffer, 0, Context3DVertexBufferFormat.FLOAT_3);
    _context.setVertexBufferAt(1, _vertexBuffer, 3, Context3DVertexBufferFormat.FLOAT_3);
    _vertexBuffer2 = _context.createVertexBuffer(_cubeVertexes2.length / 6, 6);
    _vertexBuffer2.uploadFromVector(_cubeVertexes2, 0, _cubeVertexes.length / 6);
    _context.setVertexBufferAt(2, _vertexBuffer2, 0, Context3DVertexBufferFormat.FLOAT_3);
    _context.setVertexBufferAt(3, _vertexBuffer2, 3, Context3DVertexBufferFormat.FLOAT_3);
    _indexBuffer = _context.createIndexBuffer(_cubeIndexes.length);
    _indexBuffer.uploadFromVector(_cubeIndexes, 0, _cubeIndexes.length);
    _indexBuffer2 = _context.createIndexBuffer(_cubeIndexes2.length);
    _indexBuffer2.uploadFromVector(_cubeIndexes2, 1, _cubeIndexes2.length);
    and set the shader as follows:
    protected var _vertexShader:String = [
          "m44 op, va0, vc0",  // multiply vertex by modelViewProjection
          "mov v0, va1",        // copy the vertex color
         "m44 op, va2, vc1",
          "mov v1, va3"   
        ].join("\n");
        protected var _fragmentShader:String = [
          "mov oc, v0",  // output the fragment color
          "mov oc, v1"
        ].join("\n");
    the programme just display one vertex buffer's data on the screen. So I'm wondering how can I set the shader to display both vextex buffer's data?
    Many thanks!!!

    i am not sure about that (havent run any experiments) but i doubt the penalty will be that huge! Here is what happens when you call drawTriangles :
    There are 2 buffers front and back buffer when you make a call to the drawtriangles function it draws the triangles to the back buffer (so you could call it repeatedly in a loop to draw multiple 3d objects, correctly sorted, thanks to z buffering) and the moment you call the present() function it swaps the back buffer (the one the draw triangles function drew triangles too) with the front buffer (which was being displayed to the viewer while the drawtriangles function was drawing triangles to the back buffer) so now you would be viewing the back buffer while the front buffer will be used by draw triangles function in the next iteration to draw triangles too (a pretty old technique,  but a very effective one (its used in opengl, i think its glutswapbuffers or something in gl, i have done demo with quite a lot 3d objects (primitives but heavily tesselated) and get pretty good fps!) , the method is used to avoid flickering).
    Quick Note : when you are rendering multiple objects with different program3D make sure to null out the streams for example if program1 uses a texture and program2 does not, in this case you should null out the texture stream before you draw triangles using program2 like so : context3d.settextureat(0,null)....
    i have been burned by this many times. if you dont do it you will end up getting the message : "texture stream is set but not used by the fragment shader".

  • Reduce packaging and unused cables

    Can cisco introduce a product wide order code that means "do not ship the item with all the additional paper and console/aux cables". Often the boxes are opened and all the user manuals etc are not even looked at, they are just bined. I'm sure most large organisations have draws full of console/aux cables, so make it optional.
    Should be a no cost option to remove unwanted items.
    This may even help cisco meet there 2012 25% reduction in green house gas.

    Thank you for your prudent suggestion. Cisco's Global Supply management organization is focusing on addressing 5 main environmental "impactors" of the Cisco supply chain. More efficient packaging, accessory option elections and potential increase in use of recycled materials for packaging are being investigated. While many documentation requirements are mandated by regulation, Cisco is implementing documentation reduction where feasible. Information on goals and pilots are contained in Cisco's Annual Citizenship Reports, located in the Corporate Social Responsibility section at http://www.cisco.com/web/about/index.htmlhttp://www.cisco.com/web/about/index.html.

  • Need Help to Draw and Drag Triangle - URGENT

    Hi everyone - I am developing various proofs of the pythagora's theorem
    and the following code draws a triangle on screen and the proof follows -
    but i need to know how to drag the triangle such tht 1 angle is always set to 90 degrees.
    i.e. i need to resize the triangle by dragging its vertex points by which the1 angle remains at 90 no matter what the size.
    The proof has got some graphics code hardcoded in it - i.e. LINES AND POLYGONS have been hardcoded
    i need to reconfigure that such that everytime the user increases the size of the triagnle and clicks on next it draws the lines and polygons in the correct area and place
    PLEASE HELP
    the code is as follows
    MAIN CLASS
    import java.awt.BorderLayout;
    import java.awt.Container;
    import java.awt.*;
    import java.awt.event.*;
    import java.text.*;
    import javax.swing.*;
    public class TestProof {
        TestControl control;          // the controls for the visual proof
        TestView view;          // the drawing area to display proof
        // called upon class creation
        public TestProof() {
            view = new TestView();
    view.setBackground(Color.WHITE);
            control = new TestControl(view);
            Frame f = new Frame("Pythagoras");
            f.add(view,"Center");
            f.add(control,"South");
            f.setSize(600,600);
            f.setBackground(Color.lightGray);
            f.addMouseMotionListener(
            new MouseMotionListener() { //anonymous inner class
                //handle mouse drag event
                public void mouseMoved(MouseEvent e) {
                    System.out.println("Mouse  " + e.getX() +","  + e.getY());
                public void mouseDragged(MouseEvent e) {
                    System.out.println("Draggg: x=" + e.getX() + "; y=" + e.getY());
            JMenu File = new JMenu("File");
            JMenuItem Exit = new JMenuItem("Exit");
            Exit.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    ExitActionPerformed(evt);
            JMenuBar menuBar = new JMenuBar();
            menuBar.add(File);
       File.add(Exit);
            f.add(menuBar,"North");
            f.show();
        private JMenuBar getMenuBar() {
            JMenu File = new JMenu("File");
            JMenuItem Exit = new JMenuItem("Exit");
            Exit.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    ExitActionPerformed(evt);
            JMenuBar menuBar = new JMenuBar();
            menuBar.add(File);
                 File.add(Exit);   
            return menuBar;
        private void ExitActionPerformed(java.awt.event.ActionEvent evt) {
            // TODO add your handling code here:
            System.exit(0);
        // for standalone use
        public static void main(String args[]) {
      TestProof TP = new TestProof();
    }Test VIEW
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.text.*;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    public class TestView extends Canvas {
        int TRANSLUCENT = 1;
        int sequence;          // sequencer that determines what should be drawn
        // notes matter
        int noteX = 100;     // note coordinates
        int noteY = 60;
        int fontSize = 11;     // font size
        int lineSpacing     // space between two consecutive lines
        = fontSize + 2;
        Font noteFaceFont;     // font used to display notes
        // objects matter
        Polygon tri;          // right-angled triangle with sides A, B, and C
        Polygon tri1;
        Polygon sqrA;          // square with side of length A
        Polygon sqrB;          // square with side of length B
        Polygon sqrC;          // square with side of length C
        Polygon parA;          // parallelogram of base A and height A
        Polygon parB;          // parallelogram of base B and height B
        Polygon poly1;
        Polygon poly2;
        Polygon poly3;
        Polygon poly4;
        Polygon poly5;
        Polygon poly6;
        int X0 = 350;          // coordinates of triangle
        int Y0 = 350;
        int A = 90;//60;          // triangle size
        int B = 120;//80;
        int C = 150;//100;
        //CORDS of 2nd triangle
        int X1 = 350;
        int Y1 = 500;
        // notes: three lines per note
        String notes[] = {
            // note 0
            // note 1
            // note 2
            // note 3
            // note 4
            // note 5
            // note 6
            // note 7
            // note 8
            // note 9
            // note 10
            // note 11
            // note 12
            // note 13
            // note 14
        // constructor
        public TestView() {
            addMouseMotionListener(
            new MouseMotionListener() { //anonymous inner class
                //handle mouse drag event
                public void mouseMoved(MouseEvent e) {
                    System.out.println("Mouse  " + e.getX() +","  + e.getY());
                public void mouseDragged(MouseEvent e) {
                    System.out.println("Draggg: x=" + e.getX() + "; y=" + e.getY());
            // set font
            noteFaceFont = new Font("TimesRoman", Font.PLAIN, fontSize);
            // (coordinates specified w.r.t. to P0, unless otherwise specified)
            // create the triangle
            tri = new Polygon();
            tri.addPoint(0, 0);                    // add P0 coordinate
            tri.addPoint(A*A/C, -A*B/C);          // add A3 coordinate
            tri.addPoint(C, 0);                    // add C1 coordinate
            tri.translate(X0, Y0);               // place triangle
            tri1 = new Polygon();
            tri1.addPoint(0,0);                    // add P0 coordinate
            tri1.addPoint(A*A/C +38, +A*B/C);          // add A3 coordinate
            tri1.addPoint(C, 0);                    // add C1 coordinate
            tri1.translate(X1, Y1);
            // create square of side A
            sqrA = new Polygon();
            sqrA.addPoint(0, 0);               // add P0 coordinate
            sqrA.addPoint(-A*B/C, -A*A/C);          // add A1 coordinate
            sqrA.addPoint(-A*(B-A)/C, -A*(A+B)/C);     // add A2 coordinate
            sqrA.addPoint(A*A/C, -A*B/C);          // add A3 coordinate
            sqrA.translate(X0, Y0);               // place square
            // create square of side B
            // warning: the coordinate of this object are specified relative to C1
            sqrB = new Polygon();
            sqrB.addPoint(0, 0);               // add C1 coordinate
            sqrB.addPoint(B*A/C, -B*B/C);          // add B1 coordinate
            sqrB.addPoint(B*(A-B)/C, -B*(A+B)/C);     // add B2 coordinate
            sqrB.addPoint(-B*B/C, -B*A/C);          // add A3 coordinate
            sqrB.translate(X0 + C, Y0);               // place square
            // create square of side C
            sqrC = new Polygon();
            sqrC.addPoint(0, 0);               // add P0 coordinate
            sqrC.addPoint(C, 0);               // add C1 coordinate
            sqrC.addPoint(C, C);               // add C2 coordinate
            sqrC.addPoint(0, C);               // add C3 coordinate
            sqrC.translate(X0, Y0);               // place square
            poly1 = new Polygon();
            poly1.addPoint(405,279);
            poly1.addPoint(413,350);
            poly1.addPoint(432,500);
            poly1.addPoint(442,571);
            poly1.addPoint(500,500);
            poly1.addPoint(500,350);
            poly2 = new Polygon();
            poly2.addPoint(279,297);
            poly2.addPoint(404,280);
            poly2.addPoint(571,254);
            poly2.addPoint(500,350);
            poly2.addPoint(350,350);
            //Polygon 3
            poly3 = new Polygon();
            poly3.addPoint(404,280);
            poly3.addPoint(350,350);
            poly3.addPoint(414,350);
            poly4 = new Polygon();
            poly4.addPoint(350,350);
            poly4.addPoint(350,500);
            poly4.addPoint(442,572);
            poly4.addPoint(433,500);
            poly4.addPoint(414,350);
            poly5 = new Polygon();
            poly5.addPoint(476,183);
            poly5.addPoint(332,225);
            poly5.addPoint(278,295);
            poly5.addPoint(404,279);
            poly5.addPoint(571,254);
            poly6= new Polygon();
            poly6.addPoint(405,278);
            poly6.addPoint(332,224);
            poly6.addPoint(476,182);
            // create parallelogram of height A
            parA = new Polygon();
            parA.addPoint(0, 0);               // add P0 coordinate
            parA.addPoint(0, C);               // add C3 coordinate
            parA.addPoint(A*A/C, C - A*B/C);          // add Q0 coordinate
            parA.addPoint(A*A/C, -A*B/C);          // add A3 coordinate
            parA.translate(X0,Y0);               // place parallelogram
            // create parallelogram of height B
            // warning: the coordinate of this object are specified from C1
            parB = new Polygon();
            parB.addPoint(0, 0);               // add C1 coordinate
            parB.addPoint(-B*B/C, -B*A/C);          // add A3 coordinate
            parB.addPoint(A*A/C - C, C - A*B/C);     // add Q0 coordinate
            parB.addPoint(0, C);               // add C2 coordinate
            parB.translate(X0 + C, Y0);
            // place parallelogram
        // depending on the sequence number we draw certain objects
        public void paint(Graphics gfx) {
            super.paint(gfx);
            Graphics2D g = (Graphics2D) gfx;
            g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
            RenderingHints.VALUE_ANTIALIAS_ON);
            // text first, then objects (and animation)
            // we always output some notes
            g.drawString(notes[3*sequence], noteX, noteY);
            g.drawString(notes[3*sequence + 1], noteX, noteY + lineSpacing);
            g.drawString(notes[3*sequence + 2], noteX, noteY + 2*lineSpacing);
            // the object are drawn in an order so that they are properly overlapped
            if(sequence == 13) {
                g.setColor(Color.green);
                g.fillPolygon(poly1);
                g.fillPolygon(poly2);
                g.fillPolygon(poly3);
                g.fillPolygon(poly4);
                g.fillPolygon(poly5);
                g.setColor(Color.RED);
                g.setColor(Color.GREEN);
                g.drawLine(413,351,433,499);
                g.setColor(Color.white);
                g.fillPolygon(tri);
                g.fillPolygon(tri1);
                g.fillPolygon(poly6);
            if(sequence == 12 ) {
                g.setColor(Color.green);
                g.fillPolygon(poly1);
                g.fillPolygon(poly2);
                g.fillPolygon(poly3);
                g.fillPolygon(poly4);
                g.fillPolygon(poly5);
                g.setColor(Color.BLACK);
            if(sequence == 11){
                g.setColor(Color.green);
                g.fillPolygon(poly1);
                g.fillPolygon(poly3);
                g.fillPolygon(poly4);
                g.setColor(Color.BLACK);
            if(sequence == 8 ){
                g.setColor(Color.green);
                g.fillPolygon(poly5);
                g.setColor(Color.MAGENTA);
                g.drawString("E",578,254);
                g.drawString("D",268,302);
                g.setColor(Color.black);
                g.drawArc(250,150,350,250,320,65);
            else if (sequence == 9 ){
                g.setColor(Color.green);
                g.fillPolygon(poly2);
                g.setColor(Color.MAGENTA);
                g.drawString("E",578,254);
                g.drawString("D",268,302);
                g.setColor(Color.black);
                g.drawArc(250,150,350,250,320,65);
            if( sequence == 10){
                g.setColor(Color.green);
                g.fillPolygon(poly2);
                g.fillPolygon(poly5);
                g.setColor(Color.black);
                g.setColor(Color.MAGENTA);
                g.drawString("E",578,254);
                g.drawString("D",268,302);
                g.setColor(Color.black);
                g.drawArc(250,150,350,250,320,65);
            if(sequence == 7){
                g.setColor(Color.green);
                g.fillPolygon(poly2);
                g.setColor(Color.MAGENTA);
                g.drawString("E",578,254);
                g.drawString("D",268,302);
                g.setColor(Color.black);
            if(sequence == 6){
                g.setColor(Color.yellow);
                g.fillPolygon(poly2);
                g.setColor(Color.green);
                g.fillPolygon(poly3);
                g.setColor(Color.blue);
                g.fillPolygon(poly4);
                g.setColor(Color.black);
                g.drawArc(250,175,350,275,300,65);
                //g.drawArc(250,150,350,250,320,65);
                g.drawLine( 606,309,599,299);
                g.drawLine(592,313, 599,299);
                g.drawString("+90 degrees",605,378);
            if (sequence == 5 ) {
                g.setColor(Color.yellow);
                g.fillPolygon(poly2);
                g.setColor(Color.black);
            if (sequence == 4) {
                g.setColor(Color.YELLOW);
                g.fillPolygon(poly1);
                g.setColor(Color.black);
                g.drawArc(319,310,250,195,89,-35);
                g.drawLine(499,319, 492,312);
                g.drawLine(499,319, 492,325);
                g.drawArc(200,180, 233,238,-120,-60);
                g.drawLine(200,298, 208,309);
                g.drawLine(200,298, 194,313);
                g.drawString("-90 degrees",227,347);
            if (sequence >= 3) {
                g.drawLine(404,279,442,572);
            // draw the squares
            if (sequence >= 2) {
                g.drawLine(278,296,572,254);
            // draw the squares
            if (sequence >= 1) {
                g.drawLine(333,224,476,182);
                g.drawPolygon(tri1);
            // always draw the triangle
            g.drawPolygon(tri);
            g.drawPolygon(sqrA);
            g.drawPolygon(sqrB);
            g.drawPolygon(sqrC);
            g.setColor(Color.MAGENTA);
            g.drawString("C", X0 + C/2 - fontSize/2, Y0 + lineSpacing);
            g.drawString("A",
            X0 + A*A/(2*C) - fontSize*A/B/2,
            Y0 - A*B/(2*C) - lineSpacing*A/B);
            g.drawString("B",
            X0 + C - B*B/(2*C) - fontSize*A/B/2,// the last "-" isn't log.
            Y0 - B*A/(2*C) - lineSpacing*A/B);
        public void redraw(int sequence) {
            this.sequence = sequence;
            repaint();
    }TEST CONTROL
    * TestControl.java
    * Created on 28 February 2005, 11:16
    import java.awt.*;
    import java.awt.event.*;
    import java.text.*;
    import javax.swing.JFrame;
    * @author  Kripa Bhojwani
    public class TestControl extends Panel implements ActionListener {
      TestView view;
      int sequence;                    // event sequence
      // constructor
      public TestControl(TestView view) {
        Button b = null;
        Label label = new Label("A^2 ");
        this.view = view;          // initialize drawble area
        sequence = 0;               // initialize sequence
        b = new Button("Prev");
        b.addActionListener(this);
        add(b);
        b = new Button("Next");
        b.addActionListener(this);
        add(b);
        add(label);
      // exported method
      public void actionPerformed(ActionEvent ev) {
        String label = ev.getActionCommand();
        if (label.equals("Prev")) {
          if (sequence >0) {
         --sequence;
        else {
          if (sequence < 15) {
         ++sequence;
        this.setEnabled(false);          // disable the controls
        view.redraw(sequence);
        this.setEnabled(true);          // enable the controls
    }Please help --- really need to sort this out...
    THANKS

    One of the problems you face is that it is hard to recognise which parts of your code are drawing the triangle. This is because you are writing code in a procedural way rather than an object oriented way.
    In object oriented code you would have a triangle object that could draw itself. You would create the triangle object by specifying its sizes and angles in some way. Then it should be easy to change the triangles sizes and angles and ask all the drawn objects to redraw themselves.

Maybe you are looking for