这是我的代码,我想向我创建的Rect添加功能,例如单击它时,会弹出一个窗口
public class codetwo extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponent(g);
this.setBackground(Color.LIGHT_GRAY);
g.setColor(Color.RED);
g.fillRect(110,110, 120, 120);
}
public static void main(String args[]) {
codetwo cd = new codetwo();
JFrame frame = new JFrame("Title");
frame.add(cd);
frame.setSize(440,350);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
最佳答案
您需要为此使用Mouselistener。
public class codetwo extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponent(g);
this.setBackground(Color.LIGHT_GRAY);
g.setColor(Color.RED);
g.fillRect(110,110, 120, 120);
}
public static void main(String args[]) {
codetwo cd = new codetwo();
cd.addMouseListener(new MouseListener(){
@Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
if (e.getX() >= 110 && e.getX() <= 230 && e.getY() >= 110 && e.getY() <= 230) {
JOptionPane.showMessageDialog(cd, "Some one clicked here ?", "Listening", JOptionPane.INFORMATION_MESSAGE);
}
}
@Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
JFrame frame = new JFrame("Title");
frame.add(cd);
frame.setSize(440,350);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}