在我的面板上添加图片作为背景和按钮

时间:2020-06-02 16:57:50

标签: java image swing jpanel

public class CompetitionPanel extends JPanel implements ActionListener{

 public static BufferedImage image;
 private JPanel panel;
 private JButton b1,b2,b3,b4,b5,b6;
 private JLabel l;
 
  public CompetitionPanel ()
  {
    panel=new JPanel();
    l=new JLabel();
    FlowLayout myFlowLayout = new FlowLayout();
    myFlowLayout.setAlignment(FlowLayout.CENTER);
    panel.setLayout(myFlowLayout);
    
    b1 = new JButton("Add Competition");
    b1.addActionListener(this);
    panel.add(b1);
    b2 = new JButton("Add Animal");
    b2.addActionListener(this);
    panel.add(b2);
    b3 = new JButton("Clear");
    b3.addActionListener(this);
    panel.add(b3);
    b4 = new JButton("Eat");
    b4.addActionListener(this);
    panel.add(b4);
    b5 = new JButton("Info");
    b5.addActionListener(this);
    panel.add(b5);
    b6 = new JButton("Exit");
    b6.addActionListener(this);
    panel.add(b6);
    //panel.add(l);
  
    panel.add(l);
   
  
    try{image = ImageIO.read(new File("competitionBackground.png"));}
    catch (IOException e){System.out.println("Cannot load image");}
  }

  public void paintComponent(Graphics g)
  {
    g.drawImage(image, 0,0,getWidth(),getHeight(),this);
  }

那是我的代码。 我应该更改代码中的什么,以便它也可以在背景图像上方打印按钮?

0 个答案:

没有答案