1 import java.awt.*; 2 import java.awt.event.MouseAdapter; 3 import java.awt.event.MouseEvent; 4 5 import javax.swing.*; 6 7 public class Test_16_7 extends JFrame{ 8 private JP j1 = new JP(); 9 public Test_16_7(){ 10 j1.addMouseListener(new MouseAdapter() 11 { 12 public void mousePressed(MouseEvent e) 13 { 14 j1.color = Color.BLUE; 15 j1.repaint(); 16 } 17 public void mouseReleased(MouseEvent e) 18 { 19 j1.color = Color.RED; 20 j1.repaint(); 21 } 22 }); 23 add(j1); 24 } 25 26 public static void main(String[] args) { 27 // TODO Auto-generated method stub 28 Test_16_7 T1 = new Test_16_7(); 29 T1.setTitle("Test_16.7"); 30 T1.setSize(200,200); 31 T1.setLocationRelativeTo(null); 32 T1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 33 T1.setVisible(true); 34 } 35 36 37 class JP extends JPanel{ 38 Color color = Color.BLACK; 39 40 protected void paintComponent(Graphics g){ 41 super.paintComponent(g); 42 43 g.setColor(color); 44 g.fillRect(0, 0, getWidth(), getHeight()); 45 } 46 } 47 }
Test_16_7.java
效果图:
时间: 2024-10-19 15:43:29