package javaswing; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.RenderingHints; import javax.swing.Box; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.SwingUtilities; /** * * @web http://java-buddy.blogspot.com/ */ public class JavaTestSwing { static JFrameWin jFrameWindow; public static class MyComponent extends JComponent{ Dimension myDimension = new Dimension(500, 500); @Override public Dimension getPreferredSize() { return myDimension; } @Override public Dimension getMaximumSize() { return myDimension; } @Override public Dimension getMinimumSize() { return myDimension; } @Override protected void paintComponent(Graphics g) { //fill background g.setColor(Color.gray); g.fillRect(0, 0, getWidth(), getHeight()); g.setColor(Color.darkGray); g.fillRect(50, 50, 150, 150); //rotate about 0, 0 Graphics2D graphics2D = (Graphics2D)g.create(); graphics2D.rotate(Math.toRadians(45)); graphics2D.setColor(Color.red); graphics2D.fillRect(50, 50, 150, 150); //rotate about 100, 100 graphics2D = (Graphics2D)g.create(); graphics2D.rotate(Math.toRadians(45), 100, 100); graphics2D.setColor(Color.blue); graphics2D.fillRect(50, 50, 150, 150); //dispose Graphics2D object graphics2D.dispose(); } } public static class JFrameWin extends JFrame{ public JFrameWin(){ this.setTitle("java-buddy.blogspot.com"); this.setSize(500, 500); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); MyComponent myComponent = new MyComponent(); Box horizontalBox = Box.createHorizontalBox(); horizontalBox.add(myComponent); this.add(horizontalBox); } } public static void main(String[] args){ Runnable doSwingLater = new Runnable(){ public void run() { jFrameWindow = new JFrameWin(); jFrameWindow.setVisible(true); } }; SwingUtilities.invokeLater(doSwingLater); } }
Wednesday, October 17, 2012
Create and rotate Graphics2D object
In this example, we create a new Graphics2D object (graphics2D) from original Graphics object (g), by calling it's create() method. Then rotate the Graphics2D object, by calling its rotate() method. After used, dispose it.
No comments:
Post a Comment