why isn't the square drawing when i type 1 or 2?

47 Views Asked by At

here's the code but I don't know why it doesn't work I've tried adding a revalidate and a repaint but the square won't draw, I'm trying to make the square move over a bit when 2 is entered and the 1 is there as an attempt to force a refresh and draw the square but it never worked unless i just have the square be still but as said i want it to move

import javax.swing.*;
public class App {
    public static void main(String[] args){

        JFrame frame = new JFrame("test");
        frame.setSize(1000, 1000);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
        frame.add(new DrawSquare());
        System.out.println("end");
        while (true==true){
        frame.revalidate();
        System.out.println("should work");
    }
}
}
import java.awt.Graphics;
import java.util.Scanner;


import javax.swing.JFrame;
import javax.swing.JPanel;




public class DrawSquare extends JPanel {
    
    @Override
    public void paintComponent(Graphics g) {
        g.setColor(java.awt.Color.red);
        super.paintComponent(g);
        Integer x = 90;
        Integer y = 0;
        JFrame frame = new JFrame("test");
       
        while (y==0){
        
        
        
        while (true){
            frame.revalidate();
            Scanner myObj = new Scanner(System.in); 
    System.out.println("Enter command 1=draw square 2= move square");

    Integer input = myObj.nextInt(); 
    System.out.println("Next step: " + input);
    if(input == 2){
        x=x+1;
        input = 3;
    } 
    if(input == 1 ){
    
        g.setColor(java.awt.Color.red);
        g.drawRect(x, x, x, x);
        g.fillRect(x,x,x,x);  
        frame.repaint();
        frame.revalidate();
        System.out.println("WHY");
     break;
    }
            g.setColor(java.awt.Color.red);
            g.drawRect(100, x, 100, 100);
            g.fillRect(100,x,100,100);  
            System.out.println("sqlaie");
            
           
            frame.revalidate();
           

          
}
            
    }


    }

    }
1

There are 1 best solutions below

0
MadProgrammer On

First...

while (true==true){
    frame.revalidate();
    System.out.println("should work");
}

No it shouldn't (work). Free cycling loops like this are capable of consuming all you CPU cycles which could prevent your program from performing other tasks (ie thread starvation). revalidate won't repaint the UI anyway, it's used to update the layout of the components within a given container.

Then...

g.setColor(java.awt.Color.red);
super.paintComponent(g);

paintComponent will set the color of the Graphics to the background color of the component, which means that your previous call will be undone. Call paintComponent first, then perform your custom painting.

Then...

@Override
public void paintComponent(Graphics g) {
    //...
    JFrame frame = new JFrame("test");

Ah, why? Apart from create another frame each time paintComponent is been called, this has nothing to do with what's been presented on the screen and is otherwise just a complete waste of time and resources.

And then...

while (y == 0) {
    while (true) {
        frame.revalidate();
        //...

This is going to cause your program to hang, prevent any further updates to the UI and user input being captured.

paintComponent is expected to paint the current state and exit as fast as possible, you should avoid doing extra processing which could otherwise be done else where.

and finally...

Scanner myObj = new Scanner(System.in);

Don't use Scanner for user input in a GUI environment, this isn't how user input is monitored for.

Everything speaks volumes of your lack of understanding and appropriate research into how to solve these problems.

Stackoverflow is not a tutorial site and you should spend the time researching your problems and attempting to fix them before posting. Once you've reached this point, SO becomes useful to you.

I would highly recommend taking a look at Painting in AWT and Swing and Performing Custom Painting to get a better understanding of how the paint system works and How to Use Key Bindings for details about how to monitor and respond to user input

I would avoid KeyListener as it's problematic.

Runnable example

import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;

public class Main {

    public static void main(String[] args) {
        new Main();
    }

    public Main() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame frame = new JFrame("Test");
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    protected class TestPane extends JPanel {

        private int x = 90;
        private int y = 90;

        public TestPane() {
            InputMap im = getInputMap(WHEN_IN_FOCUSED_WINDOW);
            ActionMap am = getActionMap();

            im.put(KeyStroke.getKeyStroke(KeyEvent.VK_1, 0), "pressed.one");
            im.put(KeyStroke.getKeyStroke(KeyEvent.VK_2, 0), "pressed.two");

            am.put("pressed.one", new AbstractAction() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    // Really, kind of pointless here
                    repaint();
                }
            });
            am.put("pressed.two", new AbstractAction() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    x += 5;
                    repaint();
                }
            });
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 200);
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();
            g2d.setColor(Color.RED);
            g2d.fillRect(x, y, 20, 20);
            g2d.dispose();
        }
    }
}