java applet 按钮_按下按钮后如何在applet(java)中添加图片?

我已经找到了一种奇怪的方式将图片放在一个applet中,但是当我将代码放在buttonListener中以便在按下按钮时显示图片时,它似乎不起作用 . 如果您还可以给我一个最简单的代码来将图片放入applet中,我们将非常感激!

有效的代码:import java.awt . ; import java.applet . ; import javax.swing . *;

公共类gamedone扩展JApplet {

public void init() {

Container cp = getContentPane();

cp.setBackground(Color.black);

Container content_pane = getContentPane();

Image img = getImage(getCodeBase(), "portal-cake.jpg");

DrawingPanel drawing_panel = new DrawingPanel(img);

// Add the DrawingPanel to the content pane.

content_pane.add(drawing_panel);

} // init

类DrawingPanel扩展了JPanel {Image img;

DrawingPanel (Image img)

{ this.img = img; }

public void paintComponent(Graphics g) {

super.paintComponent(g);

g.drawImage(img, 0, 0, this);

}

}

但是当这是我添加它的程序时,按钮不能使它工作:

import java.awt . ; import java.applet . ; import java.awt.event . ; import javax.swing . ;

公共类TypeInNames扩展JApplet {

JButton StartButton;

JTextField name1, name2;

String player1, player2;

String reply;

Container cp = getContentPane();

public void init()

{

setSize(350, 400);

setLayout(null);

cp.setBackground(Color.black);

StartButton = new JButton("Start Game!");

name1 = new JTextField("Player 1",35);

name2 = new JTextField("Player 2",35);

//(x, y, width, height);

StartButton.setBounds(115,200,120,30);

name1.setBounds(115,140,120,20);

name2.setBounds(115,170,120,20);

startGame();

}

public void startGame()

{

add(StartButton);

add(name1);

add(name2);

StartButton.addActionListener(new ButtonListener());

}

public void game()

{

}

public void endGame()

{

Container cp = getContentPane();

cp.setBackground(Color.black);

Container content_pane = getContentPane();

Image img = getImage(getCodeBase(), "portal-cake.jpg");

DrawingPanel drawing_panel = new DrawingPanel(img);

// Add the DrawingPanel to the content pane.

content_pane.add(drawing_panel);

}

private class ButtonListener implements ActionListener{

public void actionPerformed(ActionEvent event)

{

if (event.getSource() == StartButton)

{

player1 = name1.getText();

player2 = name2.getText();

remove(StartButton);

remove(name1);

remove(name2);

endGame();

repaint();

}

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值