- 论坛徽章:
- 0
|
回复 #2 starxing 的帖子
Code:
/**
* Dots.java
* Demonstrates mouse event.
*/
import javax.swing.JFrame;
public class Dots {
/**
* Create and display the application frame.
*/
public static void main(String[] args) {
JFrame frame = new JFrame("Dots");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
DotsPanel panel = new DotsPanel();
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
}
}
import java.util.ArrayList;
import javax.swing.JPanel;
import java.awt.*;
import java.awt.event.*;
/**
* DotsPanel.java
* Demonstrates the use of conditionals and loops to quide drawing.
*/
public class DotsPanel extends JPanel {
// radius of each dot
private final int SIZE = 6;
/**
* Constructor: Sets up this panel to listen for mouse events.
*/
public DotsPanel(){
pointList = new ArrayList<Point>();
this.addMouseListener(new DotsListener());
this.setBackground(Color.black);
this.setPreferredSize(new Dimension(300,200));
}
/**
* Action: Draws all of the dots stored in the list.
* @param page Graphics
*/
public void paintComponent(Graphics page){
super.paintComponent(page);
page.setColor(Color.green);
for (Point spot: pointList)
page.fillOval(spot.x - SIZE, spot.y - SIZE, SIZE*2, SIZE*2);
page.drawString("Count: " + pointList.size(), 5, 15);
}
/**
* innerClass DotsListener: Represents the listener for mouse events.
*/
private class DotsListener implements MouseListener{
/**
* Method mousePressed: Adds the current point to the list of points and redraws the panel
* whenever the mouse button is pressed.
* @param event MouseEvent
*/
public void mousePressed(MouseEvent event){
pointList.add(event.getPoint());
repaint();
}
/**
* Provide empty defintions for unused event methods.
* @param event MouseEvent
*/
public void mouseClicked (MouseEvent event) {
}
public void mouseReleased (MouseEvent event) {
}
public void mouseEntered (MouseEvent event) {
}
public void mouseExited (MouseEvent event) {
}
}
} |
|