这是我的代码,我想为我制作的 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);
}
}