歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Java中Swing組件上繪圖機制舉例

Java中Swing組件上繪圖機制舉例

日期:2017/3/1 10:35:57   编辑:Linux編程

A program which demonstrates the basic paint mechanism for Swing components (JPanel for example).

[java]
  1. package com.han;
  2. import java.awt.*;
  3. import java.awt.event.*;
  4. import javax.swing.*;
  5. /**
  6. * A program which demonstrates the basic paint mechanism for Swing components
  7. * (JPanel for example).
  8. * @author han
  9. *
  10. */
  11. public class SwingPaintDemo {
  12. public static void main(String[] args) {
  13. JFrame f = new JFrame("Aim For the Center");
  14. f.addWindowListener(new WindowAdapter() {
  15. public void windowClosing(WindowEvent e) {
  16. System.exit(0);
  17. }
  18. });
  19. JPanel panel = new BullsEyePanel();
  20. panel.add(new JLabel("BullsEye!", SwingConstants.CENTER), BorderLayout.CENTER);
  21. f.getContentPane().add(panel, BorderLayout.CENTER);
  22. f.pack();
  23. f.setVisible(true);
  24. }
  25. }
  26. /**
  27. * A Swing container that renders a bullseye background
  28. * where the area around the bullseye is transparent.
  29. */
  30. @SuppressWarnings("serial")
  31. class BullsEyePanel extends JPanel {
  32. public BullsEyePanel() {
  33. super();
  34. setOpaque(false); // we don't paint all our bits
  35. setLayout(new BorderLayout());
  36. setBorder(BorderFactory.createLineBorder(Color.black));
  37. }
  38. @Override
  39. public Dimension getPreferredSize() {
  40. // Figure out what the layout manager needs and
  41. // then add 100 to the largest of the dimensions
  42. // in order to enforce a 'round' bullseye
  43. /* the use of "super." is very important,
  44. because otherwise the JRE will throw a StackOverflowError.
  45. And because of the JFrame.pack() used above,
  46. the JFrame window will be resized to adapter the Container size.*/
  47. Dimension layoutSize = super.getPreferredSize();
  48. int max = Math.max(layoutSize.width,layoutSize.height);
  49. return new Dimension(max+100,max+100);
  50. }
  51. @Override
  52. protected void paintComponent(Graphics g) {
  53. Dimension size = getSize();
  54. System.out.println(size.width);
  55. System.out.println(size.height);
  56. int x = 0;
  57. int y = 0;
  58. int i = 0;
  59. while(x < size.width && y < size.height) {
  60. g.setColor(i%2==0? Color.red : Color.white);
  61. g.fillOval(x,y,size.width-(2*x),size.height-(2*y));
  62. x+=10; y+=10; i++;
  63. }
  64. }
  65. }
Copyright © Linux教程網 All Rights Reserved