Add background image into applet frame

半世苍凉 提交于 2020-01-07 08:29:03

问题


I am trying to add a background image to my applet, but don't know how to add.

Here is my code.

public class SAMmain extends JApplet{    
    public JMenuBar mbar=new JMenuBar();    
    public JMenu newStudent,viewtudent,markAttendence;

    public void init() {
        setSize(1366, 768);
        setJMenuBar(mbar);
        newStudent= new JMenu("New Student  ");
        mbar.add(newStudent);
        viewtudent= new JMenu("View student");      
        mbar.add(viewtudent);
        markAttendence= new JMenu("Mark Attendence");
        mbar.add(markAttendence);
    }

    public void start() {
    }   
     public void stop() {
    }
}

回答1:


You can use paint function

public void paint(Graphics g) {

        ImageIcon i = new ImageIcon("path");
        g.drawImage(i.getImage(), x, y, this);
    }

and dont forget to import import javax.swing.ImageIcon;




回答2:


There are any number of ways this might be achieved based on what you want...

You Could...

Make the content pane a JLabel, setting the icon to it...

public void init() {
    JLabel label = new JLabel(new ImageIcon(getClass().getResource("/path/to/resource")));
    setContentPane(label);
    setLayout(...);
    //...
}

You could...

Use the Graphics API, for example...

public class BackgroundPane extends JPanel {

    private BufferedImage img;

    public BackgroundPane() {
        try {
            img = ImageIO.read(getClass().getResource("/path/to/resource"));
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    @Override
    public Dimension getPreferredSize() {
        return img == null ? new Dimension(200, 200) : new Dimension(img.getWidth(), img.getHeight());
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        if (img != null) {
            Graphics2D g2d = (Graphics2D) g.create();
            g2d.drawImage(img, 0, 0, this);
            g2d.dispose();
        }
    }
}

Then you could set it as you applet's content pane...

public void init() {
    BackgroundPane background = new BackgroundPane();
    setContentPane(background);
    setLayout(...);
    //...
}

The only real reason to use something like this would be because you want to process the image in some special way, like it's position, size, alpha etc...

This all assumes that the image has being packaged into one of the Jars of the application and is available at runtime from the context of the class path...



来源:https://stackoverflow.com/questions/19699623/add-background-image-into-applet-frame

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!