Showing posts with label swing. Show all posts
Showing posts with label swing. Show all posts

Friday, August 15, 2014

Plotting Graphs using Java Graphics Library [Dice Throw Example] [Swing]

This program throws five dice and the sum of the numbers is plotted. The event of throwing the dice is triggered by a button pressed by the user.


Source:

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

class Die {

    Random rand = new Random();

    int getCount() {
        return rand.nextInt(6) + 1;
    }
}

public class DiceThrower extends JFrame {

    class MyPanel extends JPanel {

        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.setColor(Color.BLUE);

            int height = (getHeight());
            Integer previous = null;

            if (points.size() >= 1) {
                previous = height - points.get(0)*(getHeight())/30;
            } else {
                return;
            }

            int[] x1 = new int[points.size()];
            int hstep = getWidth() / points.size();
            
            for (int i = 0; i < x1.length; ++i) {
                x1[i] = i * hstep;
            }

            int c = 0;
            int skip = 1;
            for (int p : points) {
                if(skip==1){ skip = 0; continue; }
                g.drawLine(x1[c], previous, x1[c] + hstep, height - p*(getHeight()/30));
                previous = height - p*(getHeight()/30);
                ++c;
            }
        }
    }

    Die[] dice = new Die[5];

    int sum = 0;
    ArrayList<Integer> points = new ArrayList<>();
    MyPanel graph = new MyPanel();

    JButton throwB = new JButton("Throw Dice!");

    {
        throwB.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                int prev = sum;
                updateSum();
                ((JButton) e.getSource()).setText("Previous : " + prev + " Current : " + sum + ". Throw Again!");
                graph.repaint();
            }

        });
    }

    void updateSum() {
        sum = 0;
        for (int i = 0; i < dice.length; ++i) {
            sum += dice[i].getCount();
        } 
        points.add(sum); 
        System.out.println(sum);
    }

    DiceThrower() {
        setTitle("5 Dice Throws Sum Plotter -__-");
        for (int i = 0; i < dice.length; ++i) {
            dice[i] = new Die();
        }
        add(graph);
        add(BorderLayout.SOUTH, throwB);
        setSize(500, 500);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
    }

    public static void main(String[] args) {
        try {
            for (UIManager.LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (Exception e) {
            // If Nimbus is not available, you can set the GUI to another look and feel.
        }
        new DiceThrower();
    }
}

Thursday, August 14, 2014

JSlider Color Painter GUI Java [Swing]

This application has two JSlider s which paint a JPanel as their values change. The JSliders represent the coordinates of the JPanel to paint. A clear button clears the Panel.


Code:

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

class Point {

    int x;
    int y;

    Point(int x, int y) {
        this.x = x;
        this.y = y;
    }
}

class Display extends JPanel {

    ArrayList<Point> points = new ArrayList<>();
    Point previous, newPoint;
    Color color = Color.RED;

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D gg = (Graphics2D) g;

        gg.setColor(color);

        previous = null;

        for (Point p : points) {
            if (previous == null) {
                previous = p;
                continue;
            }
            gg.drawLine(previous.x, previous.y, p.x, p.y);
            previous = p;
        }
    }
}

public class SketchBox2 extends JFrame {

    JButton clear = new JButton("Clear Points [0]");
    private Display screen = new Display();
    private JSlider xAxis = new JSlider(0, 0, 0);
    private JSlider yAxis = new JSlider(JSlider.VERTICAL, 0, 0, 0);

    SketchBox2() {
        yAxis.setInverted(true);
        xAxis.addChangeListener(cl);
        yAxis.addChangeListener(cl);
        xAxis.setValue(0);
        yAxis.setValue(0);

        setTitle("Painter");

        add(BorderLayout.CENTER, screen);
        add(BorderLayout.NORTH, clear);
        add(BorderLayout.WEST, yAxis);
        add(BorderLayout.SOUTH, xAxis);

        screen.addComponentListener(new ComponentAdapter() {
            public void componentResized(ComponentEvent e) {
                yAxis.setMaximum(screen.getHeight());
                xAxis.setMaximum(screen.getWidth());
            }
        });

        setSize(500, 500);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);

        clear.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                screen.points.clear();
                screen.repaint();
                clear.setText(
                        "[Erase] points.size() = "
                        + screen.points.size());
            }
        });

        clear.doClick();
    }

    ChangeListener cl = new ChangeListener() {

        @Override
        public void stateChanged(ChangeEvent e) {
            screen.newPoint = new Point(xAxis.getValue(), yAxis.getValue());
            screen.points.add(screen.newPoint);

            clear.setText(
                    "[Erase] points.size() = "
                    + screen.points.size());
            screen.repaint();
        }
    };

    public static void main(String[] args) {
        new SketchBox2();
    }
}

[Concept : Thinking In Java 4th Edition GUI Ex24]