Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to add add multiple extended JPanels into one JFrame in Java?
    primarykey
    data
    text
    <p>I want two images from two different classes that extend JPanel to be side by side.</p> <p>The problem that I'm having is that the two JPanels should be inside the JFrame but when I do framename.add(panel) it replaces the other one instead of adding two of them side by side.</p> <p>I have tried adding flowlayout and other layouts inside the main class, but none of the images showed up.</p> <p><strong>So my question is</strong>, if I have two classes that extend Jpanel, how do i add those two panels inside a Jframe so that they'll be side by side (next to each other) without replacing the other panel?</p> <p>Any suggestions would be greatly appreciated.</p> <p><strong>Edit</strong>: If I extend JFrame to a class, does that class automatically become a JPanel itself? I know what extends means, but I'm not sure how it works in regards to a Jframe.</p> <p><strong>Main.java</strong></p> <pre><code>import javax.swing.*; import java.awt.*; import java.net.URL; public class Main { public static void main(String[] args) { JFrame frame = new JFrame(); Panel1 s = new Panel1(); //picture 1 Panel2 n = new Panel2(); //picture 2 frame.add(n); frame.add(s); //here is the problem, it replaces the previous panel f.setSize(200,100); f.setLocation(0,400); f.setVisible(true); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } } </code></pre> <p><strong>Panel1.java</strong></p> <pre><code>import javax.swing.*; import java.awt.*; import java.net.URL; public class image2 extends JPanel { ImageIcon anotherIcon; public image2() //constructor { URL imageURL = Panel1.class.getResource("images/puppy.png"); anotherIcon = new ImageIcon(imageURL); } public void paint(Graphics g) { super.paintComponent(g); anotherIcon.paintIcon(this, g, 0, 0); } } </code></pre> <p><strong>Panel2.java</strong> </p> <pre><code>import javax.swing.*; import java.awt.*; import java.net.URL; public class Panel2 extends JPanel { ImageIcon anotherIcon2; public Panel2() //constructor { URL imageURL = Panel2.class.getResource("images/puppy2.png"); anotherIcon = new ImageIcon(imageURL); } public void paint(Graphics g) { super.paintComponent(g); anotherIcon2.paintIcon(this, g, 0, 0); } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload