yazz
yazz

Reputation: 11

How do I clear my display while using Jframe to display new dialogue?

I've been trying to code a program or 'game' which transfers to new scenarios depending on whatever the user chooses to do. The user will be given an option to choose 'A' or 'B'. In order to do that, i need to display the information that the user needs, but I cannot remove the past dialogue, which leads to overlapping go the text and makes it impossible to read.

import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class Window extends JFrame{
  private static final long serialVersionUID = 1L;
  public static String name, choice;
  public static BufferedImage wizard;
  public static int width = 640;
  public static int height = 400;
  static String write =   
    "You will be entering a new world now!\nOne where your decision may either save you or cost you your life.\nYou will be given two options to choose from.\nPlease enter the letters 'A' or 'B' and if you wish to leave, '!'.\npress 'ENTER' to begin!";

  public Window() { //first method that gets called from other class
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    setTitle("Yasaman's game");

    setSize(width, height);
    setResizable(true);
    setLocation(0,0);
    setVisible(true);
    setLayout(new FlowLayout());
    setAlwaysOnTop(true);
    readWizard();
    name = JOptionPane.showInputDialog("What is your name");
    repaint();
  }

  private void readWizard() { //read wizard from file
    try {
      wizard = ImageIO.read(new File("magic.png"));
    } catch (IOException e) {
      System.out.println("Somebody ate my Wizard!");
    }
  }

  public void paint(Graphics g) //this is the god method, everything that you want to put onto the screen goes in here
  {
    int sBx = 100;
    int sBy = 100;
    int sBwid = 400;
    int sBhei = 200;
    int sBcurve = 50;
    super.paint(g);
    Graphics2D g2 = (Graphics2D) g;

    g2.setColor(new Color(0, 255, 155));
    if(wizard != null) {
      g2.drawImage(wizard,0,0, this);
    }else {
      System.out.println("Wizard was eaten alive, have a box");
    }
    g2.fillRoundRect(sBx, sBy, sBwid, sBhei, sBcurve, sBcurve);
    g2.fillRect(100, 100, 100, 100);
    g2.setColor(new Color(0,0,0));

//THIS IS WHERE THE PROBLEM BEGINS

    g2.setBackground(new Color(255, 255, 255));
    int y = 170;
    if (write!= null)
    for(String line: write.split("\n"))
      g2.drawString(line, 130, y+= g.getFontMetrics().getHeight());

    //g2.setBackground(new Color(255, 255, 255));


    senario1();
    y = 170;
    if (write!= null)
    for(String line: write.split("\n"))
      g2.drawString(line, 130, y+= g.getFontMetrics().getHeight());

    choice = JOptionPane.showInputDialog("Would you A. Stay Home , B. Go to school ?");
    if (choice.equalsIgnoreCase("B")){
      //g2.setBackground(new Color(255, 255, 255));
      senario2();
      y = 170;
      if (write!= null)
      for(String line: write.split("\n"))
        g2.drawString(line, 130, y+= g.getFontMetrics().getHeight());
    }
  }

  public static void senario1(){
    write = "Today is the day.\nThe day you can finally use your magic to hustle through life.\nBefore you use your powers, you must learn how to use them!\nLet's get started!\n";

  }
  public static void senario2(){
    write = "You are so lazy! It's okay though if you had went to school\n, due to many unfortunate events your life would have ended... \n\nOr maybe not...";

  }

}

How would I be able to remove the past text to display the new ones. Also the fisr display and the second display merge together for some reason.

Thank you and please help me I really appriciate it!

Upvotes: 1

Views: 31

Answers (1)

Alex Cuadrón
Alex Cuadrón

Reputation: 688

First of all the code inside the paint function was a mess. that function is meant to be used for drawing porpuses, not for lots of if...else statements (because each time you resize the frame, the paint method is being called and can cause your app to be very laggy). Anyway, I've created a separated class so everytime you hit "enter" writes value changes:

class adapter extends KeyAdapter{

    @Override
    public void keyPressed(KeyEvent e) {
        if(e.getKeyCode() == KeyEvent.VK_ENTER){
            Draw.write = nextScenario();
            repaint();
        }
    }
}

Then I've added a FocusListener to the Window constructor so you can hit enter while you're doing other stuff and the app doesn't do something "strange":

public Draw() { //first method that gets called from other class
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    setTitle("Yasaman's game");
    write =
            "You will be entering a new world now!\nOne where your decision may either save you or cost you your life.\nYou will be given two options to choose from.\nPlease enter the letters 'A' or 'B' and if you wish to leave, '!'.\npress 'ENTER' to begin!";

    setSize(width, height);
    setResizable(true);
    adapter adapter = new adapter();
    addFocusListener(new FocusListener() {
        @Override
        public void focusGained(FocusEvent e) {

            addKeyListener(adapter);

        }

        @Override
        public void focusLost(FocusEvent e) {

            removeKeyListener(adapter);

        }
    });

    setLocation(0,0);
    setVisible(true);
    readWizard();
    name = JOptionPane.showInputDialog("What is your name?");
    repaint();
}

Then, I've created a "nextscenario" function for switching between scenarios in an easy way. private static int scenario = 0;and the method which is being called from the KeyListener class:

private static String nextScenario(){

    switch(scenario) {
        case 0:
            scenario++; return senario1();
        case 1:
            scenario++; return senario2();
        default:
            return null;
    }

}

Finally the paint function became this "short" for being more efficent:

public void paint(Graphics g) //this is the god method, everything that you want to put onto the screen goes in here
{
    int sBx = 100;
    int sBy = 100;
    int sBwid = 400;
    int sBhei = 200;
    int sBcurve = 50;
    int y = 170;
    super.paint(g);
    Graphics2D g2 = (Graphics2D) g;

        g2.setColor(new Color(0, 255, 155));
        if (wizard != null) {
            g2.drawImage(wizard, 0, 0, this);
        } else {
            System.out.println("Wizard was eaten alive, have a box");
        }
        g2.fillRoundRect(sBx, sBy, sBwid, sBhei, sBcurve, sBcurve);
        g2.fillRect(100, 100, 100, 100);
        g2.setColor(new Color(0, 0, 0));
        g2.setBackground(new Color(255, 255, 255));
        for (String line : write.split("\n"))
        g2.drawString(line, 130, y += g.getFontMetrics().getHeight());

    }

If there's any problem let me know and I'll solve it to you. Mark as answer if it solved your problem! :D

Upvotes: 1

Related Questions