0
import java.awt.*;
import java.util.*;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class runner
{

public static void main(String args[])
{
    JFrame test = new JFrame("Tester");
    test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//end on closing window
    test.setVisible(true); //can see
    test.setResizable(false); //can't resize

    test.getContentPane().add(new JFrameGraphics());//where graphics happen

    test.setPreferredSize(new Dimension(500,500));//makes pack useful
    test.pack();//sets sizes
}

}

class JFrameGraphics extends JPanel
{
public boolean button = false; //SUPPOSED to make sure button was pressed

public void paint(Graphics g)
{
    JButton b1 = new JButton ("Button 1");
    add(b1);
    b1.addActionListener(new ActionListener()
    {
        public void actionPerformed(ActionEvent e)
        {
            button = true;
            buttonPressed(g); //supposed to draw giant red oval
            //System.out.println("Worked"); this worked
        }
    });

 }

public void buttonPressed(Graphics g)
{
    if(button = true)
    {
        g.setColor(Color.RED);
        g.fillOval(105,105,200,50);
        //System.out.println("This also worked"); This also worked
    }
}

}

I've gone through with printlns in the console and can see that the buttton works both when the action listener calls the button pressed method and inside the button pressed method. For some reason i can't get any graphics to show up whenever i have a button

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • The Graphics object (`g`) is only valid for a single paint session... after `paint` returns it's not useful any more. – user253751 Mar 16 '18 at 02:20
  • Don't change the component in side paint (ie add components) - painting is for painting the current state, nothing else. Instead of making wild guess, have a look at [Performing Custom Painting](https://docs.oracle.com/javase/tutorial/uiswing/painting/index.html) and [Painting in AWT and Swing](http://www.oracle.com/technetwork/java/painting-140037.html) which describes how painting works – MadProgrammer Mar 16 '18 at 02:39

1 Answers1

0

First of all, for a Swing component, you should be overriding the paintComponent method, not the paint method.

What you have in your current paint method belongs in your initial set-up, otherwise you're adding the listener over and over again every time the component paints.

The code you have in your buttonPressed method is what belongs in your paintComponent method.

kshetline
  • 12,547
  • 4
  • 37
  • 73