![](/img/trans.png)
[英]Java Swing: combine effects of CardLayout and JLayeredPane
[英]Graphics not showing in JLayeredPane (java swing)
我正在嘗試逐步建立基於用戶輸入的圖像。 我正在嘗試做的是創建一堆圖形並將它們添加為圖層但是我遇到了一些問題,因為它們不會顯示出來。 這是我正在使用的代碼:
public class ClassA
{
protected final static int dimesionsY = 1000;
private static int dimesionsX;
private static JFrame window;
private static JLayeredPane layeredPane;
public void init()
{
window = new JFrame("Foo");
dimesionsX = // some user input
window.setPreferredSize(new Dimension(dimesionsX, dimesionsY));
window.setLayout(new BorderLayout());
layeredPane = new JLayeredPane();
layeredPane.setBounds(0, 0, dimesionsX, dimesionsY);
window.add(layeredPane, BorderLayout.CENTER);
ClassB myGraphic = new ClassB();
myGraphic.drawGraphic();
layeredPane.add(myGrpahic, new Integer(0), 0);
window.pack();
window.setVisible(true);
}
}
public class ClassB extends JPanel
{
public void drawGraphic()
{
repaint();
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor(Color.BLACK);
g.fillRect(10, 10, 100, 100);
}
}
但是我的圖形似乎沒有出現,我不明白為什么。 我還嘗試將它添加到JPanel
,將JPanel
添加到JLayeredPane
但是這也不起作用。
請有人幫幫我嗎?
如果將組件添加到JLayeredPane,就像使用容器將其添加到空布局一樣:您必須完全指定組件的大小和位置。
例如,
import java.awt.*;
import javax.swing.*;
public class ClassA {
protected final static int dimesionsY = 800;
protected final static int dimesionsX = 1000; //!!
private static JFrame window;
private static JLayeredPane layeredPane;
public void init() {
window = new JFrame("Foo");
// !! dimesionsX = // some user input
//!! window.setPreferredSize(new Dimension(dimesionsX, dimesionsY));
window.setLayout(new BorderLayout());
layeredPane = new JLayeredPane();
//!! layeredPane.setBounds(0, 0, dimesionsX, dimesionsY);
layeredPane.setPreferredSize(new Dimension(dimesionsX, dimesionsY));
window.add(layeredPane, BorderLayout.CENTER);
ClassB myGraphic = new ClassB();
myGraphic.drawGraphic();
myGraphic.setSize(layeredPane.getPreferredSize());
myGraphic.setLocation(0, 0);
//!! layeredPane.add(myGraphic, new Integer(0), 0);
layeredPane.add(myGraphic, JLayeredPane.DEFAULT_LAYER);
window.pack();
window.setVisible(true);
}
public static void main(String[] args) {
new ClassA().init();
}
}
class ClassB extends JPanel {
public void drawGraphic() {
repaint();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.BLACK);
g.fillRect(10, 10, 100, 100);
}
}
請參閱Java教程中的“ 在分層窗格中布置組件 ” 。
此外,有時您需要設置首選大小:
layeredPane.setPreferredSize(new Dimension(width, height));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.