简体   繁体   English

如何在jpanel中的图片顶部添加按钮

[英]How do you add a button on top of a picture in jpanel

import java.awt.*;   
import javax.swing.*;  

public class Game
{  

  MyDrawPanel draw;  

  public static void main(String[] args)
  {  
    new Game().go();   
  }  

  public void go()
  { 
    JFrame frame=new JFrame("Revenge");  
    JPanel panel=new JPanel();  
    draw=new MyDrawPanel();         
    frame.getContentPane().add(BorderLayout.CENTER,draw);  
    frame.setSize(750,360);  
    frame.setVisible(true);    
  }  
  public class MyDrawPanel extends JPanel
  {  
    @Override
    public void paintComponent(Graphics g)
    {              
      Image image=new ImageIcon("C:\\Users\\zep\\Desktop\\title.png").getImage();  
      g.drawImage(image,0,0,this);
    }  
  }  
}  

So basically I need help trying to add a button. 所以基本上我需要帮助尝试添加按钮。 I am extremely new to java and I need to do this for my CPT in my class. 我是java的新手,我需要在课堂上为我的CPT做这个。 Please help you will be my hero :3 请帮助你成为我的英雄:3

Well...just create new button and add it on your drawPanel. 好吧......只需创建新按钮并将其添加到drawPanel上即可。 Like this: 像这样:

JButton button = new JButton("Text goes here");
drawPanel.add(button);

Default layout for drawPanel is FlowLayout so your button should be centered on top of that panel. drawPanel的默认布局是FlowLayout因此您的按钮应该位于该面板的顶部。 Or, if you want your button above your picture, add it on panel : 或者,如果您希望按钮位于图片上方,请将其添加到panel

panel.add(button);
frame.getContentPane().add(panel,BorderLayout.NORTH);

Use this code: 使用此代码:

JButton button = new JButton("Text goes here");
drawPanel.add(button, BorderLayout.NORTH);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM