我创建了两个类,其中一个扩展。我创建了一个对象,但没有出现文件(方法工作正常,因为出现了标题形式的 draw() 方法。所有代码:
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!!!!!!");
}
}