日安,
希望这是个快速解决的问题。我正在编写一个在JPanels中使用JLayeredPane和JFrame的应用程序。在我的应用程序的最初启动,其中一个面板不显示,直到我的鼠标移动到面板应该在的区域。我甚至调用了验证和重绘方法,但我仍然能够同时显示两个面板。有什么建议吗?谢谢。
这里是我的JFrame类(它有主要的方法)
import java.awt.Dimension;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;
public class Application extends JFrame
{
public Application()
{
this.setSize(500,500);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
JLayeredPane lp = new JLayeredPane();
lp.setBounds(0,0,500,500);
this.setLayeredPane(lp);
Mypanel p1 = new Mypanel();
Mypanel2 p2 = new Mypanel2();
this.getLayeredPane().add(p1,0);
this.getLayeredPane().add(p2,1);
this.validate();
this.repaint();
this.validate();
}
public static void main(String[] args)
{
Application app = new Application();
}
}这里是我的一个面板类
import javax.swing.JButton;
import javax.swing.JPanel;
public class Mypanel extends JPanel
{
public JButton button;
public Mypanel()
{
this.setLayout(null);
this.setBounds(0, 0, 500, 500);
JButton b = new JButton("Hello");
b.setBounds(20,20,300,300);
this.add(b);
}
}和最后一个面板类
import javax.swing.JButton;
import javax.swing.JPanel;
public class Mypanel2 extends JPanel
{
public JButton button;
public Mypanel2()
{
this.setLayout(null);
this.setBounds(0, 0, 500, 500);
JButton b = new JButton("SUP");
b.setBounds(20,10,200,200);
this.add(b);
this.repaint();
this.validate();
this.repaint();
}
}发布于 2012-06-25 21:48:15
首先,在一个有效的程序中,只有JComponent重新绘制自己。如果在某个时候您发现从控制器代码中调用c.repaint()解决了一些问题,那么您就忽略了作为swing框架核心的基本契约。这绝对不是个好主意。因此,删除所有这些repaint和validate调用是一个好的开始。接下来,重要的是了解轻量级swing组件如何绘制它们的子组件。有两种模式:优化和不优化。第一种只适用于兄弟姐妹在容器中不相互重叠的情况。如果这样做了,并且优化了画图,那么当这些组件重新绘制自己时,您将得到各种奇怪的行为(比如将鼠标指针悬停在它们上面)。所有轻量级组件都可以通过setComponentZOrder()处理重叠的子组件。JLayeredPane只引入了一个层的概念,以一种更灵活的方式来控制zorder。它试图聪明地选择哪种模式来画它的孩子,但遗憾的是,这是如何运作的微妙之处。因此,这段代码可以满足您的需要:
Mypanel p1 = new Mypanel();
Mypanel2 p2 = new Mypanel2();
getLayeredPane().setLayer(p1,0);
getLayeredPane().setLayer(p2,1);
getLayeredPane().add(p1);
getLayeredPane().add(p2);但这不会:
Mypanel p1 = new Mypanel();
Mypanel2 p2 = new Mypanel2();
getLayeredPane().add(p1);
getLayeredPane().add(p2);
getLayeredPane().setLayer(p1,0);
getLayeredPane().setLayer(p2,1);诀窍是在将子容器添加到容器之前调用setLayer,这样JLayeredPane就可以关闭优化的绘制。
顺便说一句,我不禁想知道为什么是JLayeredPane?如果您需要在不同的布局之间以编程方式切换,也许JTabbedPane就是您的答案。
发布于 2013-03-19 18:24:19
JLayeredPane lp = new JLayeredPane();
JPanel d = new JPanel();
d.setVisible(true);
d.setBounds(10, 10, 556, 386);
lp.add(d, new Integer(0), 0);https://stackoverflow.com/questions/11196587
复制相似问题