-1
我正在嘗試做兩件事。一個要求用戶按空格鍵開始,另一個開始遊戲。我想要有兩個構造函數,一個要求用戶按空格鍵和一個開始遊戲。問題是,如果我創建兩個教師,我會得到兩個不同的框架,而不是將這兩個框架都放在一起。如何使用重載構造函數,但保持在同一個JFrame中?
import javax.swing.*;
import java.awt.*;
import java.text.DecimalFormat;
public class DuckHunt extends JPanel {
private ImageIcon imgBackground, imgForeground, imgCursor;
private Cursor cursor;
private int score, hits;
private double accuracy;
private DecimalFormat df;
private Font f;
private static final int PANEL_WIDTH = 640;
private static final int PANEL_HEIGHT = 480;
public static void main(String[] args) {
new DuckHunt();
}
public DuckHunt(String text) {
// THIS IS WHERE IM TRYING TO DO THE SPACEBAR THING
// how do I do it so it's all in one frame, instead of two seperate ones
}
public DuckHunt() {
df = new DecimalFormat("#%");
f = new Font("Neuropol", Font.BOLD, 18);
imgBackground = new ImageIcon("images\\background.png");
imgForeground = new ImageIcon("images\\foreground.png");
imgCursor = new ImageIcon("images\\cursor.png");
cursor = Toolkit.getDefaultToolkit().createCustomCursor(imgCursor.getImage(),
new Point(imgCursor.getIconWidth()/2, imgCursor.getIconHeight()/2), "");
setLayout(null);
setCursor(cursor);
setFocusable(true);
requestFocus();
JFrame frame = new JFrame();
frame.setContentPane(this);
frame.setTitle("Duck Hunt © Nintendo 1985");
frame.setSize(PANEL_WIDTH, PANEL_HEIGHT);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setFocusable(false);
frame.setVisible(true);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.drawImage(imgBackground.getImage(), 0, 0, this);
g2.setFont(f);
g2.setColor(new Color(128, 208, 16));
g2.drawImage(imgForeground.getImage(), 0, 0, this);
g2.drawString("SCORE: " + score, 20, PANEL_HEIGHT - 50);
g2.drawString("HITS: " + hits, 250, PANEL_HEIGHT - 50);
g2.drawString("ACCURACY: " + df.format(accuracy), 450, PANEL_HEIGHT - 50);
}
}
不要爲此使用兩個構造函數。問題結束。而是在主要方法中調用一個窗口,也許是一個模態JDialog,然後在從JDialog返回後創建並顯示主JFrame GUI。 –
另一個也許更好的選擇:使用CardLayout來交換視圖 - 首先按空格鍵視圖,然後再使用遊戲。 –
請參閱編輯以回答。如果有任何混淆,請提問。 –