Happy Codings - Programming Code Examples
Html Css Web Design Sample Codes CPlusPlus Programming Sample Codes JavaScript Programming Sample Codes C Programming Sample Codes CSharp Programming Sample Codes Java Programming Sample Codes Php Programming Sample Codes Visual Basic Programming Sample Codes


Java Programming Code Examples

Java > Swing Code Examples

Creating dynamic graphics (Stars)

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
Creating dynamic graphics (Stars) import java.awt.*; import javax.swing.*; import java.awt.event.*; import java.util.*; public class Cells1 extends JFrame { private DPanel pan = new DPanel(); private Network net = new Network(pan); public Cells1() { addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent ev) { dispose(); System.exit(0); } }); setBounds(10,10,400,350); setContentPane(pan); setVisible(true); } public class DPanel extends JPanel { private Graphics2D g2f; private Color colors[] = new Color[] { Color.red,Color.black,Color.yellow,Color.blue,Color.green,Color.gray,Color.cyan,Color.cyan,Color.orange,Color.magenta }; public DPanel() { setBackground(Color.white); } public void paintComponent(Graphics g) { super.paintComponent(g); g2f = (Graphics2D)g; Vector cells = net.getCells(); for (int j=0; j < cells.size(); j++) draw((Cell_Info)cells.get(j)); g2f = null; } public void draw(Cell_Info ci) { if (g2f == null) g2f = (Graphics2D)getGraphics(); Point p = ci.getPoint(); g2f.setColor(colors[ci.getAction()]); g2f.fillOval(p.x,p.y,8,8); } } public class Network extends Object { private Vector cells = new Vector(); public Network(final DPanel pan) { cells.add(new Cell_Info(20,20)); cells.add(new Cell_Info(50,120)); cells.add(new Cell_Info(45,20)); cells.add(new Cell_Info(90,55)); cells.add(new Cell_Info(40,110)); cells.add(new Cell_Info(35,80)); cells.add(new Cell_Info(95,70)); cells.add(new Cell_Info(24,40)); cells.add(new Cell_Info(35,60)); cells.add(new Cell_Info(80,100)); cells.add(new Cell_Info(90,90)); javax.swing.Timer ta = new javax.swing.Timer(200, new ActionListener() { public void actionPerformed(ActionEvent e) { int v = (int)(Math.random()*cells.size()); int c = (int)(Math.random()*10); Cell_Info ci = (Cell_Info)cells.get(v); ci.setAction(c); pan.draw(ci); } }); ta.start(); } public Vector getCells() { return(cells); } } public class Cell_Info extends Object { Point point; int activ = 0; public Cell_Info(int x, int y) { point = new Point(x,y); } public Point getPoint() { return(point); } public int getAction() { return(activ); } public void setAction(int a) { activ = a; } } public static void main (String[] args) { new Cells1(); } }