我认为我的paintComponent无法工作的原因是因为我将图像作为JLabel放在JPanel中。当我使用MouseListener单击时,我想使用drawRect绘制一个矩形。
我的图片是来自JFileChooser的BufferedImage
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode (JFileChooser.FILES_AND_DIRECTORIES);
if (fileChooser.showOpenDialog(panelPic) == JFileChooser.APPROVE_OPTION)
{
try
{
pic = ImageIO.read(fileChooser.getSelectedFile());
//reading the image of the selected file
} catch (IOException ioe)
{
JOptionPane.showMessageDialog(panelPic, "Error Reading File!");
}
System.out.println("getFileOrDirectory exited");
}
else if (fileChooser.showOpenDialog(panelPic) == JFileChooser.CANCEL_OPTION)
System.exit(1);
return pic;
然后我的照片会经历这个
pic = getFileOrDirectory();
picLabel = new JLabel (new ImageIcon(pic));
panelPic.add(picLabel);
System.out.println("picLabel added to panel");
repaint();
frame.validate();
panelPic是我希望看到图片的地方。 那么这是我的油漆代码没有真正起作用-_-所以我删除了对我来说不起作用的drawImage方法。
public void paint(Graphics g)
{
System.out.println("paint entered"); // just a checker if the program passed through this method
super.paint(g);
g.setColor(Color.BLACK);
g.drawRect(x-50, y-50, 100, 100);
frame.validate();
}
我想知道如何解决这个问题。
已更新! 这是我的代码的SSCCE
public class TrialCode extends JPanel implements MouseListener, ActionListener
{ JFrame frame;
JPanel panelPic;
BufferedImage pic;
JButton getImg;
public TrialCode ()
{
frame = new JFrame("Java Project");
panelPic = new JPanel();
getImg = new JButton("Get Image");
frame.getContentPane().add(BorderLayout.CENTER, panelPic);
frame.setSize(900, 700);
frame.setVisible(true);
panelPic.addMouseListener(this);
getImg.addActionListener(this);
}
public void paint(Graphics g)
{
System.out.println("paintComponent entered"); // checker
super.paint(g);
g.setColor(Color.BLACK);
g.drawRect(x-50, y-50, 100, 100);
}
private BufferedImage getFileOrDirectory()
{
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode (JFileChooser.FILES_AND_DIRECTORIES);
if (fileChooser.showOpenDialog(panelPic) == JFileChooser.APPROVE_OPTION)
{
try
{
pic = ImageIO.read(fileChooser.getSelectedFile());
} catch (IOException ioe)
{
JOptionPane.showMessageDialog(panelPic, "Error Reading File!");
}
System.out.println("getFileOrDirectory exited");
}
else if (fileChooser.showOpenDialog(panelPic) == JFileChooser.CANCEL_OPTION)
System.exit(1);
return pic;
}
public void showImage()
{
pic = getFileOrDirectory();
picLabel = new JLabel (new ImageIcon(pic));
panelPic.add(picLabel);
repaint();
frame.validate();
}
public static void main (String [] args)
{
new TrialCode();
}
public void actionPerformed(ActionEvent event)
{
inputImage();
}
@Override
public void mouseClicked(MouseEvent e)
{
// TODO Auto-generated method stub
x = e.getX();
y = e.getY();
repaint();
inputName = JOptionPane.showInputDialog(frame, "Enter Name");
// when click the retangle should appear
}