Java Swing JLayeredPane未显示 [英] Java Swing JLayeredPane not showing up
问题描述
我似乎在JLayeredPane
上遇到了一些重大问题.我有一个BorderLayout()
窗格,我希望West-side元素彼此之间包含一些JLayeredPane,因此我可以在它们之间切换以显示正确的信息.
I seem to be having some major issues with JLayeredPane
. I have a BorderLayout()
pane, and I'd like for the West-side element to contain a few JLayeredPane's on top of each other, so I can switch between them to show the right information.
西窗格应为200像素宽,且应与整个窗口一样长.在我的示例代码中,我在JLayeredPanel
中添加了两层,但是没有显示出来.它们应该在西窗格中.
The west pane should be 200 pixels wide and should be as long as the total window is. In my sample code I have added two layers to the JLayeredPanel
, but they don't show up. They should be in the west pane.
这是我的代码:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;
public class Main {
private static JFrame mainFrame = new JFrame();
private static JPanel mainPane = new JPanel();
public Main(){}
public static void initGui(){
JLayeredPane westPanel = new JLayeredPane();
westPanel.setPreferredSize(new Dimension(200,0));
westPanel.setBackground(Color.blue);
JPanel layerOne = new JPanel();
layerOne.add(new JLabel("This is layer 1"));
westPanel.add(layerOne, new Integer(0), 0);
JPanel layerTwo = new JPanel();
layerTwo.add(new JLabel("This si layer 2"));
westPanel.add(layerTwo, new Integer(1), 0);
JPanel centerPanel = new JPanel();
centerPanel.setBackground(Color.yellow);
JPanel eastPanel = new JPanel();
eastPanel.setPreferredSize(new Dimension(200,0));
eastPanel.setBackground(Color.red);
mainPane = new JPanel(new BorderLayout());
mainPane.add(westPanel, BorderLayout.WEST);
mainPane.add(centerPanel, BorderLayout.CENTER);
mainPane.add(eastPanel, BorderLayout.EAST);
mainFrame = new JFrame("Learning to use JLayeredPane");
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setBounds(200, 200, 800, 500);
mainFrame.setContentPane(mainPane);
mainFrame.setVisible(true);
}
public static void main(String[] args) {
initGui();
}
}
这将导致以下结果:
What this results in:
推荐答案
JLayeredPane使用空布局,因此您有责任说明添加到其中的所有组件的大小和位置.如果不是,它们将默认为[0,0] 的位置,并且的大小为[0,0].
JLayeredPane uses a null layout and so you are responsible for stating the size and location of all components added to it. If not they will default to a location of [0, 0] and a size of [0, 0].
这篇关于Java Swing JLayeredPane未显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!