我对Java并不熟悉,而且我对当前的问题有点无能为力。 我正在尝试在我的主JFrame的单独类中绘制一个图像,但它 总是只绘制一小部分图片(可能是10x10px)。 (使用标签进行的测试)
也许我没有正确使用g.drawImage方法,或者JPanel没有足够的空间?
主窗口:
public class Deconvolutioner extends JFrame {
Draw z;
Picturearea picturearea;
class Draw extends JPanel {
public void paint(Graphics g) {
}
}
public Deconvolutioner() {
setTitle("Deconvolutioner");
setLocation(30,1);
setSize(1300,735);
super.setFont(new Font("Arial",Font.BOLD,11));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
FlowLayout flow = new FlowLayout(FlowLayout.CENTER);
this.setLayout(flow);
picturearea = new Picturearea();
this.add(picturearea);
add(z = new Draw());
setVisible(true);
}
class Open implements ActionListener {
public void actionPerformed(ActionEvent e) {
JFileChooser fileOpen = new JFileChooser();
FileFilter filter = new FileNameExtensionFilter("png & jpg files", "png",
"jpg");
fileOpen.addChoosableFileFilter(filter);
int returnVal = fileOpen.showDialog(null, "Open file");
if (returnVal == JFileChooser.APPROVE_OPTION) {
try {
String path = fileOpen.getSelectedFile().getPath();
URL url = new File(path).toURI().toURL();
BufferedImage img = ImageIO.read(url);
picturearea.setPicture(img);
} catch (IOException ex) {
System.err.println("Some IOException accured (set the right path?): ");
System.err.println(ex.getMessage());
}
} else {
}
repaint();
}
}
单独的课程:
public class Picturearea extends JPanel {
public BufferedImage image;
Draw z;
public Picturearea() {
add(z = new Draw());
setVisible(true);
}
class Draw extends JPanel {
@Override
public void paint(Graphics g) {
g.drawImage(image, 0, 0, this);
}
}
public void setPicture(BufferedImage picture) {
try {
image = picture;
} catch (Exception e) {
System.err.println("Some IOException accured (did you set the right path?): ");
System.err.println(e.getMessage());
}
repaint();
}
}
我很感激你的每一个帮助 谢谢你的时间。
答案 0 :(得分:0)
您正在使用FlowLayout
进行JFrame
的{{1}}布局。 contentPane
服从组件的FlowLayout
。尝试在preferredSize
课程中设置preferredSize
pictureArea
pictureArea.setPreferredSize(Dimension)
或覆盖getPreferredSize(Dimension)
功能。{/ p>
您正在使用PictureArea
进行自定义绘画:
paint(Graphics g)
请勿覆盖自定义绘制覆盖@Override
public void paint(Graphics g) {
g.drawImage(image, 0, 0, this);
}
的{{1}}。并且您可能需要缩放图像以适合JPanel的大小。如果需要缩放图像,可以使用paint()
功能。
paintComponent(Graphics g)