我想用我的程序做的事情是,当我点击图像时,矩形会与JOptionPane一起出来。但是,JOptionPane是唯一弹出的东西。为什么我的paintComponent不工作?
我试着改变方法并添加更多的类,没有任何工作>。 <任何人都可以解决我的问题吗?这是我的代码片段。
下面是我所说的filechooser,它允许我选择我的照片。另外,一些其他的东西,如标签在这里。
public Help(){
fc.setDialogTitle("Choose an image file to begin:");
int returnval = fc.showOpenDialog(null);
if (returnval == JFileChooser.APPROVE_OPTION){ //when user selects a file, value returned will be JFileChooser.APPROVE_OPTION
File file = fc.getSelectedFile(); //the File value of the selection is returned from a call on getSelectedFile
try{
image = ImageIO.read(file); //reads and loads File as image
}
catch (IOException e){}
System.out.println("You chose to open this file: " + file.getName());
}else
System.out.println("No file selected.");
icon = new ImageIcon(image);
label = new JLabel(icon);
tagName = new JLabel(input);
label.addMouseListener(new ImagePanel());
label.addMouseMotionListener(new ImagePanel());
panel.add(tagName);
}
最后,我的ImagePanel类,其中包含麻烦的paintComponent。此外,还有一些mouseListeners。
class ImagePanel extends JPanel implements MouseListener, MouseMotionListener{
@Override
public void mouseClicked(MouseEvent event) {
// TODO Auto-generated method stub
x = event.getX();
y = event.getY();
input = JOptionPane.showInputDialog("Enter tag name");
tagName.setText("You have tagged: " + input);
System.out.println(input);
}
@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
}
public void paintComponent(Graphics g){
super.paintComponent(g);
if(image != null && isRectPresent){
g.setColor(Color.DARK_GRAY);
g.drawRect(x-50, y-50, 100, 100);
}
}
@Override
public void mouseDragged(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseMoved(MouseEvent e) {
// TODO Auto-generated method stub
}
}
您可以编译代码并亲自查看。如果你知道该怎么做,请指教我:)非常感谢!
只需要注意:确保你确实通过添加了@ @ Override注解来覆盖'paintComponent'。另外,不要*在'paintComponent'中做任何事情,比如添加监听器等等.-) – aioobe
无论如何,压倒性的做什么?大声笑我没有得到这一点xD(去表明我真的是小白)。感谢您的答复。 – alicedimarco
测试时尽量简化问题:删除所有不必要的方法,像'g.setColor()一样制作非常简单的'paintComponent'; g.drawRect()'无条件地。告诉我们结果 – pajton