绘制图形对象

时间:2015-01-26 14:14:58

标签: java swing graphics jpanel

我想在JFrame中绘制一些东西,所以我决定使用下面的代码但是虽然它真的有用,但我不想要任何ActionListener。

public class Draw
{
    public static void main(String[] args)
    {
        final JPanel jPanel = new JPanel();
        JFrame jFrame = new JFrame("Drawing Window");
        JButton jButton = new JButton("draw");
        jPanel.add(jButton);
        jFrame.add(jPanel);
        jFrame.setBounds(0, 0, 500, 500);

        // first place

        jFrame.setVisible(true);
        jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // second place

        jButton.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                Graphics graphics = jPanel.getGraphics();
                graphics.drawLine(0,0,100,100);
                graphics.drawOval(0,0,100,100);
            }
        });
    }
}

如您所见,我在ActionPerfomed方法中添加了以下代码:

Graphics graphics = jPanel.getGraphics();
graphics.drawLine(0,0,100,100);
graphics.drawOval(0,0,100,100);

现在我想把它放在第一位(代码中的注释位置)但我会得到一个错误,如果我把它放在第二位,我将得到没有错误,但它不会绘制任何东西

似乎有必要将绘图方法放在actionPerformed中,我的问题是为什么?还有其他方法吗?

2 个答案:

答案 0 :(得分:2)

            graphics.drawLine(0,0,100,100);
            graphics.drawOval(0,0,100,100);

需要将这些语句移至paintComponent(Graphics)的重写jPanel方法。


还应该覆盖面板的getPreferredSize()方法以返回500x500的维度,然后代替:

jFrame.setBounds(0, 0, 500, 500); 

只需致电:

jFrame.pack(); 

答案 1 :(得分:0)

另一个选择是制作方法( paintComponent 绘制):

public void paintComponent(Graphics graphics){

        graphics.drawLine(0,0,100,100);
        graphics.drawOval(0,0,100,100);

}

并从actionListener调用重绘,如图所示..

public void actionPerformed(ActionEvent action){


   repaint();
 }

如果它对您有用,您可以根据需要进行转换....