因此,我正在製作一款遊戲,在有人獲勝後,我想要一種顯示「x贏了」或「y贏了」的方法。現在我的問題是,如果我讓方法繪製一個包含勝利消息的字符串,那麼我的IDE不允許我,因爲我不能使用Graphics g作爲顯式參數運行方法。如何調用以圖形g爲參數的方法?
是否有任何其他方式在JFrame屏幕上顯示消息?
這裏是我的代碼:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;`
//nothing wrong here :P
public class Demonstration extends JFrame {
private JButton b1;
private JButton b2;
public Demonstration() {
//My constructor
JPanel panel = new JPanel();
panel.setLayout(null);
add(panel);
handler h = new handler();
b1 = new JButton("yes");
b2 = new JButton("no");
//A sub - class to handle events. Created below
b1.setBounds(34, 34, 34, 34);
//random
panel.add(b1);
b1.addActionListener(h);
b2.setBounds(56, 56, 56, 56);
// random again
panel.add(b2);
b2.addActionListener(h);
setTitle("Demonstration");
setBackground(Color.BLACK);
setDefaultCloseOperation(3);
setSize(720, 720);
setVisible(true);
}
}
這是我的面板。
public static void main (String[] args) {
new Demonstration();
}
因此,讓我們說,我所做的處理程序類以後,我希望它運行一段代碼,它有一個的if/else爲其點擊按鈕(.getSource()),我想使用圖形重新設計界面並打印出勝利信息,我該怎麼做?
那麼你有什麼想法我可以使用它嗎? –
@AditKirtani您可以在'JFrame'中使用它,通過類似於您現在使用'JPanel'的方式添加它。我建議''JFrame'的'BorderLayout','Demonstration'在中心,'JPanel'中的按鈕和'GridLayout'在南部。然後,只需將所有繪圖代碼移動到'paintComponent'方法中,它就會自動爲您調用它。 – resueman