我有一个JPanel
基地,我将在其中放置其他JPanel
个项目。我想在另一个JPanel
项目的顶部显示一个JPanel
。
我尝试使用下面的代码,但它没有用。
package test;
import java.awt.Color;
import java.awt.HeadlessException;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class JPanelParent extends JFrame
{
public JPanelParent() throws HeadlessException {
JPanel nPanel = getNode(10,10,20,20, Color.red,1);
JPanel nPanel2 = getNode(20,20,20,20, Color.yellow,2);
JPanel nPanel3 = getNode(30,30,20,20, Color.green,3);
add(nPanel);
add(nPanel2);
add(nPanel3);
}
public JPanel getNode(int i, int i1, int j, int j1, Color color, int zOrder){
JPanel nodePanel = new JPanel();
nodePanel.setBackground(color);
nodePanel.setBounds(i,i1,j,j1);
nodePanel.setOpaque(true);
nodePanel.setLayout(null);
return nodePanel;
}
public static void main(String argv[]){
JPanelParent jpp = new JPanelParent();
jpp.setVisible(true);
jpp.setSize(300,300);
jpp.setBackground(Color.black);
}
}
由于
答案 0 :(得分:4)
您可以使用JLayeredPane
。查看更多How to Use JLayeredPane
public JPanelParent() throws HeadlessException {
JPanel nPanel = getNode(10, 10, 20, 20, Color.red, 1);
JPanel nPanel2 = getNode(20, 20, 20, 20, Color.yellow, 2);
JPanel nPanel3 = getNode(30, 30, 20, 20, Color.green, 3);
JLayeredPane pane = new JLayeredPane();
pane.add(nPanel, new Integer(1));
pane.add(nPanel2, new Integer(2));
pane.add(nPanel3, new Integer(3));
setContentPane(pane);
getContentPane().setBackground(Color.BLACK);
}
注意:传递的Integer
值是图层顺序。数字越高,越高图层
import java.awt.Color;
import java.awt.HeadlessException;
import javax.swing.JFrame;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class JPanelParent extends JFrame {
public JPanelParent() throws HeadlessException {
JPanel nPanel = getNode(10, 10, 20, 20, Color.red, 1);
JPanel nPanel2 = getNode(20, 20, 20, 20, Color.yellow, 2);
JPanel nPanel3 = getNode(30, 30, 20, 20, Color.green, 3);
JLayeredPane pane = new JLayeredPane();
pane.add(nPanel, new Integer(1));
pane.add(nPanel2, new Integer(2));
pane.add(nPanel3, new Integer(3));
setContentPane(pane);
getContentPane().setBackground(Color.BLACK);
}
public JPanel getNode(int i, int i1, int j, int j1, Color color, int zOrder) {
JPanel nodePanel = new JPanel();
nodePanel.setBackground(color);
nodePanel.setBounds(i, i1, j, j1);
nodePanel.setOpaque(true);
nodePanel.setLayout(null);
return nodePanel;
}
public static void main(String argv[]) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JPanelParent jpp = new JPanelParent();
jpp.setVisible(true);
jpp.setSize(300, 300);
jpp.setBackground(Color.black);
}
});
}
}
旁注
答案 1 :(得分:2)
如果您了解自己的问题,那么首先在将JPanels
添加到父框架之前,您需要告诉parent frame
将component
添加到特定坐标中,并且可以完成通过为父框架设置Layout
为空。
在构造函数的第一行添加此行。
setLayout(null);