Java的GUI刽子手无法正常显示 [英] Java Hangman GUI not properly displaying

查看:822
本文介绍了Java的GUI刽子手无法正常显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个不同的问题,我的code,其中大部分都是基于图形用户界面的问题,但我有一个问题的ActionEvent。我将张贴在我的部分code第一次那么我会指出这个问题与每个部分具体是什么。 *注意,所有我的code的将是如何实际上是我的IDE命令。

I'm having a couple of different problems with my code, most of them are GUI based problems but i do have one actionevent problem. I will post my code in sections first then I will point out what the issue is specifically with each section. *note all of my code will be in order of how is actually in my IDE.

如果您想复制我的code,而不此处所有的其他的东西它是引擎收录:的http:// pastebin.com/HHjRRtGZ

If you wish to copy my code without all of the other stuff here it is on pastebin: http://pastebin.com/HHjRRtGZ

我的进口:

import java.awt.*;
import java.awt.event.*;

import javax.swing.*; //Makes it a Japplet

import java.util.Random;

我的计划从这里开始:

My Program Starts here:

public class Hangman extends JApplet implements ActionListener {

    // How many times you can guess the wrong letter till you lose
    static final int DEAD = 7;   

    private int errors;        // amount of errors
    private String message;   // Message displaying either Error or Victory
    private String information; // Secondary Message
    private String RealWord;      // The Real word
    private StringBuffer GuessWord;// The Guessed word
    private Button StartBtn;      // The Restart Button
    private Button GoBtn;         // The Go Button
    private TextField LetterBox; // The LetterBox

我的ActionEvent:

My ActionEvent:

    public void actionPerformed(ActionEvent e){

        if (e.getSource() == StartBtn){
            initGame();
        }

        if (e.getSource() == GoBtn){

            processTurn();

            LetterBox.setText("");
            repaint();
        }
    }

问题一:

这是我与我的Action事件遇到的问题是,当我打的StartBtn它不会重新初始化一切。没有被清除。什么都不做。它不会做任何事情。所以这是个问题在那里。

The problem that I am having with my Action event is that when I hit the StartBtn it does not reinitialize everything. Nothing is cleared. Nothing is done. It doesn't do anything. So that's the issue there.

我的init()函数(这是我的一个问题所在。

My init() function (This is where one of my problems lie.

    public void init() {

        // Create a "Textbox" for the letter guessing
        LetterBox = new TextField();

        //Create my buttons and labels
        StartBtn = new Button("Restart");
        GoBtn = new Button("Go");

        //Add the elements to the applet

        JPanel p = new JPanel();
        p.setLayout(new FlowLayout());

        p.add(StartBtn);
        p.add(new Label("Guess a letter"));
        p.add(LetterBox);
        p.add(GoBtn);

        add(p, BorderLayout.SOUTH);

        //Make buttons event listeners
        StartBtn.addActionListener(this);
        GoBtn.addActionListener(this);

        //Startup the Game
        initGame();

    }

2的问题(主要问题):

我的初始化code会影响我的GUI是实际猜字区和刽子手面积是种搞砸了我的问题。这很难解释,所以我会告诉你的图像。几乎所有形式的背景是完全透明的。所以它只是使用的不管它是什么就因为它的回地面之上的静止图像。

The problems I have with my Init code that affect my GUI is that the actual word guess area and the hangman area are kind of messed up. It's hard to explain, so i'll show you an image. The Backdrop for almost all of the form is completely transparent. So it just uses a still image of whatever it was on top of as it's back ground.

问题3:
有与图像其他一些问题,你可以看到。在code是进一步下跌但是对于那些部分。但是,正如你所知道的,消息不明确,只写了对方,即使我他们指定(你会看到进一步的下降)。

Problem 3: There are some other issues with the image as you can see. The code is further down for those parts however. But as you can tell, the messages do not clear and just write over each other, even though I specify them to (which you will see further down).

问题4:
现在,你猜的信之前,这个词是隐藏着有,但是当你猜一个正确的字母单词它应该取代的用正确的字母猜测。然而,它只是把的它在它的上面(你会看到code这下面还有)。

Problem 4: Now before you guess any letters, the word is hidden with a "" but when you guess a correct letter for the word it's supposed to replace the "" with the correct letter guessed. However it just put's it on top of it (you will see the code for this below as well).

这是游戏初始化

    public void initGame() {
        //Set the errors to 0
        errors = 0;

        //Enter the wordslist, separated by a | here
        String str = "write|program|receive|positive|variables|temporary|good|bad|test";        
        String[] temp;


        //delimiter
        String delimiter = "\\|";

        // given string will be split by the argument delimiter provided.
        temp = str.split(delimiter);

        //Create the Random Seed Generator
        Random RandGenerator = new Random();

        //Generate my Random Number
        int randomInt = RandGenerator.nextInt(temp.length);

        RealWord = new String(temp[randomInt]);

        char positions[] = new char[RealWord.length()];

就在这里,它取代屏幕上的unguessed字符用*。

Right here is where it replaces the unguessed characters on screen with a "*".

        for (int i = 0; i < RealWord.length(); i++) {
            positions[i] = '*';
        }


        String s = new String(positions);
        GuessWord = new StringBuffer(s);

        LetterBox.setText("");

        //Delete Messages
        message = "";
        information = "";
        repaint();
    }

我的绘画功能

    @Override
    public void paint(Graphics g) {

        int BaseY = 250;

        //THE HANGING STAND
        if (errors > 0) { //1 Error
            g.drawLine(90, BaseY, 200, BaseY); //The ground
            g.drawLine(125, BaseY, 125, BaseY-100); //The bar going up
            g.drawLine(125, BaseY-100, 175, BaseY-100); //The sidebar
            g.drawLine(175, BaseY-100, 175, BaseY-75); //The Rope
        }

        //THE PERSON
        if (errors > 1) { 
           g.drawOval(170, BaseY-75, 10, 12); // The Head       
        }

        if (errors > 2) { 
           g.drawLine(175, BaseY-62, 175, BaseY-45); // The Body    
        }

        if (errors > 3) { 
           g.drawLine(165, BaseY-65, 175, BaseY-55); // Left Arm  
        }

        if (errors > 4) { 
           g.drawLine(185, BaseY-65, 175, BaseY-55); // Right Arm 
        }

        if (errors > 5) { 
           g.drawLine(170, BaseY-30, 175, BaseY-45); //Left Leg       
        }

        if (errors > 6) {  //7 Errors
           g.drawLine(175, BaseY-45, 180, BaseY-30); // Right Left 
        }


        //Show Messages/Errors
        g.drawString(message, 40, BaseY+25);
        g.drawString(information, 25, BaseY+45);
        g.drawString(new String (GuessWord), 140, BaseY-120);

        g.drawString(new String("WELCOME TO HANGMAN!"), 75, 40);
    }

这就是神奇发生了很多。这是processTurn功能

This is where alot of the magic happens. This is the processTurn Function

    private void processTurn() {

        String s, t;
        char a;

        s = LetterBox.getText();
        a = s.charAt(0);

        if (!Character.isLetter(a)) {
            message = "Only enter letters please.";
            return;
        }

        if (s.length() > 1) {
            message = "One letter at a time please.";
            return;
        }

        //Check if letter has been used already
        t = new String(GuessWord);
        if (t.indexOf(s) != -1) {
            message = "You have already guessed with that letter!";
            return;
        }

        //If the letter you guessed does not occur in the Real Word
        if (RealWord.indexOf(s) == -1) {

            message = "";
            errors++;

            if (errors==DEAD) {
                message = "Sorry, you lose";
                information = "Click restart to try again!";

                //INSERT MOVING HANGMAN HERE.
            }

            return;
        }

这是这里的*应该与correctl猜测字母代替,但它不能正常工作!

This is where the "*" is supposed to be replaced with the correctl guessed letter but it doesn't work correctly!

        //Replace stars in the Guessed Word with the found letter
        for (int i = 0; i < RealWord.length(); i++) {
            if (RealWord.charAt(i) == a) {
                GuessWord.setCharAt(i, a);
            }
        }

        t = new String(GuessWord);

        //If all of the stars have been filled, then you win!
        if (t.indexOf('*') == -1) {
            message = "You have won!";
            return;
        }

        //Delete the Message
        message = "";
        repaint();
    }

主要功能

    public static void main(String[] args) {

        JFrame frame = new JFrame();
        JApplet applet = new Hangman();

        applet.init();
        applet.start();
        frame.add(applet);

        frame.setSize(300, 400);
        frame.setLocationRelativeTo(null); // Center the frame
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);


    }
}

任何及所有的援助将大大AP $ P $提前pciated :)谢谢!

