Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package so;
- import java.awt.*;
- import java.util.Random;
- import java.util.function.*;
- import javax.swing.*;
- public class CirclePainter {
- public static void main(String[] args) {
- JFrame frame = new JFrame("Circle Painter");
- frame.setLayout(new FlowLayout());
- //java 8 style
- Function<Integer, int[]> fiftyShadesOfGray = (i -> new int[]{4*i,4*i,4*i});
- //pre-java 8 style
- DiameterToColor anotherFunc = new DiameterToColor() {
- @Override
- public int[] getColor(int i) {
- return new int[]{20+4*i,255-4*i,100+2*i};
- }
- };
- JPanel gray = new MyPanel(fiftyShadesOfGray);
- JPanel colorful = new MyPanel(anotherFunc);
- frame.add(gray);
- frame.add(colorful);
- frame.pack();
- frame.setLocationRelativeTo(null);
- frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- frame.setVisible(true);
- }
- private static class MyPanel extends JPanel {
- //better than magic constants hard-coded deep inside method
- private static final int X = 0, Y = 1, DIAM = 2,
- COLOR_R = 3, COLOR_G = 4, COLOR_B = 5;
- private int width = 500, height = 500;
- private Dimension prefSize = new Dimension(width, height);
- /**
- * array of information about circles, in format
- * x|y|diameter|colorR|colorG|colorG
- */
- private int[][] circles;
- private int maxDiameter = 50;
- private int count = 100;
- //use this if you have java 8
- public MyPanel(Function<? super Integer, ? extends int[]> diamToColor) {
- //optional: seed your random generator for repeatable testing
- long seed = 6194466113533747327L;
- Random ran = new Random(seed);
- circles = new int[count][];
- for (int i = 0; i < count; i++) {
- int x = ran.nextInt(width);
- int y = ran.nextInt(height);
- int d = ran.nextInt(maxDiameter);
- int[] col = diamToColor.apply(d);
- circles[i] = new int[]{x, y, d, col[0], col[1], col[2]};
- }
- }
- //move body of previous constructor here
- //if you don't have java 8
- public MyPanel(DiameterToColor diamToColor) {
- this((Function<Integer, int[]>) diamToColor::getColor);
- }
- @Override
- public Dimension getPreferredSize() {
- return prefSize;
- }
- @Override
- protected void paintComponent(Graphics g) {
- super.paintComponent(g);
- for(int[] circle: circles) {
- g.setColor(new Color(circle[COLOR_R], circle[COLOR_G], circle[COLOR_B]));
- g.fillOval(circle[X], circle[Y], circle[DIAM], circle[DIAM]);
- }
- }
- }
- //use java 8 Function instead if avaliable
- private static interface DiameterToColor {
- public int[] getColor(int diameter);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement