我正在编写一个模拟单轮纸牌游戏WAR的程序。
我不知道如何以图形方式显示卡片(数字/颜色/套装)。
import java.util.*; // for Scanner class
import java.awt.*;
import javax.swing.*;
// Class Definition
class Project4 {
// Main method definition
public static void main(String[] args) {
// Object and Variable Declarations
JFrame win;
Container contentPane;
Graphics g;
String player1Name, player2Name, scoreWinLoss;
//This is the graphics portion, all of the graphics (so far) are working.
win = new JFrame("War Game");
win.setSize(900, 600);
win.setLocation(100, 100);
win.setVisible(true);
win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Color white = new Color(255, 255, 255);
Color white2 = new Color(255, 255, 255);
Color black = new Color(0, 0, 0);
Color black2 = new Color(0, 0, 0);
contentPane = win.getContentPane();
//Also if anyone knows how to change this .setBackground(Color.Green)from lime green to forest(card table) green that would be awesome!
contentPane.setBackground(Color.GREEN);
g = contentPane.getGraphics();
Font font = new Font("Serif", Font.BOLD, 25);
g.setFont(font);
try {
Thread.sleep(200);
} catch (Exception e) {}
player1Name = JOptionPane.showInputDialog(null, "Player 1, what is your name?");
player2Name = JOptionPane.showInputDialog(null, "Player 2, what is your name?");
g.setColor(black);
g.drawString(player1Name, 220, 35);
g.setColor(black2);
g.drawString(player2Name, 625, 35);
g.setColor(white);
g.fillRoundRect(125, 50, 250, 450, 20, 20);
g.setColor(white2);
g.fillRoundRect(525, 50, 250, 450, 20, 20);
g.setColor(black);
g.drawRoundRect(125, 50, 250, 450, 20, 20);
g.setColor(black2);
g.drawRoundRect(525, 50, 250, 450, 20, 20);
//This is where it gets confusing and this stuff is all not working
int card1Max = 14, card1Min = 2, card2Max = 14, card2Min = 2, randomNum1 = 0, randomNum2 = 0;
g.setColor(black);
g.drawInt(randomNum1, 150, 35);
g.setColor(black2);
g.drawInt(randomNum2, 500, 35);
Random randomPicker = new Random(System.currentTimeMillis());
randomNum1 = randomPicker.nextInt(card1Max - card1Min + 1) + card1Min;
randomNum2 = randomPicker.nextInt(card2Max - card2Min + 1) + card2Min;
if (randomNum1 < randomNum2) {
scoreWinLoss = player2Name + " won!";
} else if (randomNum1 > randomNum2) {
scoreWinLoss = player1Name + " won!";
} else if (randomNum1 == randomNum2) {
scoreWinLoss = "It's a tie! Play again to determine a winner.";
}
答案 0 :(得分:0)
不要像你一样玩图形对象:
g.setColor(black);
g.drawString(player1Name, 220, 35);
这很糟糕!
相反,你应该看一下布局。查看 GridLayout 或 GridBagLayout 。这些允许您将JPanels组织为网格。使用这些面板,您可以设置背景颜色并添加文本(通过JLabel)。
答案 1 :(得分:0)
如果我理解您的问题:以简单的方式,您可以将JPanel
与CardLayout
一起使用,然后通过JLabel.setImageIcon(ImageIcon imageIcon)
JLabel
方法设置来自网络的卡片图片这张照片和CardLayout
上的照片会带来卡片。