我想要两个不同类的两个图像来扩展JPanel并排。
我遇到的问题是两个JPanel应该放在JFrame中,但是当我做framename.add(panel)时,它会替换另一个,而不是并排添加其中的两个。
我曾尝试在主类中添加flowlayout和其他布局,但没有任何图像出现。
所以我的问题是,如果我有两个扩展Jpanel的类,我如何将这两个面板添加到Jframe中,以便它们并排(彼此相邻)而不替换其他面板?
任何建议将不胜感激。
编辑:如果我将JFrame扩展到一个类,该类是否自动成为JPanel本身?我知道扩展意味着什么,但我不确定它如何在Jframe上工作。
Main.java
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);
}
}Panel1.java
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);
}
}Panel2.java
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);
}
}