Search code examples
javaactionlistenerpaintcomponent

paintComponent() not activatedby actionListener


I'm currently working on a piece of code for school and I'm seriously stuck. So what I am trying to do is through a JTextField, have the user enter either "rektangel" or "cirkel" and then push a button. After that, the program is supposed to print out either a rectangle or a circle.

So I got an ActionListener connected to the button, which in turn activates a method which decides what the user wants to print. So then I've tried to access the paintComponent method by creating an instance of the painter Class I have. However, it doesn't seem to work as it never prints anything.

Sorry for my poor description, but I'm seriously lost and don't really know where the issue might be other than it probably has something to do with repaint(); not activating the paintCompontent.

Here's my code, so if anyone could help me find the problem I'd be very grateful.

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener; 
public class FigurRitare {
public String Figur = " ";
public Boolean activator = false;
public int draw = 0;
private JPanel mainPanel;
private JButton registreraButton;
private JTextField textField1;
private JPanel DrawingBord;

public FigurRitare() {
    registreraButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            String inputString = textField1.getText();
            decider(inputString);
        }
    });
}

public static void main(String[] args) {
    //Skapa ditt fönster
    JFrame frame = new JFrame("Hello World!");
    //Tala om att du vill kunna stänga ditt förnster med krysset i högra hörnet
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //Ange storleken på ditt fönster och att det ska vara fast
    frame.setSize(500, 600);
    frame.setResizable(false);
    //Positionera ditt fönster i mitten av skärmen
    frame.setLocationRelativeTo(null);

    //Skapa en instans av din den här klassen som hanterar din panel
    FigurRitare myForm = new FigurRitare();
    //Lägg in din panel i programfönstret
    frame.setContentPane(myForm.mainPanel);
    //Visa programfönstret på skärmen
    frame.setVisible(true);

}

public void decider(String input) {
    ritPanel rita = new ritPanel();
    String Cirkel = "cirkel";
    String Rektangel = "rektangel";
    if (input.matches(Cirkel)) {
        rita.whatToDraw(1);
        textField1.setText("");
        textField1.requestFocusInWindow();
    } else if (input.matches(Rektangel)) {
        rita.whatToDraw(2);
        Figur = Rektangel;
        textField1.setText("");
        textField1.requestFocusInWindow();
    } else {
        JOptionPane.showMessageDialog(mainPanel, "Vänligen ange antingen cirkel eller rektangel i rutan ovanför");
        textField1.setText("");
        textField1.requestFocusInWindow();
    }
}

private void createUIComponents() {
    // TODO: place custom component creation code here
    DrawingBord = new ritPanel();
}

class ritPanel extends JPanel {

    public void whatToDraw(int toDraw) {
        draw = toDraw;
        repaint();
    }

    @Override
    public void paintComponent(Graphics grafik) {
        super.paintComponent(grafik);
        if (draw == 2) {
            grafik.fillRect(100, 100, 100, 100);
        }
        if (draw == 1) {
            grafik.fillOval(100, 100, 100, 100);
        }
    }
}

Solution

  • I apologise for the extremely late answer, but here is the code:

    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener; 
    public class FigurRitare
    {
        public String Figur = " ";
        public Boolean activator = false;
        public int draw = 0;
        private JPanel mainPanel;
        private JButton registreraButton;
        private JTextField textField1;
        private JPanel DrawingBord;
    
        public FigurRitare() {
            registreraButton = new JButton("Submit");
            mainPanel = new JPanel();
            textField1 = new JTextField();
    
            mainPanel.setLayout(new GridLayout(2, 1));
    
            registreraButton.addActionListener(new ActionListener()
                {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        String inputString = textField1.getText();
                        decider(inputString);
                    }
                });
    
            mainPanel.add(registreraButton);
            mainPanel.add(textField1);
        }
    
        public static void main()
        {
            //Skapa ditt fönster
            JFrame frame = new JFrame("Hello World!");
            //Tala om att du vill kunna stänga ditt förnster med krysset i högra hörnet
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //Ange storleken på ditt fönster och att det ska vara fast
            frame.setSize(500, 600);
            frame.setResizable(false);
            //Positionera ditt fönster i mitten av skärmen
            frame.setLocationRelativeTo(null);
    
            //Skapa en instans av din den här klassen som hanterar din panel
            FigurRitare myForm = new FigurRitare();
            frame.setLayout(null);
            //Lägg in din panel i programfönstret
            frame.setContentPane(myForm.mainPanel);
            //Visa programfönstret på skärmen
            frame.setVisible(true);
        }
    
        public void decider(String input)
        {
            ritPanel rita = new ritPanel();
            if (input.equalsIgnoreCase("Cirkel")) {
                JFrame NewFrame = new JFrame("Cirkel");
                NewFrame.setVisible(true);
                NewFrame.setSize(500, 500);
                NewFrame.add(rita);
                rita.whatToDraw(1);
                textField1.setText("");
                textField1.requestFocusInWindow();
            } else if (input.equalsIgnoreCase("Rektangel")) {
                JFrame NewFrame = new JFrame("Rektangel");
                NewFrame.setVisible(true);
                NewFrame.setSize(500, 500);
                NewFrame.add(rita);
                rita.whatToDraw(2);
                textField1.setText("");
                textField1.requestFocusInWindow();
            } else {
                JOptionPane.showMessageDialog(mainPanel, "Vänligen ange antingen cirkel eller rektangel i rutan ovanför");
                textField1.setText("");
                textField1.requestFocusInWindow();
            }
        }
    
        private void createUIComponents() {
            // TODO: place custom component creation code here
            DrawingBord = new ritPanel();
        }
    
        class ritPanel extends JPanel {
    
            public void whatToDraw(int toDraw) {
                draw = toDraw;
                repaint();
            }
    
            @Override
            public void paintComponent(Graphics grafik) {
                super.paintComponent(grafik);
                if (draw == 2) {
                    grafik.fillRect(100, 100, 100, 100);
                }
                if (draw == 1) {
                    grafik.fillOval(100, 100, 100, 100);
                }
            }
        }
    }
    

    As mentioned in the comments, A NullPointerException would be thrown if your code was executed as is. To avoid this, you should initialize all member variables in the constructor, here FigureRitare().

    I have removed some unnecessary variables such as String Rektangel and String Cirkel, but otherwise the original code is maintained.

    I have set the layout of mainPanel to a GridLayout with two rows and one column, just for better visual appeal :)
    Remember to add the necessary components like JButton and JTextField to the panel like this: mainPanel.add(registreraButton) so that they actually do appear on the panel.

    Another thing was that you drew the shapes on the JPanel successfully, but you didn't add the panel to any JFrame. I've taken the liberty to do so by using:

    JFrame NewFrame = new JFrame("Cirkel");
    NewFrame.setVisible(true);
    NewFrame.setSize(500, 500);
    NewFrame.add(rita);
    

    for both cases, whether the user enters 'rektangel' or 'cirkel'.

    Finally, I've removed the input.matches() that you have used to check the input, and replaced them with input.equalsIgnoreCase() which checks if the input is the same as "rektangel" or "cirkel", whether the input is in capitals or not (case-insensitive)