我正在尝试将图像放入设定尺寸的JPanel(图片面板---黑色边框线)(必须适合JPANEl“图片面板”)。当我单击上传按钮时,我能够在新的JFrame中看到JFilechooser并选择我想要的图片,但是在“打开”按钮后单击没有任何反应。
import classes.BackgroundPanel;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.swing.*;
import javax.imageio.ImageIO;
import javax.swing.filechooser.FileNameExtensionFilter;
public class Test
{
public static void main(String[] args) {
final JFileChooser chooser = new JFileChooser();
JButton button = new JButton();
button.setText("Upload");
JFrame frame = new JFrame("My Frame");
final JFrame imageFrame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JFileChooser fc = new JFileChooser();
final Test_Image t = new Test_Image();
JPanel panel = new JPanel();
JPanel picturePanel = new JPanel();
// chooser.showOpenDialog(null);
Dimension d = new Dimension(1261, 765);
Dimension d2 = new Dimension(1300, 900);
picturePanel.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
panel.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
Dimension d3 = new Dimension(343, 247);
picturePanel.setSize(d3);
//picturePanel.setSize(d);
panel.add(button);
panel.setSize(d3);
//panel.setVisible(true);
//panel.add(picturePanel);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
if(chooser.showOpenDialog(imageFrame) == JFileChooser.APPROVE_OPTION) {
try {
Image bi = ImageIO.read(
chooser.getSelectedFile());
BackgroundPanel bp = new BackgroundPanel(bi);
if (bi != null)
bp.setImage(bi);
else
JOptionPane.showMessageDialog(imageFrame,
"File is not an image!");
} catch (IOException ioe) {
JOptionPane.showMessageDialog(imageFrame,
"Error Reading File!");
}
}
}
});
frame.setSize(d2);
frame.add(picturePanel).setLocation(100, 100);
frame.add(panel);
frame.setVisible(true);
}
}
答案 0 :(得分:0)
BackgroundPanel bp = new BackgroundPanel(bi);
您不会在任何地方将FramePane添加到框架中。动态添加组件的基本代码是:
panel.add( someComponent );
panel.revalidate();
panel.repaint();
如果已经将BackgroundPanel添加到框架中,那么您应该只能在面板上调用setImage()方法。因此,现在您需要更改代码,以便在从文件选择器中选择路径后使用ImageIO.read(...)读取图像。
答案 1 :(得分:0)
同样,我没有看到将BackgroundPanel添加到picturePanel JPanel的任何地方。您需要将picturePanel的布局设置为BorderLayout,然后将BackgroundPanel,bp添加到BorderLayout.CENTER位置的picturePanel,然后调用revalidate并重新绘制,如camickr所示。
即使我们已经请求,我们也看不到您的BackgroundPanel类的代码。同样,我希望你在paintComponent方法中绘制图像并使用正确的drawImage重载,但是直到你展示代码,我们才会确定。