62,623
社区成员
发帖
与我相关
我的任务
分享
package mobi.chenwei.sample.shapesample;
import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.Shape;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
/**
* @author Chen Wei
* @website www.chenwei.mobi
*/
public class DrawPanel extends javax.swing.JPanel {
private Shape shape = null;
/** Creates new form DrawPanel */
public DrawPanel() {
initComponents();
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
formMouseClicked(evt);
}
});
setLayout(null);
}// </editor-fold>
private void formMouseClicked(java.awt.event.MouseEvent evt) {
if(getShape().contains(evt.getPoint())){
JOptionPane.showMessageDialog(this, "");
}
}
public Shape getShape() {
return shape;
}
public void setShape(Shape shape) {
this.shape = shape;
}
// Variables declaration - do not modify
// End of variables declaration
public void paintComponent(Graphics g){
if(getShape() != null){
Graphics2D g2d = (Graphics2D)g;
g2d.draw(getShape());
}
}
public static void main(String[] args){
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
DrawPanel drawPanel = new DrawPanel();
drawPanel.setShape(new Rectangle(20, 20, 100, 100));
frame.add(drawPanel, BorderLayout.CENTER);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}