我想用我的程序做的事情是,當我點擊圖像時,矩形會與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