Results 1 to 12 of 12
  1. #1
    tyroceur's Avatar
    tyroceur is offline Member
    Join Date
    May 2010
    Location
    Fast Growing City, INDIA
    Posts
    44
    Rep Power
    0

    Unhappy I want to make graph in java swing without using any libraries

    Hello, I am trying to make a program using Java swings in which one can load coordinates from a text file and then plot a graph accordingly.

    I don't want to use the graph libraries but I don't know how to proceed on the drawing part. I am comfortable with the GUI interface but want help with the Graph functionality.

    I also want to implement scaling(zoom in/out from graph), move, set max/min range, select color of the line, turn grid off/on, display ticks on the axes and change axis labels.

    I have made the interface but I have really no idea how to go in the graph. I searched for it in the previous threads and I found a program to plot points made by hardwired (it helped me somewhat ) but can you please help me complete the other functionalities required?

    Here's the GUI code

    Java Code:
    import java.awt.BorderLayout;
    import java.awt.event.*;
    import javax.swing.*;
    import java.io.File;
    import javax.swing.filechooser.FileFilter;
    
    /**
     * 
     * @author 
     *
     */
    @SuppressWarnings("serial")
    public class MainWindow extends JFrame {
    
        /* setting look and feel of the interface */
        {
            try {
                javax.swing.UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        private JMenuBar menuBar;
        private JMenu menuFile;
        private JMenuItem itemOpen;
        private JMenuItem itemSave;
        private JMenuItem itemExit;
        private JMenu menuHelp;
        private JMenuItem itemHelp;
        private JMenuItem itemAbout;
        private JSplitPane splitPane;
        private JPanel setPanel;
        private Graph graph1;
        private JLabel labelSet;
        private JLabel labelZoom;
        private JSlider sliderZoom;
        private JButton buttonColor;
        private JToggleButton buttonGrid;
        private JLabel labelGraph;
        private JComboBox graphType;
        private JLabel labelLine;
        private JComboBox lineType;
        private JRadioButton scaleLin;
        private JRadioButton scaleLog;
    
        /**
         * MAIN
         */
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
    
                public void run() {
                    MainWindow inst = new MainWindow();
                    inst.setLocationRelativeTo(null);
                    inst.setVisible(true);
                }
            });
        }
    
        public MainWindow() {
            super();
            initGUI();
        }
    
        private void initGUI() {
            try {
                setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
                setTitle("Graph viewer");
                this.setMinimumSize(new java.awt.Dimension(750, 530));
    
                {
                    splitPane = new JSplitPane();
                    getContentPane().add(splitPane, BorderLayout.CENTER);
                    splitPane.setPreferredSize(new java.awt.Dimension(586, 375));
    
                    {
                        setPanel = new JPanel();
                        splitPane.add(setPanel, JSplitPane.RIGHT);
                        setPanel.setPreferredSize(new java.awt.Dimension(190, 505));
                        setPanel.setLayout(null);
                        setPanel.setMinimumSize(new java.awt.Dimension(190, 505));
    
                        {
                            labelSet = new JLabel();
                            setPanel.add(labelSet);
                            labelSet.setText("Settings");
                            labelSet.setBounds(114, 14, 74, 16);
                            labelSet.setFont(new java.awt.Font("Arial", 1, 14));
                        }
    
                        {
                            labelZoom = new JLabel();
                            setPanel.add(labelZoom);
                            labelZoom.setText("Zoom");
                            labelZoom.setBounds(26, 59, 32, 16);
                            labelZoom.setToolTipText("Zooms the graph");
                        }
    
                        {
                            sliderZoom = new JSlider();
                            setPanel.add(sliderZoom);
                            sliderZoom.setBounds(26, 73, 140, 21);
                        }
    
                        {
                            buttonColor = new JButton();
                            setPanel.add(buttonColor);
                            buttonColor.setText("Color");
                            buttonColor.setBounds(20, 112, 58, 28);
                            buttonColor.setToolTipText("Changes graph color");
    
                            buttonColor.addActionListener(new ActionListener() {
    
                                public void actionPerformed(ActionEvent evt) {
                                    buttonColorActionPerformed(evt);
                                }
                            });
                        }
    
                        {
                            buttonGrid = new JToggleButton();
                            setPanel.add(buttonGrid);
                            buttonGrid.setText("Grid on/off");
                            buttonGrid.setBounds(91, 112, 84, 28);
                            buttonGrid.setToolTipText("Turns on/off the grid");
                            buttonGrid.addActionListener(new ActionListener() {
    
                                public void actionPerformed(ActionEvent evt) {
                                    buttonGridActionPerformed(evt);
                                }
                            });
                        }
    
                        {	/*  */
                            labelGraph = new JLabel();
                            setPanel.add(labelGraph);
                            labelGraph.setText("Graph type:");
                            labelGraph.setBounds(20, 170, 77, 16);
                        }
    
                        {
                            ComboBoxModel graphTypeModel =
                                    new DefaultComboBoxModel(
                                    new String[]{"Line graph", "Bar graph", "Horizontal graph"});
                            graphType = new JComboBox();
                            setPanel.add(graphType);
                            graphType.setModel(graphTypeModel);
                            graphType.setBounds(32, 189, 134, 26);
                            graphType.setToolTipText("Changes the graph type");
                        }
    
                        {
                            labelLine = new JLabel();
                            setPanel.add(labelLine);
                            labelLine.setText("Line type:");
                            labelLine.setBounds(20, 230, 58, 16);
                        }
    
                        {
                            ComboBoxModel lineTypeModel =
                                    new DefaultComboBoxModel(
                                    new String[]{"Solid", "Dotted", "Dashed"});
                            lineType = new JComboBox();
                            setPanel.add(lineType);
                            lineType.setModel(lineTypeModel);
                            lineType.setBounds(32, 250, 134, 26);
                            lineType.setToolTipText("Changes the type of line");
                        }
    
                        {
                            scaleLin = new JRadioButton();
                            setPanel.add(scaleLin);
                            scaleLin.setText("Linear scale");
                            scaleLin.setBounds(32, 308, 90, 18);
                        }
    
                        {
                            scaleLog = new JRadioButton();
                            setPanel.add(scaleLog);
                            scaleLog.setText("Log scale");
                            scaleLog.setBounds(32, 333, 76, 18);
                        }
                    }
    
                    {
                        graph1 = new Graph();
                        splitPane.add(graph1, JSplitPane.LEFT);
                        graph1.setPreferredSize(new java.awt.Dimension(535, 473));
                        graph1.setFocusable(false);
                        graph1.setMinimumSize(new java.awt.Dimension(370, 473));
                    }
                }
    
                {
                    menuBar = new JMenuBar();
                    setJMenuBar(menuBar);
    
                    {
                        menuFile = new JMenu();
                        menuBar.add(menuFile);
                        menuFile.setText("File");
    
                        {
                            itemOpen = new JMenuItem();
                            menuFile.add(itemOpen);
                            itemOpen.setText("Open file");
                            itemOpen.addActionListener(new ActionListener() {
    
                                public void actionPerformed(ActionEvent evt) {
                                    itemOpenActionPerformed(evt);
                                }
                            });
                        }
    
                        {
                            itemSave = new JMenuItem();
                            menuFile.add(itemSave);
                            itemSave.setText("Save");
                        }
    
                        {
                            itemExit = new JMenuItem();
                            menuFile.add(itemExit);
                            itemExit.setText("Exit");
                            itemExit.addActionListener(new ActionListener() {
    
                                public void actionPerformed(ActionEvent evt) {
                                    itemExitActionPerformed(evt);
                                }
                            });
                        }
                    }
    
                    {
                        menuHelp = new JMenu();
                        menuBar.add(menuHelp);
                        menuHelp.setText("Help");
    
                        {
                            itemHelp = new JMenuItem();
                            menuHelp.add(itemHelp);
                            itemHelp.setText("Help");
                        }
    
                        {
                            itemAbout = new JMenuItem();
                            menuHelp.add(itemAbout);
                            itemAbout.setText("About");
                            itemAbout.addActionListener(new ActionListener() {
    
                                public void actionPerformed(ActionEvent evt) {
                                    itemAboutActionPerformed(evt);
                                }
                            });
                        }
                    }
                }
    
                pack();
                this.setSize(750, 530);
                pack();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
        /* OPEN FILE */
        private void itemOpenActionPerformed(java.awt.event.ActionEvent evt) {
            JFileChooser fc = new JFileChooser();
            fc.setCurrentDirectory(new File("."));
            fc.setFileFilter(new FileFilter() {
    
                public boolean accept(File f) {
                    return f.getName().toLowerCase().endsWith(".txt")
                            || f.getName().toLowerCase().endsWith(".xml")
                            || f.isDirectory();
                }
    
                public String getDescription() {
                    return "Data Files (*.txt, *.xml)";
                }
            });
    
            int returnVal = fc.showOpenDialog(MainWindow.this);
    
        }
    
        /* EXIT */
        private void itemExitActionPerformed(ActionEvent evt) {
            System.exit(0);
        }
    
        private void itemAboutActionPerformed(ActionEvent evt) {
            JOptionPane.showMessageDialog(null, "Graph viewer\n ", "About",
                    JOptionPane.PLAIN_MESSAGE);
        }
    
        private void buttonGridActionPerformed(ActionEvent evt) {
            // TODO add your handling code here:
        }
    
        private void buttonColorActionPerformed(ActionEvent evt) {
        }
    
        /**
         * This constructor is used by the getGUIBuilderInstance method to
         * provide an instance of this class which has not had it's GUI elements
         * initialized (ie, initGUI is not called in this constructor).
         */
        public MainWindow(Boolean initGUI) {
            super();
        }
    }
    The Graph class in the code is which I am having problem with and want help with it.

    Any help will be appreciated .... Thanks
    Last edited by tyroceur; 05-04-2010 at 10:24 PM.

  2. #2
    curmudgeon is offline Senior Member
    Join Date
    May 2010
    Posts
    436
    Rep Power
    5

    Default

    Quote Originally Posted by tyroceur View Post
    The Graph class in the code is which I am having problem with and want help with it.

    Any help will be appreciated .... Thanks
    What problems are you having? Specifically.

  3. #3
    tyroceur's Avatar
    tyroceur is offline Member
    Join Date
    May 2010
    Location
    Fast Growing City, INDIA
    Posts
    44
    Rep Power
    0

    Default

    I want to plot graphs but I don't know how to draw on swings. moreover, I want to implement scaling(zoom in/out from graph), move, set max/min range, select color of the line, turn grid off/on, display ticks on the axes and change axis labels.
    For which, I am just directionless....:(

  4. #4
    curmudgeon is offline Senior Member
    Join Date
    May 2010
    Posts
    436
    Rep Power
    5

    Default

    If the problem is that you are clueless (which is OK -- none of us are born with "Java Knowledge"), then borrowing code you don't understand probably won't help you much. And I doubt that anyone here has the time to lead you by the hand through the complex mine-field of learning this large and complex field. What you need to do is study the tutorials to gain a better understanding of Java graphics. The things you want to do are advanced graphics techniques and are not something you are going to be able to master in a day or a week, but with effort and ability, soon. So my advice is that you best get started studying.

    Buena suerte.
    Last edited by curmudgeon; 05-05-2010 at 04:37 AM.

  5. #5
    curmudgeon is offline Senior Member
    Join Date
    May 2010
    Posts
    436
    Rep Power
    5

    Default

    Here are some tutorials that have helped me:

    2D Graphics
    Custom Painting
    Painting in AWT and Swing

  6. #6
    tyroceur's Avatar
    tyroceur is offline Member
    Join Date
    May 2010
    Location
    Fast Growing City, INDIA
    Posts
    44
    Rep Power
    0

    Default

    Thanks....but can you please give me code for scaling, changing color etc. coz I have drawn the graph using the code I found

    Java Code:
    package example;
    
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.font.*;
    import java.awt.geom.*;
    import java.util.Random;
    import javax.swing.*;
    
    public class Plot2D {
    
        Random seed = new Random();
        final int SIZE = 8;
        final double MAX = 10.0;
        PlotPanel plotPanel;
    
        private double[] getData(double min, double max) {
            double[] d = new double[SIZE];
            for (int i = 0; i < SIZE; i++) {
                d[i] = min + seed.nextDouble() * (max - min);
                //System.out.printf("%5.1f ", d[i]);
            }
            //System.out.println();
            return d;
        }
    
        private JPanel getContent() {
            double[] x = getData(-MAX, MAX);
            double[] y = getData(-MAX, MAX);
            plotPanel = new PlotPanel(x, y);
            return plotPanel;
        }
    
        private JPanel getUIPanel() {
            JButton button = new JButton("change data");
            JRadioButton[] rbs = new JRadioButton[5];
            final ButtonGroup group = new ButtonGroup();
            button.addActionListener(new ActionListener() {
    
                public void actionPerformed(ActionEvent e) {
                    int index = Integer.parseInt(
                            group.getSelection().getActionCommand());
                    double xMin = -MAX, xMax = MAX, yMin = -MAX, yMax = MAX;
                    switch (index) {
                        case 0:
                            xMax = -5;
                            break;
                        case 1:
                            xMin = 5;
                            break;
                        case 2:
                            break;
                        case 3:
                            yMax = -5;
                            break;
                        case 4:
                            yMin = 5;
                    }
                    double[] x = getData(xMin, xMax);
                    double[] y = getData(yMin, yMax);
                    plotPanel.setData(x, y);
                }
            });
            JPanel panel = new JPanel(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            String minus = "<html>\u2013";
            String[] ids = {
                "<html>\u2013x", "+x", "<html>+/\u2013x&y", "<html>\u2013y", "+y"
            };
            for (int i = 0; i < rbs.length; i++) {
                rbs[i] = new JRadioButton(ids[i], i == 2);
                rbs[i].setActionCommand(String.valueOf(i));
                group.add(rbs[i]);
                panel.add(rbs[i], gbc);
            }
            panel.setBorder(BorderFactory.createEtchedBorder());
            gbc.weightx = 1.0;
            panel.add(button, gbc);
            return panel;
        }
    
        public static void main(String[] args) {
            Plot2D test = new Plot2D();
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.add(test.getContent());
            f.add(test.getUIPanel(), "Last");
            f.setSize(400, 400);
            f.setLocation(50, 50);
            f.setVisible(true);
        }
    }
    
    class PlotPanel extends JPanel {
    
        double[] x;
        double[] y;
        double xMin;
        double xMax;
        double yMin;
        double yMax;
        final int PAD = 20;
        final boolean DEBUG = false;
        boolean firstTime;  // Set at end of setData method.
    
        public PlotPanel(double[] x, double[] y) {
            setData(x, y);
        }
    
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D) g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                    RenderingHints.VALUE_ANTIALIAS_ON);
            int w = getWidth();
            int h = getHeight();
            double xScale = (w - 2 * PAD) / (xMax - xMin);
            double yScale = (h - 2 * PAD) / (yMax - yMin);
            if (firstTime) {
                System.out.printf("xScale = %.1f  yScale = %.1f%n",
                        xScale, yScale);
            }
            Point2D.Double origin = new Point2D.Double(); // Axes origin.
            Point2D.Double offset = new Point2D.Double(); // Locate data.
            if (xMax < 0) {
                origin.x = w - PAD;
                offset.x = origin.x - xScale * xMax;
            } else if (xMin < 0) {
                origin.x = PAD - xScale * xMin;
                offset.x = origin.x;
            } else {
                origin.x = PAD;
                offset.x = PAD - xScale * xMin;
            }
            if (yMax < 0) {
                origin.y = h - PAD;
                offset.y = origin.y - yScale * yMax;
            } else if (yMin < 0) {
                origin.y = PAD - yScale * yMin;
                offset.y = origin.y;
            } else {
                origin.y = PAD;
                offset.y = PAD - yScale * yMin;
            }
            if (firstTime) {
                System.out.printf("origin = [%6.1f, %6.1f]%n", origin.x, origin.y);
                System.out.printf("offset = [%6.1f, %6.1f]%n", offset.x, offset.y);
            }
    
            // Draw abcissa.
            g2.draw(new Line2D.Double(PAD, origin.y, w - PAD, origin.y));
            // Draw ordinate.
            g2.draw(new Line2D.Double(origin.x, PAD, origin.x, h - PAD));
            g2.setPaint(Color.red);
            // Mark origin.
            g2.fill(new Ellipse2D.Double(origin.x - 2, origin.y - 2, 4, 4));
    
            // Plot data.
            g2.setPaint(Color.blue);
            for (int i = 0; i < x.length; i++) {
                double x1 = offset.x + xScale * x[i];
                double y1 = offset.y + yScale * y[i];
                if (firstTime) {
                    System.out.printf("i = %d  x1 = %6.1f  y1 = %.1f%n", i, x1, y1);
                }
                g2.fill(new Ellipse2D.Double(x1 - 2, y1 - 2, 4, 4));
                g2.drawString(String.valueOf(i), (float) x1 + 3, (float) y1 - 3);
            }
    
            // Draw extreme data values.
            g2.setPaint(Color.black);
            Font font = g2.getFont();
            FontRenderContext frc = g2.getFontRenderContext();
            LineMetrics lm = font.getLineMetrics("0", frc);
            String s = String.format("%.1f", xMin);
            float width = (float) font.getStringBounds(s, frc).getWidth();
            double x = offset.x + xScale * xMin;
            g2.drawString(s, (float) x, (float) origin.y + lm.getAscent());
            s = String.format("%.1f", xMax);
            width = (float) font.getStringBounds(s, frc).getWidth();
            x = offset.x + xScale * xMax;
            g2.drawString(s, (float) x - width, (float) origin.y + lm.getAscent());
            s = String.format("%.1f", yMin);
            width = (float) font.getStringBounds(s, frc).getWidth();
            double y = offset.y + yScale * yMin;
            g2.drawString(s, (float) origin.x + 1, (float) y + lm.getAscent());
            s = String.format("%.1f", yMax);
            width = (float) font.getStringBounds(s, frc).getWidth();
            y = offset.y + yScale * yMax;
            g2.drawString(s, (float) origin.x + 1, (float) y);
            if (firstTime) {
                System.out.println("------------------------------");
            }
            firstTime = false;
        }
    
        public void setData(double[] x, double[] y) {
            if (x.length != y.length) {
                throw new IllegalArgumentException("x and y data arrays "
                        + "must be same length.");
            }
            this.x = x;
            this.y = y;
            double[] xVals = getExtremeValues(x);
            xMin = xVals[0];
            xMax = xVals[1];
            if (DEBUG) {
                System.out.printf("xMin = %5.1f  xMax = %5.1f%n", xMin, xMax);
            }
            double[] yVals = getExtremeValues(y);
            yMin = yVals[0];
            yMax = yVals[1];
            if (DEBUG) {
                System.out.printf("yMin = %5.1f  yMax = %5.1f%n", yMin, yMax);
            }
            firstTime = DEBUG;
            repaint();
        }
    
        private double[] getExtremeValues(double[] d) {
            double min = Double.MAX_VALUE;
            double max = -min;
            for (int i = 0; i < d.length; i++) {
                if (d[i] < min) {
                    min = d[i];
                }
                if (d[i] > max) {
                    max = d[i];
                }
            }
            return new double[]{min, max};
        }
    }
    but I don't know how do i like do those changes in the graph from the interface I have created..
    Can you please provide me code to change the color or range when i click on a button in my interface... thanks

  7. #7
    curmudgeon is offline Senior Member
    Join Date
    May 2010
    Posts
    436
    Rep Power
    5

    Default

    I tell you, I'm against "giving the code" here and posts like Hardwire's just for this reason. Folks get the code but they don't get the understanding. Besides, it's your project, and therefore you should be the one who's doing most of the work, not us. Again, please, please read, study and create on your own. If your own code doesn't work, we'll work with you, trust me, but most here won't work with you on someone else's borrowed code unless you really put in the effort to learn what it's doing. Sorry, but there are no short cuts here. :)
    Last edited by curmudgeon; 05-05-2010 at 05:29 AM.

  8. #8
    tyroceur's Avatar
    tyroceur is offline Member
    Join Date
    May 2010
    Location
    Fast Growing City, INDIA
    Posts
    44
    Rep Power
    0

    Default

    Thank you.... I want to do the work on my own.... but please just tell me how do I change the properties of graph by using controls which are in some other class.... I just want a hint so that i can start the work... Thank you

  9. #9
    curmudgeon is offline Senior Member
    Join Date
    May 2010
    Posts
    436
    Rep Power
    5

    Default

    Quote Originally Posted by tyroceur View Post
    Thank you.... I want to do the work on my own....
    Good. That's the best thing you can do.


    but please just tell me how do I change the properties of graph by using controls which are in some other class.... I just want a hint so that i can start the work... Thank you
    This mainly requires decent OOP techniques. For something like this I try to emulate how Swing does these sorts of things -- by creating a model that represents the logic of my class, by having my view or GUI be the visual representation of the model and by using controller classes to convert user interactions into changes in the model which are then automatically reflected in the view. This is better known as the MVC design pattern. It has many variations (which you can read about on Google and at Wikipedia) and all are usefull. I suggest you take a look at this and borrow ideas from it: Model-View-Controller Pattern

  10. #10
    tyroceur's Avatar
    tyroceur is offline Member
    Join Date
    May 2010
    Location
    Fast Growing City, INDIA
    Posts
    44
    Rep Power
    0

    Default

    Thank you for your time :)

  11. #11
    chyrl is offline Senior Member
    Join Date
    Mar 2010
    Location
    Manila, Philippines
    Posts
    257
    Rep Power
    5

    Default

    tyroceur,

    Is this thread solved?
    Every project, package, class, method, variable, syntax, algorithm, etc.
    are registered in my memory bank. Thanks to this thread.

  12. #12
    tyroceur's Avatar
    tyroceur is offline Member
    Join Date
    May 2010
    Location
    Fast Growing City, INDIA
    Posts
    44
    Rep Power
    0

    Default

    Sorry for late reply... Yes I have got my solution....Thanks :)

Similar Threads

  1. How to make swing.Timer as a separate class
    By nethz13 in forum New To Java
    Replies: 9
    Last Post: 04-18-2010, 10:14 AM
  2. How to make a runnable jar with necessary libraries
    By Atriamax in forum New To Java
    Replies: 2
    Last Post: 10-27-2009, 11:36 PM
  3. Java Media Libraries
    By SilentCodingOne in forum Advanced Java
    Replies: 2
    Last Post: 07-04-2009, 06:21 AM
  4. Java 3D Scene Graph Libraries
    By sweeyt in forum AWT / Swing
    Replies: 1
    Last Post: 04-10-2009, 09:26 AM
  5. how to make histogram using jfreechart in swing
    By saradap80 in forum Introductions
    Replies: 0
    Last Post: 02-10-2009, 08:25 PM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •