在java中怎样在JLabel上添加JButton呢

为什么总是显示不出来呢,希望得到帮助
我只是想将button显示在图片上,我将JLabel设置icon,再将jlabel放入panel,之后我将button放入panel想叠加在label上面可以吗

java swing中JLabel中添加JButton只需要使用JLabel的add方法就可以添加,实例如下:

package components;
 
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.net.URL;
 
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
 
public class JButtonTest extends JPanel implements ActionListener {
 
   
    private static final long serialVersionUID = 1L;
 
    JButton button1,button2,button3;
    public JButtonTest() {
       //创建button上的图标
       ImageIcon imageIcon1 = createImage("images/right.gif");
       ImageIcon imageIcon2 = createImage("images/middle.gif");
       ImageIcon imageIcon3 = createImage("images/left.gif");
      
       //创建Button,并设置Button的图标
       button1 = new JButton("中间按钮不可用",imageIcon1);
       //设置Button的文本位置
       button1.setVerticalTextPosition(JButton.CENTER);
       button1.setHorizontalTextPosition(JButton.LEADING);
       //设置Button的快捷键
       button1.setMnemonic(KeyEvent.VK_D);
       //设置Button的反馈消息,消息处理者通过这个标记来辨别是哪个按钮被点击
       button1.setActionCommand("disable");
       //为Button添加监听者
       button1.addActionListener(this);
       //设置Button的提示信息
       button1.setToolTipText("点击此按键,此按键和中间按键变为不可用,右边按键变为可用");
       //将Button添加到panel中
       add(button1);
 }
温馨提示:答案为网友推荐,仅供参考
第1个回答  2008-12-09
1: JButton有setIcon(Icon icon)的方法可以设置图片,
2: JLabel 也可以加入任意组件,add(Component c);这个方法
3:JLabel 默认布局是BorderLayout
4: 你的补充问题当然能实现,没问题
第2个回答  推荐于2018-03-10
可以..把在JLabel中加入图片.然后当成JApplet的背景..JButton放在JApplet上就行

//###################################

import java.awt.FlowLayout;

import javax.swing.*;

public class Test extends JApplet{
public Test()
{
JPanel jp=(JPanel)this.getContentPane(); //从JFrame 里面创建一个JPanel
jp.setOpaque(false); //JPanel 透明模式
ImageIcon img = new ImageIcon("c://Sunset.jpg"); //创建一个图片路径
JLabel background = new JLabel(img); //创建个带背景图片的JLabel
this.getLayeredPane().add(background,new Integer(Integer.MIN_VALUE));
background.setBounds(0, 0, img.getIconWidth(), img.getIconHeight());
jp.setLayout(new FlowLayout());
JButton jb=new JButton("我是按钮");
jp.add(jb);
}
}本回答被提问者和网友采纳
第3个回答  2008-12-09
是在JButton里添加JLabel吧?
标签里怎么添加按钮?
JLabel a=new JLabel("label");
JButton b=new JButton(a);
不知道这是不是你要的.
要么可能是
定义面版,在面版里加标签又加按钮.
JPanel pane=new JPanel();
JButton b=new JButton("click");
JLabel a=new JLabel("label");
pane.add(a);
pane.add(b);
第4个回答  2008-12-09
好像不行,没这样用过~!
相似回答