我正在實現從文件加載並可以對其進行編輯的Paint應用程序。 但我的Openfile函數不能正確運行,它會加載圖像並正確更改界限,但不要在Jpanel中繪製它。在Java Swing/Awt中實現圖像加載器
這是我的代碼。
public class OpenSave extends JPanel{
private static final long serialVersionUID = 1L;
protected BufferedImage imagem;
public OpenSave() {}
public void open(JPanel panel) throws IOException {
JFileChooser escolher = new JFileChooser();
escolher.setCurrentDirectory(new File("."));
escolher.setFileFilter(new javax.swing.filechooser.FileFilter() {
public boolean accept(File f) {
return f.getName().toLowerCase().endsWith(".jpg") || f.isDirectory();
}
public String getDescription() {
return "Imagens JPG";
}
});
escolher.setFileFilter(new javax.swing.filechooser.FileFilter() {
public boolean accept(File f) {
return f.getName().toLowerCase().endsWith(".png") || f.isDirectory();
}
public String getDescription(){
return "Imagens PNG";
}
});
JFrame frame = new JFrame();
frame.setIconImage(Toolkit.getDefaultToolkit().getImage(OpenSave.class.getResource("/javax/swing/plaf/metal/icons/ocean/directory.gif")));
int r = escolher.showOpenDialog(frame);
if (r == JFileChooser.APPROVE_OPTION) {
imagem = ImageIO.read(new File(escolher.getSelectedFile().getAbsolutePath()));
panel.setBounds(77, 13, imagem.getWidth(this), imagem.getHeight(this));
}
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(imagem, 0, 0, this);
repaint();
}
}
與此我可以保存並正確加載,但加載的圖像不會去我的JPanel面板。
這裏是主要的簡化類。
private JPanel contentPane;
private Jpanel panel;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
TelaMain frame = new TelaMain();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public TelaMain() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 600, 400);
JMenuBar menuBar = new JMenuBar();
menuBar.setFocusTraversalKeysEnabled(true);
setJMenuBar(menuBar);
JMenu mnArchive = new JMenu("Archive");
menuBar.add(mnArchive);
JMenuItem mntmOpen = new JMenuItem("Open");
mnArquivo.add(mntmOpen);
panel = new JPanel();
panel.setAutoscrolls(true);
panel.setBorder(new LineBorder(new Color(0, 0, 0)));
panel.setBackground(Color.WHITE);
panel.setBounds(77, 13, 498, 307);
contentPane.add(panel);
mntmAbrir.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent abrir) {
OpenSave a = new OpenSave();
try {
a.open(panel);
a.repaint();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
);
我打開任何其他編輯要求我的問題。
1)爲了更好地幫助更快分開,張貼[MCVE]或[簡要,獨立的,正確的示例](HTTP://www.sscce .org等/)。 2)獲取圖像的一種方法是通過[本問答](http://stackoverflow.com/q/19209650/418556)中的圖像進行熱鏈接。顯然(我希望),因爲問題是加載圖像,保存圖像的所有代碼都可以被刪除。 –
您似乎誤解了我在發佈MCVE/SSCCE時提供的建議。你讀過鏈接文件嗎? –
仍在閱讀,但我還沒有找到解決方案。 –