Any and all assistance will be greatly appreciated :) Thanks in advance!

推荐答案

这是基本的事实,你已经打破了油漆链造成的。

This is caused by the basic fact that you have broken the paint chain.

在AWT / Swing的绘画是由方法调用链中。如果你忽视维持这个链,你开始​​结束了油漆的文物,其形式为您所看到的。

Painting in AWT/Swing is made of a chain of method calls. If you neglect to maintain this chain, you start ending up with paint artifacts, in the form you are seeing.

图形上下文是一个共享的资源,那就是,在任何给定的涂料循环绘每个组件将被赋予相同的图形资源。每个组件绘画到它之前预计prepare的图形背景...

The Graphics context is a shared resource, that is, every component painted during any given paint cycle will be given the same Graphics resource. Each component is expected to prepare the Graphics context before painting to it...

要解决这个问题,在你所有的油漆方法,你应该叫 super.paint(G)以确保油漆链维持,图形上下文是针对单个组件绘画需要$ p $每年preD。

To fix the problem, in all your paint methods, you should be calling super.paint(g) to ensure that the paint chain is maintained and that the Graphics context is preapred for the individual components painting needs.

说了这么多。不建议重写油漆顶层容器。相反,我们建议您使用像一个执行您的自定义绘制的JP​​anel 并重写它的的paintComponent 方法来代替(确保您致电 super.paintComponent方法以及!)

Having said that. It is not recommended to override paint of top level containers. Instead, it is recommended that you perform your custom painting using something like a JPanel and override it's paintComponent method instead (ensuring that you call super.paintComponent as well!)

这有一个至少有两个基本的好处。第一个是,你可以知道决定在哪里面板应该显示,例如,你可以将其添加到 JApplet的的JFrame 或你认为合适的其他容器中。它是双默认缓冲。这意味着你不会看到当画被更新任何闪烁。

This has a least two basic benefits. The first is, you can know decide where the panel should be displayed, for example, you could add it to an JApplet or JFrame or other container as you see fit. It is double buffered by default. This means you won't see any flicker when the painting is updated.

您应该考虑将你的应用分解成小板,专注于每个组件分别需要。这将有助于减少应用程序的复杂性,并使其更容易地管理你的应用程序的每个部分的个性化需求。

You should consider breaking your application down into small panels, focusing on each of the components needs separately. This will help reduce the complexity of your application and make it easier to manage the individual needs of each section of your application.

看看表演风俗画并的绘画在AWT和Swing 了解更多详情

这篇关于Java的GUI刽子手无法正常显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