EXIT_ON_CLOSE

Hi friends....
im new to java....on execting my first program im really stuck up in this command EXIT_ON_CLOSE
wenever i comple...the error is "undefined variable EXIT_ON_CLOSE"....did i need to include any header files here?????
public static void main(String args[])
JFrame frameObject=new JFrame("customer");
frameObject.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frameObject.setVisible(true);
frameObject.setSize(300,300);
public Customer()
panelObject= new JPanel();
frameObject.getContentPane().add(panelObject);
frameObject.setDefaultCloseOperation(EXIT_ONCLOSE);
cust=new JLabel("customet name");
tcust= new JTextField(30);
panelObject.add(cust);
panelObject.add(tcust);
}

As i had already send you the corrected code. I hope you had read the
response earlier sent.
Sent Before
As you are new to java, i am sending you the corrected code.
The problem in your code is
1. The frameObject you are creating is part of the main method. which will not be accessible to your Customer class.
2. the value you are setting to frameObject.setDefaultCloseOperation(EXIT_ONCLOSE) is not correct.
Below is the corrected code. have a look and try to identify the difference.
Corrected code:
public static void main(String args[]) {
new Customer();
public Customer() {
JFrame frameObject = new JFrame("customer");
frameObject.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panelObject = new JPanel();
frameObject.getContentPane().add(panelObject);
JLabel cust = new JLabel("customet name");
JTextField tcust = new JTextField(30);
panelObject.add(cust);
panelObject.add(tcust);
frameObject.setVisible(true);
frameObject.setSize(300, 300);
null

Similar Messages

  • EXIT_ON_CLOSE doesn't work with JDialog

    Is there a way to make the frame exit without having to use the killer statement "System.exit(0)"?
    The code below should work but doesn't!
    import javax.swing.JDialog;
    public class ExitOnCloseProblem extends JDialog {
         public static void main(String args[]) {
              ExitOnCloseProblem me = null;
              me = new ExitOnCloseProblem();
              me.setDefaultCloseOperation(JDialog.EXIT_ON_CLOSE);
              me.show();
    }When extending JFrame instead of JDialog and using JFrame.EXIT_ON_CLOSE, it works!
    But I need JDialog.

    Try
    import javax.swing.JDialog;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    public class ExitOnCloseProblem extends JDialog {
        public static void main(String args[]) {
         final ExitOnCloseProblem me = new ExitOnCloseProblem();
         me.addWindowListener(new WindowAdapter() {
              public void windowClosing(WindowEvent we) {
                  me.hide();
                  me.dispose();
                  me.getOwner().dispose();
         me.show();
    }When you read the API documentation for JDialog it says that a shared, hidden
    frame is set as the owner of this dialog - and you have to 'destroy' that one
    as well.
    HTH
    Cheers,
    Torsten
    PS: this is a simplified version of what you would actually do (therefore the
    'final ExitOnCloseProblem me' stuff). Usually you would do a
    WindowEvent.getSource(), cast it to JDialog and then hide() and dispose() all
    the relevant things.

  • EXIT_ON_CLOSE problem

    I get this message when I compile my file:
    C:\jdk1.2.2\textproperties\TextFrame.java:14: No variable EXIT_ON_CLOSE defined in class javax.swing.JFrame.tf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    I am new to java programming but I thought EXIT_ON_CLOSE is a constant with return type int in class JFrame. Why am I getting this msg?
    Any help would be appreciated.

    It is defined there. You'll have to post the relevant part of your code so we can see what the actual cause of the problem is.

  • EXIT_ON_CLOSE for one window

    Hi,
    I'm creating a program which has a menu with a menuItem that says "Settings". If I click on the menuItem a new window opens where you are supposed to be able to make a couple of settings for the program. All that stuff works just fine but there is one thing that doesn't. When I close the settings window, the entire program shuts down. How do I get the program to close the settings window only?
    Thanks a lot!
    Karl-Johan

    Don't use EXIT_ON_CLOSE.
    Read the API. You will find other values that you can use for the default close operation method.

  • Executing code on EXIT_ON_CLOSE

    I was wondering how you execute code when a JFrame closes using the X button (ie, without using a menu). Because you don't attach an ActionListener to it, I am unsure as to where I would place code that I would like to execute before the program exits.
    Thanks

    add a WindowListener to the JFrame; windowClosing() will be called when the X is clicked (setDefaultAction is more or less just a convenience method for this)

  • Problem with threads in my swing application

    Hi,
    I have some problem in running my swing app. Thre problem is related to threads.
    What i am developing, is a gui framework where i can add different pluggable components to the framework.
    The framework is working fine, but when i press the close action then the gui should close down the present component which is active. The close action is of the framework and the component has the responsibility of checking if it's work is saved or not and hence to throw a message for saving the work, therefore, what i have done is that i call the close method for the component in a separate thread and from my main thread i call the join method for the component's thread.But after join the whole gui hangs.
    I think after the join method even the GUI thread , which is started for every gui, also waits for the component's thread to finish but the component thread can't finish because the gui thread is also waiting for the component to finish. This creates a deadlock situation.
    I dont know wht's happening it's purely my guess.
    One more thing. Why i am calling the component through a different thread, is because , if the component's work is not saved by the user then it must throw a message to save the work. If i continue this message throwing in my main thread only then the main thread doesnt wait for user press of the yes no or cancel button for saving the work . It immediately progresses to the next statement.
    Can anybody help me get out of this?
    Regards,
    amazing_java

    For my original bad thread version, I have rewritten it mimicking javax.swing.Timer
    implementation, reducing average CPU usage to 2 - 3%.
    Will you try this:
    import javax.swing.*;
    import java.awt.*;
    import java.text.*;
    import java.util.*;
    public class SamurayClockW{
      JFrame frame;
      Container con;
      ClockTextFieldW ctf;
      public SamurayClockW(){
        frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        con = frame.getContentPane();
        ctf = new ClockTextFieldW();
        con.add(ctf, BorderLayout.SOUTH);
        frame.setBounds(100, 100, 300, 300);
        frame.setVisible(true);
        ctf.start();
      public static void main(String[] args){
        new SamurayClockW();
    class ClockTextFieldW extends JTextField implements Runnable{
      String clock;
      boolean running;
      public ClockTextFieldW(){
        setEditable(false);
        setHorizontalAlignment(RIGHT);
      public synchronized void start(){
        running = true;
        Thread t = new Thread(this);
        t.start();
      public synchronized void stop(){
        running = false;
      public synchronized void run(){
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        try{
          while (running){
            clock = sdf.format(new Date());
            SwingUtilities.invokeLater(new Runnable(){
              public void run(){
                setText(clock);
            try{
              wait(1000);
            catch (InterruptedException ie){
              ie.printStackTrace();
        catch (ThreadDeath td){
          running = false;
    }

  • Problem with threads in JFrame

    Hy everyone...i have a small problem when i try to insert clock in my JFrame , because all i get is an empty text field.
    What i do is that i create inner class that extends Thread and implements Runnable , but i dont know ... i saw some examples on the intrnet...but they are all for Applets...
    Does any one know how i can implement this in JFrame (JTextField in JFrame).
    Actually any material on threads in JFrame or JPanel would be great....THNX.

    For my original bad thread version, I have rewritten it mimicking javax.swing.Timer
    implementation, reducing average CPU usage to 2 - 3%.
    Will you try this:
    import javax.swing.*;
    import java.awt.*;
    import java.text.*;
    import java.util.*;
    public class SamurayClockW{
      JFrame frame;
      Container con;
      ClockTextFieldW ctf;
      public SamurayClockW(){
        frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        con = frame.getContentPane();
        ctf = new ClockTextFieldW();
        con.add(ctf, BorderLayout.SOUTH);
        frame.setBounds(100, 100, 300, 300);
        frame.setVisible(true);
        ctf.start();
      public static void main(String[] args){
        new SamurayClockW();
    class ClockTextFieldW extends JTextField implements Runnable{
      String clock;
      boolean running;
      public ClockTextFieldW(){
        setEditable(false);
        setHorizontalAlignment(RIGHT);
      public synchronized void start(){
        running = true;
        Thread t = new Thread(this);
        t.start();
      public synchronized void stop(){
        running = false;
      public synchronized void run(){
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        try{
          while (running){
            clock = sdf.format(new Date());
            SwingUtilities.invokeLater(new Runnable(){
              public void run(){
                setText(clock);
            try{
              wait(1000);
            catch (InterruptedException ie){
              ie.printStackTrace();
        catch (ThreadDeath td){
          running = false;
    }

  • 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

  • How to find a point lies inside circle

    Hi,
    How do I find a point (x,y) is lies inside a circle? I trying to do a small shooting game.
    If the user clicks inside the circle they get a point. I am using the Pythagoras theorem to achieve this. But I can't.
    Please advice me.
    Here is my code
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class Shoot extends JFrame implements MouseListener, MouseMotionListener
        private int winWidth = 300;
        private int winHeight = 300;
        private MyCanvas canvas = null;
        private int ballX = 50;
        private int ballY = 50;
        private int ballW = 50;
        private int ballH = 50;
        private int ballR = ballW / 2;
        private int curX = 0;
        private int curY = 0;
        private int left = 0;
        private int top = 0;
        public Shoot()
            Cursor c = new Cursor(Cursor.CROSSHAIR_CURSOR);
            this.setCursor(c);
            canvas = new MyCanvas();
            packIt();
            left = getInsets().left;
            top = getInsets().top;
        private void packIt()
            setTitle("My first game!");
            setPreferredSize(new Dimension(winWidth, winHeight));
            setSize(new Dimension(winWidth, winHeight));
            setContentPane(canvas);
            addMouseListener(this);
            addMouseMotionListener(this);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //setUndecorated(true);
            setLocation(300, 0);
            setVisible(true);
        public void mouseClicked(MouseEvent e)
            int x = e.getX() - left - ballX;
            int y = e.getY() - top - ballY;
            int r = ballR;
            System.out.println("x :" + x + "\ty :" + y);
            //Trying to implememt Pythagoras theorem. But I am missing something.
            System.out.println(((x * x) + (y * y)) + "\t=\t" + (r * r));
            System.out.println();
        public void mousePressed(MouseEvent e)
        public void mouseReleased(MouseEvent e)
        public void mouseEntered(MouseEvent e)
        public void mouseExited(MouseEvent e)
        public void mouseDragged(MouseEvent e)
        public void mouseMoved(MouseEvent e)
            curX = e.getX() - left;
            curY = e.getY() - top;
            canvas.repaint();
        private class MyCanvas extends JPanel
            public MyCanvas()
                setBackground(Color.BLACK);
                setBorder(BorderFactory.createLineBorder(Color.yellow));
            public void paintComponent(Graphics g)
                super.paintComponent(g);
                g.setColor(Color.WHITE);
                g.drawString("x :" + curX, 10, 20);
                g.drawString("y :" + curY, 10, 30);
                g.setColor(Color.RED);
                g.fillOval(ballX, ballY, ballW, ballH);
        public static void main(String[] asd)
            new Shoot();
    }

    public boolean isPointInCircle(){
        double x= circle.getWidth/2.0+circle.getX();
        double y= circle.getHeight/2.0+circle.getY();
        double distance=getDistance(x,y,pointX,PointY);
        return (distance<= circle.getWidth/2.0); //if the distance from the point to the center of the circle is less than the radius of the circle return true
    double getDistance(double x1, double y1, double x2, double y2){
        return math.sqrt((x1-x2)(x1-x2) + (y1-y2)(y1-y2));
    }Edited by: ghostbust555 on Jan 23, 2011 3:20 PM

  • 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.

  • InternalFrame.setNorthPane(null) and JDesktopPane outline drag mode

    package components;
    import javax.swing.JDesktopPane;
    import javax.swing.JMenu;
    import javax.swing.JMenuItem;
    import javax.swing.JMenuBar;
    import javax.swing.JFrame;
    import javax.swing.KeyStroke;
    import java.awt.event.*;
    import java.awt.*;
    import javax.swing.plaf.basic.BasicInternalFrameUI;
    * InternalFrameDemo.java requires:
    *   MyInternalFrame.java
    public class InternalFrameDemo extends JFrame
                                   implements ActionListener {
        JDesktopPane desktop;
        Point mouseCoord, windowCoord = new Point();
        public InternalFrameDemo() {
            super("InternalFrameDemo");
            //Make the big window be indented 50 pixels from each edge
            //of the screen.
            int inset = 50;
            Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
            setBounds(inset, inset,
                      screenSize.width  - inset*2,
                      screenSize.height - inset*2);
            //Set up the GUI.
            desktop = new JDesktopPane(); //a specialized layered pane
            createFrame(); //create first "window"
            setContentPane(desktop);
            setJMenuBar(createMenuBar());
            //Make dragging a little faster but perhaps uglier.
            desktop.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
        protected JMenuBar createMenuBar() {
            JMenuBar menuBar = new JMenuBar();
            //Set up the lone menu.
            JMenu menu = new JMenu("Document");
            menu.setMnemonic(KeyEvent.VK_D);
            menuBar.add(menu);
            //Set up the first menu item.
            JMenuItem menuItem = new JMenuItem("New");
            menuItem.setMnemonic(KeyEvent.VK_N);
            menuItem.setAccelerator(KeyStroke.getKeyStroke(
                    KeyEvent.VK_N, ActionEvent.ALT_MASK));
            menuItem.setActionCommand("new");
            menuItem.addActionListener(this);
            menu.add(menuItem);
            //Set up the second menu item.
            menuItem = new JMenuItem("Quit");
            menuItem.setMnemonic(KeyEvent.VK_Q);
            menuItem.setAccelerator(KeyStroke.getKeyStroke(
                    KeyEvent.VK_Q, ActionEvent.ALT_MASK));
            menuItem.setActionCommand("quit");
            menuItem.addActionListener(this);
            menu.add(menuItem);
            return menuBar;
        //React to menu selections.
        public void actionPerformed(ActionEvent e) {
            if ("new".equals(e.getActionCommand())) { //new
                createFrame();
            } else { //quit
                quit();
        //Create a new internal frame.
        protected void createFrame() {
            final MyInternalFrame frame = new MyInternalFrame();
            ((BasicInternalFrameUI) frame.getUI()).setNorthPane(null);   
            frame.setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR));   
            frame.addMouseMotionListener(new MouseMotionAdapter() {
                public void mouseDragged(MouseEvent e) {  
                    isMouse2Move(frame, e);               
            frame.addMouseListener(new MouseAdapter() {          
                public void mousePressed(MouseEvent e) {                                                 
                    setWindowDragPoint(e);              
            frame.setVisible(true); //necessary as of 1.3
            desktop.add(frame);
            try {
                frame.setSelected(true);
            } catch (java.beans.PropertyVetoException e) {}
        private void isMouse2Move(Component frame, MouseEvent e) {
            int cur_type = frame.getCursor().getType();   
            if (cur_type >= Cursor.DEFAULT_CURSOR) {
                if (cur_type == Cursor.MOVE_CURSOR) {
                    moveWindow(frame, e);                       
        private void moveWindow(Component frame, MouseEvent e) {
            int deltaX, deltaY;
            Point newMouseCoord = e.getPoint();
            deltaX = (int) (newMouseCoord.getX() - mouseCoord.getX());
            deltaY = (int) (newMouseCoord.getY() - mouseCoord.getY());
            frame.getLocation(windowCoord);
            windowCoord.translate(deltaX, deltaY);
            frame.setLocation(windowCoord);
        private void setWindowDragPoint(MouseEvent e) {
            mouseCoord = e.getPoint();
        //Quit the application.
        protected void quit() {
            System.exit(0);
         * Create the GUI and show it.  For thread safety,
         * this method should be invoked from the
         * event-dispatching thread.
        private static void createAndShowGUI() {
            //Make sure we have nice window decorations.
            JFrame.setDefaultLookAndFeelDecorated(true);
            //Create and set up the window.
            InternalFrameDemo frame = new InternalFrameDemo();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //Display the window.
            frame.setVisible(true);
        public static void main(String[] args) {
            //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
    package components;
    import javax.swing.JInternalFrame;
    import java.awt.event.*;
    import java.awt.*;
    /* Used by InternalFrameDemo.java. */
    public class MyInternalFrame extends JInternalFrame {
        static int openFrameCount = 0;
        static final int xOffset = 30, yOffset = 30;
        public MyInternalFrame() {
            super("Document #" + (++openFrameCount),
                  true, //resizable
                  true, //closable
                  true, //maximizable
                  true);//iconifiable
            //...Create the GUI and put it in the window...
            //...Then set the window size or call pack...
            setSize(300,300);
            //Set the window's location.
            setLocation(xOffset*openFrameCount, yOffset*openFrameCount);
    }how to move frame (JDesktopPane) <desktop> can not enable drag outline mode..
    help me please!
    thank you.

    yes i want all the decorations.Then I have no idea what you are tying to do. Why are you getting rid of the title bar?
    Dragging is supported automatically by clicking on and then dragging the title bar. If you want to customize the behaviour then you would need to look at the UI. Good luck.

  • Method all values from row

    Hi,
    Is there a method that get the all the values of a row? I've gone through the java api but didn't found one, but wanted to be sure.
    If not I'll have to do getValueAt for every column?
    Grtz

    Here is one possible implementation using RowTableModel (a self made class).
    To access a row, we can use this: Product product = (Product) model.getRow(rowIndex);
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import java.util.List;
    public class Tabel extends JPanel {
        private JTable table;
        private JTextField filterText;
        private TableRowSorter<MyTableModel> sorter;
        private String output;
        private final MyTableModel model;
        public Tabel() {
            //Create a table with a sorter.
            model = new MyTableModel();
            sorter = new TableRowSorter<MyTableModel>(model);
            table = new JTable(model);
            table.setRowSorter(sorter);
            table.setPreferredScrollableViewportSize(new Dimension(500, 200));
            table.setFillsViewportHeight(true);
            //Single selection
            table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
            //Making sure columns can't be dragged and dropped
            table.getTableHeader().setReorderingAllowed(false);
            //Double click event
            table.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent mouseEvent) {
                    if (mouseEvent.getClickCount() == 2) {
                        System.out.print(output);
            //Create the scroll pane and add the table to it.
            JScrollPane scrollPane = new JScrollPane(table);
            //Add the scroll pane to this panel.
            add(scrollPane);
            JPanel form = new JPanel();
            JLabel l1 = new JLabel("Filter Text:");
            form.add(l1);
            filterText = new JTextField(15);
            //Whenever filterText changes, invoke newFilter.
            filterText.getDocument().addDocumentListener(
                    new DocumentListener() {
                        public void changedUpdate(DocumentEvent e) {
                            newFilter();
                        public void insertUpdate(DocumentEvent e) {
                            newFilter();
                        public void removeUpdate(DocumentEvent e) {
                            newFilter();
            l1.setLabelFor(filterText);
            form.add(filterText);
            add(form);
         * Update the row filter regular expression from the expression in
         * the text box.
        private void newFilter() {
            RowFilter<MyTableModel, Object> rf = null;
            //If current expression doesn't parse, don't update.
            try {
                rf = RowFilter.regexFilter("(?i)" + filterText.getText(), 0); //"(?i)" => Zoeken gebeurd case-insensitive
            } catch (java.util.regex.PatternSyntaxException e) {
                return;
            sorter.setRowFilter(rf);
        class MyTableModel extends RowTableModel {
            private final List<Product> mData;
            private final List<String> cNames;
            public MyTableModel() {
                super(Product.class);
                mData = new ArrayList<Product>();
                mData.add(new Product("Frontline Small", 5, 1));
                mData.add(new Product("Frontline Medium", 10, 2));
                mData.add(new Product("Frontline Large", 15, 1));
                mData.add(new Product("Frontline Extra Large", 20, 2));
                mData.add(new Product("Frontline spuitbus", 7.5, 3));
                cNames = new ArrayList<String>();
                cNames.add("Product");
                cNames.add("Prijs");
                cNames.add("Aantal stuks beschikbaar");
                setDataAndColumnNames(mData, cNames);
                setColumnClass(0, String.class);
                setColumnClass(1, Double.class);
                setColumnClass(2, Integer.class);
            public Object getValueAt(final int rowIndex, final int columnIndex) {
                switch (columnIndex) {
                    case 0:
                        return mData.get(rowIndex).getDescriction();
                    case 1:
                        return mData.get(rowIndex).getPrice();
                    case 2:
                        return mData.get(rowIndex).getNumber();
                return null;
            @Override
            public Class getColumnClass(int column) {
                return super.getColumnClass(column);
        private static void createAndShowGUI() {
            //Create and set up the window.
            JFrame frame = new JFrame();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //Create and set up the content pane.
            Tabel newContentPane = new Tabel();
            newContentPane.setOpaque(true); //content panes must be opaque
            frame.setContentPane(newContentPane);
            //Display the window.
            frame.pack();
            frame.setVisible(true);
        public static void main(final String[] args) {
            //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
    class Product {
        private String descriction;
        private double price;
        private int number;
        Product(final String descriction, final double price, final int number) {
            this.descriction = descriction;
            this.price = price;
            this.number = number;
        public String getDescriction() {
            return descriction;
        public void setDescriction(final String descriction) {
            this.descriction = descriction;
        public int getNumber() {
            return number;
        public void setNumber(final int number) {
            this.number = number;
        public double getPrice() {
            return price;
        public void setPrice(final int price) {
            this.price = price;
        @Override
        public String toString() {
            return descriction + ", " + price + ", " + number;
    }

  • Disabled JMenuItem doesn show animated gif

    Hi there
    I would like to have a popup menu with actions that are enabled after they have finished with some background task taking some time. Basically this works fine for the enabling action on a shown popup. However, adding an animated gif as the icon or disabled icon does not show it in disabled state. In enabled state it works perfect. Please have a try with the sample code. You should see the disabled item for 2 secs and the icon is not showing up. After being enabled, it does. Invoking the menu again shows the animated gif in its last state left, but not moving any more.
    I guess, repaints are not done appropriately in disabled state... Any ideas how to solve that would be highly appreciated :-)
    Actually I used the icon at http://mentalized.net/activity-indicators/indicators/pascal_germroth/indicator.white.gif
    Cheers
    Daniel
    public class Main
      public static void main(String[] args)
        final JFrame frame = new JFrame();
        frame.addMouseListener(new MouseAdapter()
          public void mousePressed(final MouseEvent e)
            final JPopupMenu popup = new JPopupMenu();
            popup.add(new JMenuItem("Open..."));
            popup.add(new JMenuItem("Close"));
            final JMenuItem action = new JMenuItem("Long loading until enabled");
            action.setIcon(new ImageIcon("C:/spinner.gif"));
            action.setDisabledIcon(new ImageIcon("C:/spinner.gif"));
            popup.add(action).setEnabled(false);
            popup.show(e.getComponent(), e.getX(), e.getY());
            SwingUtilities.invokeLater(new Runnable()
              public void run()
                try
                  Thread.sleep(2000);
                  action.setEnabled(true);
                catch (InterruptedException e1)
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(300, 200);
        frame.setVisible(true);
    }Edited by: daniel.frey on Apr 22, 2009 7:50 AM

    The problem is that you are causing the EDT to sleep, which means the GUI can't repaint itself. Read the section from the Swing tutorial on Concurrency to understand what is happening.

  • Resized animated gif ImageIcon not working properly with JButton etc.

    The problem is that when I resize an ImageIcon representing an animated gif and place it on a Jbutton, JToggelButton or JLabel, in some cases the image does not show or does not animate. More precicely, depending on the specific image file, the image shows always, most of the time or sometimes. Images which are susceptible to not showing often do not animate when showing. Moving over or clicking with the mouse on the AbstractButton instance while the frame is supposed to updated causes the image to disappear (even when viewing the non-animating image that sometimes appears). No errors are thrown.
    Here some example code: (compiled with Java 6.0 compliance)
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Test
         public static void main(String[] args)
              new Test();
         static final int  IMAGES        = 3;
         JButton[]           buttons       = new JButton[IMAGES];
         JButton             toggleButton  = new JButton("Toggle scaling");
         boolean            doScale       = true;
         public Test()
              JFrame f = new JFrame();
              f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              JPanel p = new JPanel(new GridLayout(1, IMAGES));
              for (int i = 0; i < IMAGES; i++)
                   p.add(this.buttons[i] = new JButton());
              f.add(p, BorderLayout.CENTER);
              f.add(this.toggleButton, BorderLayout.SOUTH);
              this.toggleButton.addActionListener(new ActionListener() {
                   @Override
                   public void actionPerformed(ActionEvent e)
                        Test.this.refresh();
              f.setSize(600, 300);
              f.setVisible(true);
              this.refresh();
         public void refresh()
              this.doScale = !this.doScale;
              for (int i = 0; i < IMAGES; i++)
                   ImageIcon image = new ImageIcon(i + ".gif");
                   if (this.doScale)
                        image = new ImageIcon(image.getImage().getScaledInstance(180, 180, Image.SCALE_AREA_AVERAGING));
                   image.setImageObserver(this.buttons);
                   this.buttons[i].setIcon(image);
                   this.buttons[i].setSelectedIcon(image);
                   this.buttons[i].setDisabledIcon(image);
                   this.buttons[i].setDisabledSelectedIcon(image);
                   this.buttons[i].setRolloverIcon(image);
                   this.buttons[i].setRolloverSelectedIcon(image);
                   this.buttons[i].setPressedIcon(image);
    Download the gif images here:
    http://djmadz.com/zombie/0.gif
    http://djmadz.com/zombie/1.gif
    http://djmadz.com/zombie/2.gif
    When you press the "Toggle scaling"button it switches between unresized (properly working) and resized instances of three of my gif images. Notice that the left image almost never appears, the middle image always, and the right image most of the time. The right image seems to (almost) never animate. When you click on the left image (when visble) it disappears only when the backend is updating the animation (between those two frames with a long delay)
    Why are the original ImageIcon and the resized ImageIcon behaving differently? Are they differently organized internally?
    Is there any chance my way of resizing might be wrong?

    It does work, however I refuse to use SCALE_REPLICATE for my application because resizing images is butt ugly, whether scaling up or down. Could there be a clue in the rescaling implementations, which I can override?
    Maybe is there a way that I can check if an image is a multi-frame animation and set the scaling algorithm accordingly?
    Message was edited by:
    Zom-B

Maybe you are looking for

  • Scanner error 6: HP LaserJet Pro 400 color MFP M475dw does not get through initialization phase

    My lJ400 MFP475 detects a problem with the scanner unit after chewing on it for several minutes and never finishes intitialization. Initially you can hear the scanner head move softly, but after less than a minute it starts rattling at the end of eve

  • HP LaserJet P2055dn Printer won't print the last page of documents & envelope problem

    My HP LaserJet P2055dn Printer won't print the last page of documents until i send another document, then it will print the last page of the previous document, but omit the last page of the current document.  I need to keep printing a blank page or a

  • Aperture 3.3.2 and Mountain Lion

    Aperture crashes in Mountain Lion when trying to do multiple processes.  I get multi windows, photos then have to reboot I re-installed Aperture 3.3.2 with updates, Still crashes when doing more then one thing. I have a macbook pro 15" 2.66 core 2 du

  • Snapshot boot with TuxOnIce?

    Hi, Is it possible to snapshot boot with TuxOnIce? That means, to have a image of booted system and "resume from hybernate" each time instead of normal booting. When i boot → open xterm → hybernate → resume (without anything opened), resuming takes a

  • STO PO default text

    Hi Guru's   I did all the config settings for default text for PO from vendor master, its works on NB type PO, when I create UB type STO i don't see the text defaulting, Is there any config I'am missing, is it possible for having a default text in ST