gpt4 book ai didi

java - 关于JFrame上鼠标单击时添加矩形

转载 作者:行者123 更新时间:2023-12-02 13:41:59 24 4
gpt4 key购买 nike

我是初学者。我正在尝试使用多个内部类在 JFrame 上添加填充矩形或任何其他图形。我遇到调试错误。这里有什么问题?如果这是一个错误的方法。请告诉我如何仅使用 JFrame 和 JPanel 执行相同的操作。

import java.util.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import java.io.*;

public class RainBow{

JFrame frame;

public static void main(String[] args){
RainBow bow = new RainBow();
bow.go();
}

public class Paint extends JPanel{
public void paintComponent(Graphics g){
g.setColor(Color.red);
g.fillRect(100, 100, 100, 100);

}
}

public void go(){
frame.addMouseListener(new ListenMouse());
frame.setSize(400, 400);
frame.setVisible(true);
}

public class ListenMouse implements MouseListener{
public void mosueClicked(MouseEvent a){
Paint p = new Paint();
frame.getContentPane().add(p);
frame.setVisible(true);
}

@Override
public void mouseClicked(MouseEvent arg0) {
// TODO Auto-generated method stub

}

@Override
public void mouseEntered(MouseEvent arg0) {
// TODO Auto-generated method stub

}

@Override
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub

}

@Override
public void mousePressed(MouseEvent arg0) {
// TODO Auto-generated method stub

}

@Override
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub

}

}

}

最佳答案

发布的代码有多个问题。请参阅此工作示例以及评论中的说明。

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;

public class RainBow {

JFrame frame;
boolean paintRectangle = false;

public static void main(String[] args) {
RainBow bow = new RainBow();
bow.go();
}

public class Paint extends JPanel {

public void paintComponent(Graphics g) {
super.paintComponent(g); // should always be done
if (paintRectangle) {
g.setColor(Color.red);
g.fillRect(100, 100, 100, 100);
}
}
}

public void go() {
frame = new JFrame(); // otherwise NPE
Paint paint = new Paint();
paint.addMouseListener(new ListenMouse()); // add listner to paint
frame.add(paint); // add paint at start-up
frame.setSize(400, 400);
frame.setVisible(true);
// ensures JVM shuts down when frame is closed.
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}

public class ListenMouse extends MouseAdapter {

// this method is incorrectly spelled!
public void mosueClicked(MouseEvent a) {
}

@Override
public void mouseClicked(MouseEvent arg0) {
/* requires special handling to add components on the fly */
//Paint p = new Paint();
paintRectangle = true;
frame.repaint(); // forces the Paint to be painted as well.
}
}
}

关于java - 关于JFrame上鼠标单击时添加矩形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42700490/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com