我發現了一個奇怪的方式,把一張圖片放在一個小程序中,但它似乎不起作用,當我將代碼放到buttonListener中時,按鈕被按下時,圖片顯示出來。如果你也可以給我最簡單的代碼來將圖片放入applet,那將非常感謝!如何在按下按鈕後在applet(java)中添加圖片?
工作的代碼: 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 { 圖像IMG;
DrawingPanel (Image img)
{ this.img = img; }
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(img, 0, 0, this);
}
}
,但是當這是我加入到程序,並且按鈕不會使其工作:
進口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();
}
}
}
}
你爲什麼不發佈你到目前爲止? – Joel 2010-09-06 14:54:01