当我点击我的JButton时,为什么我的代码没有绘制任何内容?

时间:2018-03-16 02:09:26

标签: java swing graphics jpanel jbutton

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
    }
}

}

我已经在控制台中使用了printlns,并且可以看到当动作侦听器调用按钮按下方法和按钮按下方法时,按钮都可以工作。出于某种原因,只要有按钮,我就无法显示任何图形

1 个答案:

答案 0 :(得分:0)

首先,对于Swing组件,您应该覆盖paintComponent方法,而不是paint方法。

您当前paint方法中的内容属于初始设置,否则每次组件绘制时都会反复添加侦听器。

buttonPressed方法中的代码属于paintComponent方法。