I created two classes which one extending. I create an object, but a file is not appearing (method work fine, because title form draw() method appears. There is all code:
public class Main_class extends JFrame implements ActionListener{
//**************************//
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable(){
public void run(){
new Main_class().setVisible(true);
}
});
}
//**************************//
JPanel panel;
JMenuBar mbar;
JMenuItem item;
JMenuItem open;
JMenu file;
BufferedImage my_image;
public Main_class(){
setSize(800, 600);
setTitle("TEST");
setResizable(false);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel=new JPanel();
mbar=new JMenuBar();
setJMenuBar(mbar);
file=new JMenu("File");
mbar.add(file);
open=new JMenuItem("Open");
open.addActionListener(this);
file.add(open);
}
@Override
public void actionPerformed(ActionEvent e) {
String zrodlo=e.getActionCommand();
image_class k=new image_class();
if(zrodlo.equals("Open")) try {
k.load(my_image);
} catch (IOException ex) {
Logger.getLogger(Main_class.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
///////////////////////////////////////////
public class image_class extends Main_class{
public void load(BufferedImage my_image) throws IOException{
JFileChooser open_chooser=new JFileChooser("//");
FileNameExtensionFilter rast=new FileNameExtensionFilter("Pliki grafiki rastrowej(.jpeg,.png.,gif...)", "jpeg","jpg", "gif","png","bmp");
open_chooser.setFileFilter(rast);
int a=open_chooser.showOpenDialog(null);
if(a==JFileChooser.APPROVE_OPTION){
String image_name=open_chooser.getSelectedFile().getAbsolutePath();
String roz=image_name.substring(image_name.lastIndexOf('.')+1);
my_image=ImageIO.read(open_chooser.getSelectedFile());
draw();
}
}
public void draw(){
panel=new JPanel(){
protected void paintComponent(Graphics g){
Graphics g2 = g.create();
g2.drawImage(my_image, 0, 0, getWidth(), getHeight(), null);
g2.dispose();
}
};
panel.setBounds(0, 0, 200, 200);
add(panel);
revalidate();
repaint();
System.out.print("LOADED!!!!!!");
}
}
One of your main problems is that you’re misusing inheritance. Your code here from image_class.java:
You are adding the new JPanel to a Main_class instance, but not the one that is displayed but rather to the one that image_class inherits from. These are two completely distinct objects and making changes to one will not affect the other.
The solution is not to misuse inheritance for this but rather to display the image in the original GUI.
Also, you should never dispose of a Graphics object that was given to you from the JVM as this can have nasty side effects.