简体   繁体   中英

I have a frame with an image in it and i am trying to add a JComponent over it

I have tried a few different ways of doing this but all have failed.

Currently I have a frame with an image set in it using a class called backViewer that extends JPanel. I would like to take that frame and place a JComponent over it that I can then move. The background image will appear but the JComponent, SchellTower, will not appear over top of it.

 package Graphical; import java.awt.Component; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import java.awt.LayoutManager; import javax.swing.ImageIcon; import javax.swing.JPanel; import javax.accessibility.*; import javax.imageio.ImageIO; import java.awt.*; import java.awt.event.*; import java.io.File; import java.io.IOException; import javax.swing.*; public class TowerViewer extends JFrame { public TowerViewer() { //backViewer /*public class backViewer extends JPanel { @Override protected void paintComponent(Graphics g){ super.paintComponents(g); Image image = new ImageIcon("filename").getImage(); g.drawImage(image,0,0,500,690,null); }*/ setSize(500, 688); backViewer back = new backViewer(); add(back); setVisible(true); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setTitle("Schell Tower"); } public static void main(String args[]) { TowerViewer t = new TowerViewer(); SchellTower comp = new SchellTower(); t.add(comp); t.setVisible(true); //moving the component this works on its own and seems to be running in the back ground //but the SchellTower component isnt visible int x = 0; while (true) { for (int i = 0; i <= 10; i++) { comp.move(0, x); t.add(comp); x += 60; try { Thread.sleep(1000); //1000 milliseconds is one second. } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } } try { Thread.sleep(3000); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } x -= 60; for (int j = 0; j <= 9; j++) { comp.move(0, x); t.add(comp); x -= 60; try { Thread.sleep(1000); //1000 milliseconds is one second. } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } } } } } 

I'm willing to try anything at this point thanks in advance

Adding t.setComponentZOrder(component, index) after adding the component to the frame placed the component above the background

 final TowerViewer t = new TowerViewer(); //a frame with a background image already set SchellTower comp = new SchellTower(); t.add(comp); t.setComponentZOrder(comp, 0); //this line places image above background t.setVisible(true); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM