Please pardon me if this is hard to follow, but I have a specific problem that I need help solving. I have done a ton of research, and I have tried numerous solutions but none of them are working.
My issue is that I have an ImagePanel
class that is extending JPanel
(code below), this class needs to use width and height to scale images (I am making a program where users can create custom tutorials including images). When I instantiate this I get an error saying that the width and height must be nonzero. I understand that this is because the layout manager has not yet passed the ImagePanel
a preferred size, however I do not know how to get that size to the panel. The ImagePanel
is inside a JPanel
which is inside a JSplitPane
inside of a JScrollPane
inside of a JPanel
inside of a JTabbedPane
inside of a JSplitPane
inside of a JFrame
. A graphical representation of this in decreasing container order is as follows:
- JFrame (GridLayout)
- JSplitPane (Default SplitPane Layout)
- JTabbedPane (Deault JTabbedPane Layout)
- JPanel (GridLayout)
- JScrollPane (Default ScrollPane Layout)
- JSplitPane (Default SplitPane Layout)
- JPanel (GridLayout);
- ImagePanel
The code for the ImagePanel is as follows:
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
public class ImagePanel extends JPanel{
private BufferedImage i;
private ImageIcon miniature;
private Image paint = null;
public void createImage(String path){
try {
i = ImageIO.read(new File(path));
} catch (IOException ex) {
ex.printStackTrace();
}
if(i != null){
int width = (int)((double)i.getWidth() * ((double)getWidth()/i.getWidth()));
int height = (int)((double)i.getHeight()*i.getHeight()/i.getWidth()*((double)this.getHeight()/i.getHeight()));
miniature = new ImageIcon(i.getScaledInstance(width, height, Image.SCALE_SMOOTH));
paint = miniature.getImage();
}
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (paint!=null){
g.drawImage(paint, 0, 0, null);}
}
}
How can I get the proper size to the ImagePanel
. I would like the image to change size with the size of the JFrame
, which is why I don't just use setPreferedSize();
.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…