Hey;

I'm trying to do a hang man game in Java. I newly learned some stuff about programming some GUI using Swing and AWT, but I'm not still clear with it.

The problem is that all the drawing is done by a single function paintComponent() from the JPanel that I should add to the JFrame. The function does not give me flexibility to take some parameters, there is only one parameter, Graphics object.

I want to be able to respond to the users answer/input to the program and draw some primitive shapes such as lines and circles. But I have only one function, and that does not let me pass parameters to it.

I know I got something wrong there but I cant make my way out. So can you tell me what I got wrong and a code snippet to show me that draws a line if user inputs a "line" in a text box and a circle if the user inputs a "circle".

class MyPanel extends JPanel
    {

    @Override
    public void paintComponent(Graphics g)//This function always does the same, no interaction with user inputs
    {
        Graphics2D graph = (Graphics2D)g;
        graph.draw(new Ellipse2D.Double(100, 100, 200, 300));
        
        graph.drawString("Heeeyy!!!", 100, 400);
        Rectangle2D rec = new Rectangle2D.Double(100, 100, 50, 50);
        graph.draw(rec);

        Line2D line = new Line2D.Double(new Point2D.Double(0,0), new Point2D.Double(300, 400));
        graph.draw(line);
        graph.setPaint(Color.MAGENTA);
        graph.fill(rec);
    }
}

Add some instance variables to your class (eg a list of shapes, colours, positions ...). Add some public methods to set those variables. Use the variables in paintComponent method to control what/where/how you paint

Ok, I was thinking about what you told too, I wanted to know if there is a more convenient way to do that. So that is how all java programmers do or should do ?

Yes, that, in general terms, is how its done. The instance variables may hold the info needed to do all the work in paintComponent, or they may just be a list of objects that have their own paint methods that can be called from paintComponent to delegate the work. Those 2 options pretty much cover it; experienced developers may be more likely to go for the second variant, depending on the exact requirements.

but at the beginning you have to decide

1/ I'm just want to pass painting via constructor with
ObjectType (Line, Oval...)
and with
Sizing into Container

2/ all from point 1st. plus something more that plain paints (remove painted Object, move Object into Container....)

3/ all from both above points (1st and 2nd.) plus with painting Container too
(BackGroung, Border, GradientPaint, add JComponent, Transparency ....)

4/ :-)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.