Java中Swing组件上绘图机制举例


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

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

相关内容