将JLayeredPane添加到JPanel

编程入门 行业动态 更新时间:2024-10-27 23:20:53
本文介绍了将JLayeredPane添加到JPanel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我试图将JLayeredPane添加到JPanel,然后将图像(JLabel图标)和按钮添加到JLayeredPane,但均未显示.我已经测试了没有按钮和分层窗格的图像,所以我知道这是可行的.这是我正在使用的一些代码.有什么我想念或做错的事吗?

I am trying to add a JLayeredPane to a JPanel and then add an image (JLabel icon) and a button to the JLayeredPane, but neither show up. I've tested the image without the button and the layeredpane so I know that works. Here is some of the code I am using. Is there something I am missing or doing wrong?

public class MyClass extends JPanel { private JLayeredPane layeredPane; private JLabel imageContainer = new JLabel(); private JButton info = new JButton("i"); MyClass(ImageIcon image) { super(); this.imageContainer.setIcon(image); this.layeredPane = new JLayeredPane(); layeredPane.setPreferredSize(new Dimension(300, 300)); layeredPane.add(imageContainer, new Integer(50)); layeredPane.add(info, new Integer(100)); this.add(layeredPane); } }

推荐答案

来自教程

默认情况下,分层窗格没有布局管理器.这意味着您通常必须编写代码来确定放置在分层窗格中的组件的位置和大小.

查看对您代码的更改:

import java.awt.*; import javax.swing.*; public class MyClass extends JPanel { private JLayeredPane layeredPane; private JLabel imageContainer = new JLabel(); private JButton info = new JButton("i"); MyClass(ImageIcon image) { super(); this.imageContainer.setIcon(image); this.layeredPane = new JLayeredPane(); layeredPane.setPreferredSize(new Dimension(300, 300)); layeredPane.add(imageContainer, new Integer(50)); layeredPane.add(info, new Integer(100)); this.add(layeredPane); // CHANGED CODE // Manually set layout the components. imageContainer.setBounds( 0, 0, image.getIconWidth(), image.getIconHeight() ); info.setBounds( 200, 00, 50, 40 ); } public static void main( String [] args ) { JFrame frame = new JFrame(); frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); frame.add( new MyClass( new ImageIcon("logo.png") ) ); frame.pack(); frame.setVisible( true ); } }

其他说明:

1)(我认为)最好将开括号放在同一行.那就是大多数Java代码的样子.

1) It is better ( in my opinion ) to put the opening brace in the same line. That's how most Java code looks like.

2)如果您并不是真正在创建子类,请避免从JPanel(或任何其他组件)继承.您可以直接使用它而无需继承(除非您确实要创建一个新组件.

2) Avoid inheriting from JPanel ( or any other component ) if you don't are not really creating a subclass. You can use it directly without having to inherit ( unless you're indeed creating a new component.

更多推荐

将JLayeredPane添加到JPanel

本文发布于:2023-08-06 03:32:02,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1309773.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:JLayeredPane   JPanel

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!