Write a Java program that will output a 640x480 screen pixels, with a diagonal line from each both ends. Please help.
You should have already learned about swing, frames, panels, etc. and so this example should help from: Publisher : Prentice Hall PTR Core Java™ 2 Volume I - Fundamentals, Seventh Edition By Cay S. Horstmann, Gary Cornell Pub Date : August 17, 2004 ISBN : 0-13-148202-5 Pages : 784 Example 7-4. DrawTest.java 1. import java.awt.*; 2. import java.awt.geom.*; 3. import javax.swing.*; 4. 5. public class DrawTest 6. { 7. public static void main(String[] args) 8. { 9. DrawFrame frame = new DrawFrame(); 10. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 11. frame.setVisible(true); 12. } 13. } 14. 15. /** 16. A frame that contains a panel with drawings 17. */ 18. class DrawFrame extends JFrame 19. { 20. public DrawFrame() 21. { 22. setTitle("DrawTest"); 23. setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); 24. 25. // add panel to frame 26. 27. DrawPanel panel = new DrawPanel(); 28. add(panel); 29. } 30. 31. public static final int DEFAULT_WIDTH = 400; 32. public static final int DEFAULT_HEIGHT = 400; 33. } 34. 35. /** 36. A panel that displays rectangles and ellipses. 37. */ 38. class DrawPanel extends JPanel 39. { 40. public void paintComponent(Graphics g) 41. { 42. super.paintComponent(g); 43. Graphics2D g2 = (Graphics2D) g; 44. 45. // draw a rectangle 46. 47. double leftX = 100; 48. double topY = 100; 49. double width = 200; 50. double height = 150; 51. 52. Rectangle2D rect = new Rectangle2D.Double(leftX, topY, width, height); 53. g2.draw(rect); 54. 55. // draw the enclosed ellipse 56. 57. Ellipse2D ellipse = new Ellipse2D.Double(); 58. ellipse.setFrame(rect); 59. g2.draw(ellipse); 60. 61. // draw a diagonal line 62. 63. g2.draw(new Line2D.Double(leftX, topY, leftX + width, topY + height)); 64. 65. // draw a circle with the same center 66. 67. double centerX = rect.getCenterX(); 68. double centerY = rect.getCenterY(); 69. double radius = 150; 70. 71. Ellipse2D circle = new Ellipse2D.Double(); 72. circle.setFrameFromCenter(centerX, centerY, centerX + radius, centerY + radius); 73. g2.draw(circle); 74. } 75. }
You just nailed it! Thank you so much espex!
You're welcome.
Join our real-time social learning platform and learn together with your friends!