- Draw a star with GeneralPath in Java
- Example
- Рисуем звезду на Java
- Draw Star in Java Swing Example
- Primary Sidebar
- SQL Tutorials
- SQL Tutorials
- Advanced SQL
- Other Links
- Footer
- Basic Course
- Programming
- Draw Star in Java Swing Example
- Primary Sidebar
- SQL Tutorials
- SQL Tutorials
- Advanced SQL
- Other Links
- Footer
- Basic Course
- Programming
- Draw stars in java
- Thursday, March 29, 2012
- Draw stars using Java
- No comments:
- Post a Comment
- Search This Blog
- Blog Archive
- Followers
- About Me
Draw a star with GeneralPath in Java
The following code shows how to draw a star with GeneralPath.
Example
import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.geom.GeneralPath; import java.awt.geom.Point2D; /* ww w . j ava 2s . c o m*/ import javax.swing.JComponent; import javax.swing.JFrame; class MyCanvas extends JComponent < public void paint(Graphics g) < Graphics2D g2D = (Graphics2D) g; Point2D.Float point = new Point2D.Float(100, 100); // store start point GeneralPath p = new GeneralPath(GeneralPath.WIND_NON_ZERO); p.moveTo(point.x, point.y); p.lineTo(point.x + 20.0f, point.y - 5.0f); // Line from start to A point = (Point2D.Float)p.getCurrentPoint(); p.lineTo(point.x + 5.0f, point.y - 20.0f); // Line from A to B point = (Point2D.Float)p.getCurrentPoint(); p.lineTo(point.x + 5.0f, point.y + 20.0f); // Line from B to C point = (Point2D.Float)p.getCurrentPoint(); p.lineTo(point.x + 20.0f, point.y + 5.0f); // Line from C to D point = (Point2D.Float)p.getCurrentPoint(); p.lineTo(point.x - 20.0f, point.y + 5.0f); // Line from D to E point = (Point2D.Float)p.getCurrentPoint(); p.lineTo(point.x - 5.0f, point.y + 20.0f); // Line from E to F point = (Point2D.Float)p.getCurrentPoint(); p.lineTo(point.x - 5.0f, point.y - 20.0f); // Line from F to g p.closePath(); // Line from G to start g2D.draw(p); > > public class Main < public static void main(String[] a) < JFrame window = new JFrame(); window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); window.setBounds(30, 30, 450, 450); window.getContentPane().add(new MyCanvas()); window.setVisible(true); > >
The code above generates the following result.
Рисуем звезду на Java
Все умеют рисовать линии, прямоугольники и круги на Java – для этого есть стандартные методы drawLine, dravOval и так далее. А вот рисование более сложных геометрических фигур – уже задача поинтереснее. В этой заметке мы научимся рисовать на Java звезды разной сложности и с различным количеством лучей.
Нарисовать звезду на Java чаще всего предлагают с помощью класса Polygon, который присутствовал еще с Java 1.0, но вряд ли стоит использовать его в современном коде. Область применения его ограничена массивом целых чисел. Также, несмотря на то, что он реализует интерфейс Shape, есть более современные реализации этого интерфейса, которые могут быть использованы для представления многоугольников. В большинстве случаев, создавать многоугольник с помощью Path2D проще.
Общий алгоритм такой: создаем новый объект класса Path2D, а затем, с помощью методов MoveTo и LineTo генерируем многоугольник нужной формы.
В программе ниже показано, как класс Path2D может быть использован для создания различных типов звезд. Самым важным является метод drawStar. Этот метод очень общего характера. На вход он получает:
- координаты центра звезды;
- внутренний и внешний радиус звезды;
- количество лучей у звезды;
- угол поворота звезды.
package stars; /** * * @author upread.ru */ import java.awt.*; import javax.swing.*; import java.awt.geom.Path2D; public class Stars < public static void main(String[] args) < SwingUtilities.invokeLater(new Runnable() < @Override public void run() < drawingAndDisplay(); >>); > private static void drawingAndDisplay() < JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.getContentPane().add(new StarPanel()); f.setSize(600, 600); f.setLocationRelativeTo(null); f.setVisible(true); >> class StarPanel extends JPanel < @Override protected void paintComponent(Graphics gr) < super.paintComponent(gr); Graphics2D g = (Graphics2D) gr; g.setColor(Color.GRAY); g.fillRect(0, 0, getWidth(), getHeight()); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON); g.setColor(Color.BLACK); g.draw(createSimpleStar(50, 200, 200)); g.setPaint(Color.GREEN); g.fill(drawStar(400, 400, 40, 60, 10, 0)); g.setPaint(new RadialGradientPaint( new Point(400, 200), 60, new float[] < 0, 1 >, new Color[] < Color.RED, Color.YELLOW >)); g.fill(drawStar(400, 200, 20, 60, 8, 0)); g.setPaint(new RadialGradientPaint( new Point(200, 400), 50, new float[] < 0, 0.3f, 1 >, new Color[] < Color.BLACK, Color.YELLOW, Color.ORANGE >)); g.fill(drawStar(200, 400, 40, 50, 20, 0)); > private static Shape createSimpleStar(double radius, double koordX, double koordY) < return drawStar(koordX, koordY, radius, radius * 2.63, 5, Math.toRadians(-18)); >private static Shape drawStar(double koordX, double koordY, double innerRadius, double outerRadius, int numRays, double startAngleR) < Path2D p = new Path2D.Double(); double deltaAngleR = Math.PI / numRays; for (int i = 0; i < numRays * 2; i++) < double angleR = startAngleR + i * deltaAngleR; double ca = Math.cos(angleR); double sa = Math.sin(angleR); double relX = ca; double relY = sa; if ((i & 1) == 0) < relX *= outerRadius; relY *= outerRadius; >else < relX *= innerRadius; relY *= innerRadius; >if (i == 0) < p.moveTo(koordX + relX, koordY + relY); >else < p.lineTo(koordX + relX, koordY + relY); >> p.closePath(); return p; > >
Автор этого материала — я — Пахолков Юрий. Я оказываю услуги по написанию программ на языках Java, C++, C# (а также консультирую по ним) и созданию сайтов. Работаю с сайтами на CMS OpenCart, WordPress, ModX и самописными. Кроме этого, работаю напрямую с JavaScript, PHP, CSS, HTML — то есть могу доработать ваш сайт или помочь с веб-программированием. Пишите сюда.
заметки, java, рисование, звезда, геометрические фигуры
Бесплатный https и
домен RU в подарок
Draw Star in Java Swing Example
Dinesh Thakur holds an B.C.A, MCDBA, MCSD certifications. Dinesh authors the hugely popular Computer Notes blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps.
Dinesh Thakur is a Freelance Writer who helps different clients from all over the globe. Dinesh has written over 500+ blogs, 30+ eBooks, and 10000+ Posts for all types of clients.
For any type of query or something that you think is missing, please feel free to Contact us.
Primary Sidebar
SQL Tutorials
SQL Tutorials
- SQL — Home
- SQL — Select
- SQL — Create
- SQL — View
- SQL — Sub Queries
- SQL — Update
- SQL — Delete
- SQL — Order By
- SQL — Select Distinct
- SQL — Group By
- SQL — Where Clause
- SQL — Select Into
- SQL — Insert Into
- SQL — Sequence
- SQL — Constraints
- SQL — Alter
- SQL — Date
- SQL — Foreign Key
- SQL — Like Operator
- SQL — CHECK Constraint
- SQL — Exists Operator
- SQL — Drop Table
- SQL — Alias Syntax
- SQL — Primary Key
- SQL — Not Null
- SQL — Union Operator
- SQL — Unique Constraint
- SQL — Between Operator
- SQL — Having Clause
- SQL — Isnull() Function
- SQL — IN Operator
- SQL — Default Constraint
- SQL — Minus Operator
- SQL — Intersect Operator
- SQL — Triggers
- SQL — Cursors
Advanced SQL
- SQL — Joins
- SQL — Index
- SQL — Self Join
- SQL — Outer Join
- SQL — Join Types
- SQL — Cross Join
- SQL — Left Outer Join
- SQL — Right Join
- SQL — Drop Index
- SQL — Inner Join
- SQL — Datediff() Function
- SQL — NVL Function
- SQL — Decode Function
- SQL — Datepart() Function
- SQL — Count Function
- SQL — Getdate() Function
- SQL — Cast() Function
- SQL — Round() Function
Other Links
Footer
Basic Course
- Computer Fundamental
- Computer Networking
- Operating System
- Database System
- Computer Graphics
- Management System
- Software Engineering
- Digital Electronics
- Electronic Commerce
- Compiler Design
- Troubleshooting
Programming
- Java Programming
- Structured Query (SQL)
- C Programming
- C++ Programming
- Visual Basic
- Data Structures
- Struts 2
- Java Servlet
- C# Programming
- Basic Terms
- Interviews
Draw Star in Java Swing Example
Dinesh Thakur holds an B.C.A, MCDBA, MCSD certifications. Dinesh authors the hugely popular Computer Notes blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps.
Dinesh Thakur is a Freelance Writer who helps different clients from all over the globe. Dinesh has written over 500+ blogs, 30+ eBooks, and 10000+ Posts for all types of clients.
For any type of query or something that you think is missing, please feel free to Contact us.
Primary Sidebar
SQL Tutorials
SQL Tutorials
- SQL — Home
- SQL — Select
- SQL — Create
- SQL — View
- SQL — Sub Queries
- SQL — Update
- SQL — Delete
- SQL — Order By
- SQL — Select Distinct
- SQL — Group By
- SQL — Where Clause
- SQL — Select Into
- SQL — Insert Into
- SQL — Sequence
- SQL — Constraints
- SQL — Alter
- SQL — Date
- SQL — Foreign Key
- SQL — Like Operator
- SQL — CHECK Constraint
- SQL — Exists Operator
- SQL — Drop Table
- SQL — Alias Syntax
- SQL — Primary Key
- SQL — Not Null
- SQL — Union Operator
- SQL — Unique Constraint
- SQL — Between Operator
- SQL — Having Clause
- SQL — Isnull() Function
- SQL — IN Operator
- SQL — Default Constraint
- SQL — Minus Operator
- SQL — Intersect Operator
- SQL — Triggers
- SQL — Cursors
Advanced SQL
- SQL — Joins
- SQL — Index
- SQL — Self Join
- SQL — Outer Join
- SQL — Join Types
- SQL — Cross Join
- SQL — Left Outer Join
- SQL — Right Join
- SQL — Drop Index
- SQL — Inner Join
- SQL — Datediff() Function
- SQL — NVL Function
- SQL — Decode Function
- SQL — Datepart() Function
- SQL — Count Function
- SQL — Getdate() Function
- SQL — Cast() Function
- SQL — Round() Function
Other Links
Footer
Basic Course
- Computer Fundamental
- Computer Networking
- Operating System
- Database System
- Computer Graphics
- Management System
- Software Engineering
- Digital Electronics
- Electronic Commerce
- Compiler Design
- Troubleshooting
Programming
- Java Programming
- Structured Query (SQL)
- C Programming
- C++ Programming
- Visual Basic
- Data Structures
- Struts 2
- Java Servlet
- C# Programming
- Basic Terms
- Interviews
Draw stars in java
Here is a tutorial to make your way into drawing graphics with Java. This program creates a semi-circle line of stars. The stars are.
Greasemonkey is a Firefox add-on that lets you run JavaScript on web pages you specify. Using Greasemonkey you can improve and change the w.
Most developers who have worked with Alfresco and Liferay have had the problem of having to integrate both applications. This integratio.
We are soon releasing native iPhone client application enabling access to images generated by JA-84P wireless motion detector with built-in.
While the age of the computer and the Internet has brought a myriad of conveniences to many people worldwide, it has likewise opened up a .
A csrss.exe, also known as the Client/Server Runtime System, pertains to a component of the Windows operating system, particularly Windows.
Have you ever been stuck in a situation where you really need to take the keys off of your laptop? You may be cleaning the keyboard sect.
You may already be aware that you can use Adobe Photoshop to heavily edit any image. There are so many types of commands that you can do.
More and more people are purchasing smart phones like Treo, because these smart phones allow users to do more than just send and receive c.
ompoZer is a complete web authoring system that combines web file management and “what you see is what you get” (WYSIWYG) web page editin.
Thursday, March 29, 2012
Draw stars using Java
Here is a tutorial to make your way into drawing graphics with Java. This program creates a semi-circle line of stars. The stars are randomly colored. I made the program using Netbeans 5.5, and I tested the code also with Sun Java Studio Enterprise 8.1. Both of them are free. The output is what you see above (star color may differ as they are randomly colored).
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.awt.geom.*;
class psy2k extends JFrame public psy2k()
super( «Psy2k star draw» );
Graphics2D g2d = ( Graphics2D ) g;
GeneralPath star = new GeneralPath();
star.moveTo( xPoints[ 0 ], yPoints[ 0 ] );
for ( int k = 1; k < xPoints.length; k++ ) star.lineTo( xPoints[ k ], yPoints[ k ] ); star.closePath();
g2d.translate( 200, 200 );
for ( int j = 1; j g2d.rotate( Math.PI / 20.0 );
g2d.setColor( new Color( ( int ) ( Math.random() * 256 ),
( int ) ( Math.random() * 256 ),
( int ) ( Math.random() * 256 ) ) );
g2d.fill( star );
>
>
public static void main( String args[] )
<
psy2k app = new psy2k();
app.addWindowListener( new WindowAdapter()
<
public void windowClosing( WindowEvent e )
<
System.exit( 0 );
>
>
);
>
>
No comments:
Post a Comment
Search This Blog
Blog Archive
- ▼2012 (20)
- ▼March (20)
- Alfresco Search Portlet for Liferay
- Five In One Free Magento Extension
- Draw stars using Java
- Create a drop-down menu for image selection using .
- The bad co-worker: recognise him!
- Kompozer, The Adobe Dreamweaver Alternative
- VDrift, The Great Opensource Racing Game
- Bio-Linux 6.0 has been released !
- JA-84P camera PIR images soon coming to your iPhone
- How To Create a Mosaic in Photoshop
- How to Uninstall Programs From Your Computer
- What Are QR Codes?
- How To Uninstall Security Sphere 2012
- Christmas Classics On Blu-Ray
- Stream TV To Anything!
- Add jQuery to your Greasemonkey script
- How To Take the Keys Off a Laptop
- How To Synchronize Your Treo and Computer Using Bl.
- How To Use Stinger to Remove a Virus
- How To Solve a Csrss.exe Problem
Followers
About Me
Lulzim Miftari I’m Joanna and this blog is All About Me. 🙂 I’m a 30-something Polish girl living in Belgium. I have a pretty regular job that I like, a beautiful house in the suburbs, a wonderful partner and a lovely son born in January 2010. I’m a very lucky girl. I have always loved to read and was looking for book blogs when I discovered that the book blogging universe was a whole community that cares about its members and considers them friends. I wanted to belong too and so started blogging in January 2008. I haven’t looked back since — although like everyone I have ups and downs and sometimes life is simply too busy for me to be able to blog, I always come back to the wonderful people who I now consider friends. Most of the content of my blog is book-related, but I also include recipes and other kitchen notes, since I like to cook and try to make time for it. I imagine that my son comes up a lot too. 😉 You’re always welcome to contact me if you wish — email me on joanna dot loves dot books at gmail dot com View my complete profile
- ▼March (20)