Java 围绕超级类创建GUI
对于我正在做的这个项目,我想利用一个高低卡游戏类并围绕它创建一个gui。我熟悉GUI的制作并理解它,但问题是我不太确定如何实现超类方法(例如:play方法)以显示在文本区域中。当我叫这出戏时;方法它会导致终端输出,我想知道如何使它使文本区域接收来自方法的文本 以下是原始的HighLow类:Java 围绕超级类创建GUI,java,user-interface,super,Java,User Interface,Super,对于我正在做的这个项目,我想利用一个高低卡游戏类并围绕它创建一个gui。我熟悉GUI的制作并理解它,但问题是我不太确定如何实现超类方法(例如:play方法)以显示在文本区域中。当我叫这出戏时;方法它会导致终端输出,我想知道如何使它使文本区域接收来自方法的文本 以下是原始的HighLow类: /** * Simulates a card game called High/Low using the classes Card, and Deck. * * @author (Prof R)
/**
* Simulates a card game called High/Low using the classes Card, and Deck.
*
* @author (Prof R)
* @version (v1.0 11/01/2014)
*/
import java.util.Scanner;
public class HighLow
{
private int m_gamesPlayed;
private int m_sumOfScores;
// Constructor to initialize all the data members
HighLow()
{
m_gamesPlayed = 0;
m_sumOfScores = 0;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
//
// This is the main loop of the of the game. It calls the method to play a round of High-Low,
// and calls the methos to display the result when the round is over. It then will prompt the user to check
// if they want to continue. When the user stops playing it calls the method to display the final stats
//
// parameters: None
// return: None
//
/////////////////////////////////////////////////////////////////////////////////////////////////////
public void Play()
{
boolean playAgain = true; // local variable representing status of "continue to play"
while (playAgain) {
int scoreThisGame; // Score for one game.
scoreThisGame = PlayARound(); // Play a round and get the score.
m_sumOfScores += scoreThisGame; // Sum up scores
m_gamesPlayed++; // Sum up rounds played
char c = PlayAgainPrompt(); // Prompt user to see if they want to continue
if (c == 'Y') {
playAgain = true;
}
else {
playAgain = false;
}
}
DisplayFinalStats();
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Prompts the user for fot Y/y or N/y with prompt "Do you want to play again?".
//
// Paramters; none.
// return: char where Y is play again, or N is stop playing
//
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
protected char PlayAgainPrompt()
{
Scanner in = new Scanner(System.in);
char c;
do {
System.out.println("Play again? ");
String buffer;
buffer = in.nextLine();
c = buffer.charAt(0);
c = Character.toUpperCase(c);
} while (c != 'Y' && c != 'N');
return c;
}
// Lets the user play a round HighLow, and returns the user's score in the game.
//
// Parameter: none
// return: an in reprsenting the number of correct guesses
private int PlayARound()
{
Scanner in = new Scanner(System.in);
Deck deck = new Deck(); // Get a new deck of cards
Card currentCard; // The current card, which the user bases his guess off
Card nextCard; // The next card in the deck, whic will determine outcome of user's guess
int correctGuesses ; // variable for sum of correct guess
char guess; // The user's guess. 'H/h' -higher, 'L/l' lower
deck.Shuffle(); // Shuffle the deck
correctGuesses = 0;
currentCard = deck.DealACard(); // Get a card from the top of the deck
boolean correct = true; // Loop will continue until this is false
while (correct) { // Loop ends when user's prediction is wrong.
DisplayCurrentCard(currentCard); // Call methos to display current card
guess = GuessPrompt(); // Get the user's predition, 'H' or 'L'.
nextCard = deck.DealACard(); // Get next card from the deck
DisplayNextCard(nextCard); // Display the next card
// Check the user's prediction. *
if (nextCard.GetValue() == currentCard.GetValue()) { // A tie
DisplayResult("You lose on ties. Sorry!");
correct = false; // End the round
}
else if (nextCard.GetValue() > currentCard.GetValue()) { // Next card is higher
if (guess == 'H') {
DisplayResult("Your prediction was correct.");
correctGuesses++;
}
else {
DisplayResult("Your prediction was incorrect.");
correct = false; // End the round
}
}
else { // nextCards is lower
if (guess == 'L') {
DisplayResult("Your prediction was correct.");
correctGuesses++;
}
else {
DisplayResult("Your prediction was incorrect.");
correct = false; // End round
}
}
currentCard = nextCard;
//System.out.println();
}
DisplayStats(correctGuesses);
return correctGuesses;
}
///////////////////////////////////////////////////////////////////////////////////////////////
//
// Display stats of a round of High/Low
//
// parameters: int correctGuesses - represents the number of corrects guesses for this round
// return: none.
//
////////////////////////////////////////////////////////////////////////////////////////////////
protected void DisplayStats(int correctGuesses)
{
System.out.println();
System.out.println("The game is over.");
System.out.println("You made " + correctGuesses + " correct predictions.");
System.out.println();
}
//////////////////////////////////////////////////////////////////////////////////////////////
//
// Prompt the user for a guess with choices being H (next card will be higher), or
// L (next card will be lower. Displays prompt messages, and then gets the input from a scanner.
// The function will not return until the user inputs an H/h, or a L/l.
//
// parameters: none
//
// return: a Char representing the user's guess.
protected char GuessPrompt()
{
Scanner in = new Scanner(System.in);
char guess;
System.out.println("Will the next card be higher (H) or lower (L)? ");
do {
String buffer;
buffer = in.nextLine();
guess = buffer.charAt(0);
guess = Character.toUpperCase(guess);
if (guess != 'H' && guess != 'L') {
System.out.println("Please respond with H or L: ");
}
} while (guess != 'H' && guess != 'L');
return guess;
}
///////////////////////////////////////////////////////////////////////////////////////////////
//
// Displays the current card that the user will base the guess of high or low from.
//
// parameters: card of type Card representing the last card dealt from the deck. The user
// will guess if the next card delat is higher or lower than this.
// return: none
//
/////////////////////////////////////////////////////////////////////////////////////////////////
protected void DisplayCurrentCard(Card card) {
System.out.println("The current card is " + card);
}
///////////////////////////////////////////////////////////////////////////////////////////////
//
// Displays the next card dealt from the deck after the user's guess. This card will be capared to see if
// it is higher or lower than the last card dealt.
//
// parameters: card of type Card representing the last card dealt from the deck. This card will be compared
// to the last card dealt, along with the user's guess to determine a right or wrong guess.
//
//////////////////////////////////////////////////////////////////////////////////////////////////////
protected void DisplayNextCard(Card card) {
System.out.println("The next card is " + card);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Display result of a round of High/Low
//
// parameters: result of type String indicating whether the use won or lost based on the last card dealt,
// the user guess.
// return: None
//
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
protected void DisplayResult(String result)
{
System.out.println(result);
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Displays the finals stats of all the rounds of Hi/Low played (displays the average score) It computes
// the average score using the data members m_gamesPlayed, and m_sumOfScores.
//
// parameters: none.
// return type none.
//
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
protected void DisplayFinalStats()
{
double averageScore = m_sumOfScores / (double)m_gamesPlayed;
System.out.println("Average score of " + averageScore + " for " + m_gamesPlayed + " rounds played. ");
}
}
这是迄今为止我所拥有的供参考的图形高-低,我知道我现在的代码不起作用,但我希望有人能给我指出正确的方向
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class GHighLow extends HighLow
{
private JFrame m_frame;
private JButton m_play;
private JButton m_exit;
private JButton m_high;
private JButton m_low;
private char m_k;
private JTextArea m_card1;
private JTextArea m_card2;
private JTextField m_input;
/**
* Constructor for objects of class GHighLow
*/
public GHighLow()
{
// constructs highlow
super();
// create inital frame
m_frame = new JFrame();
m_frame.setSize(400,400);
m_frame.setVisible(true);
m_frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
// inital button to play
m_play = new JButton("Play!");
// action listener from listener class
m_play.addActionListener(new Listener());
// button the recieve the players input
m_high = new JButton("High");
m_high.addActionListener(new Listener());
m_low = new JButton("Low");
m_low.addActionListener(new Listener());
JPanel m_bottom = new JPanel();
m_bottom.add(m_play);
m_bottom.add(m_high);
m_bottom.add(m_low);
m_bottom.setBackground(Color.GREEN);
m_frame.add(m_bottom, BorderLayout.SOUTH);
// creates two graphic cards
m_card1 = new JTextArea(10,10);
m_card2 = new JTextArea(10,10);
m_card1.setBackground(Color.BLUE);
m_card2.setBackground(Color.BLUE);
JPanel m_center = new JPanel();
m_center.setBackground(Color.GREEN);
m_center.add(m_card1);
m_center.add(m_card2);
m_frame.add(m_center, BorderLayout.CENTER);
// instruction pane
JOptionPane.showMessageDialog(null," *INSTRUCTIONS*"
+ " The object of the High Low game is simple. The computer will present you a card"
+ " All you have to do is guess if the next card is higher or lower, enjoy!");
}
public class Listener extends HighLow implements ActionListener {
public void actionPerformed (ActionEvent e)
{
Object obj = e.getSource();
if(obj == m_play){
this.Play();
}
else if(obj == m_high) {
m_k = 'H';
}
else if(obj == m_low){
m_k = 'L';
}
else if(obj == m_exit){
m_k = 'N';
}
}
}
public void Play(){
super.Play();
}
}
这需要一个对我来说正常工作的card和deck类,请帮助我找到实现HighLow类的方法,并在其周围包装一个GUI,而不必在GHighLow类中重新创建机制
谢谢,,
Dave您可能希望从将游戏逻辑与GUI代码分离开始。创建这样的子类的最大原因之一是添加功能(如GUI),而无需重写所有代码。在本例中,
GHighLow
类的要点是将GUI添加到由HighLow
实现的现有游戏逻辑中
游戏机制将是使游戏工作的代码。Play()
函数是游戏机制的一个示例。GUI将是为用户设计的一个窗口,用户可以与之交互来玩游戏。基本上,您希望将代码分解为函数,以便GUI函数与游戏机制函数分开,就像您在Play()
和PlayAgainPrompt()中所做的那样Play()
是游戏机制,但它调用GUI函数(playaginprompt()
)PlayAgainPrompt()
使用终端询问用户是否要继续,但如果需要对话框怎么办?您将重写该函数,并改用对话框。对于GUI应该处理的每一位代码,您应该将其放入一个可以重写的函数中。对于作为游戏机制一部分的每一位代码,它都应该在自己的函数中,这样就不必在子类中重写
所有这些都是一个叫做“干”的概念的一部分,或者说“不要重复你自己”。干代码是好代码;如果您重复代码,那么以后需要更改它,返回并修复所有代码是非常烦人的。如果你不把它全部修好,那么可能会引入bug。这就是为什么子类如此有用的原因之一。有关DRY的更多信息,请参见问题。谢谢您的回答,我了解高低级别的功能,但我不确定如何让预先编写的机制与gui@DaveDiienno我已经添加了更多关于这样做的信息,希望能有所帮助。非常感谢你让我理解了背后的逻辑,让我更清楚