试图在我已经绘制的图像上绘制java中的线条,但我无法在图像上找到它?

时间:2016-09-23 00:06:06

标签: java graphics drawing shapes

我必须绘制一个射箭目标,在最里面的圆圈中形成一个十字形的两条黑线,但每次我调整线条以使线条更接近中心时,它会在图像后面而不是出现在顶部。我怎么能阻止这个?它是否需要完全单独的一组指令?

这是我的代码:

package sumshapes;

import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.event.*;
import javax.swing.*;

public class SumShapes extends JFrame 
    implements ActionListener {

    private JPanel panel;

    public void paint(Graphics g)
    {
        g.setColor(Color.BLACK);
        g.drawLine(250, 200, 250, 200);
        g.drawOval(140,90,200,200);
        g.setColor(Color.BLACK);
        g.fillOval(140,90,200,200);
        g.drawOval(162,109,155,155);
        g.setColor(Color.BLUE);
        g.fillOval(162,109,155,155);
        g.drawOval(183,129,112,112);
        g.setColor(Color.RED);
        g.fillOval(183, 129, 112, 112);
        g.drawOval(210,153,60,60);
        g.setColor(Color.YELLOW);
        g.fillOval(210, 153, 60, 60);
        g.setColor(Color.BLACK);


    }

    public static void main(String[] args) {
        SumShapes frame = new SumShapes();
        frame.setSize(500,400);
        frame.setBackground(Color.yellow);
        frame.createGUI();
        frame.setVisible(true);
    }

    private void createGUI(){
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        Container window = getContentPane();
        window.setLayout (new FlowLayout());


    }

    public void actionPerformed(ActionEvent event) {
        Graphics paper = panel.getGraphics();
        paper.drawLine(20,80,120,80);




    }




}

1 个答案:

答案 0 :(得分:-1)

  1. 您的所有绘图都应该放入轻量级组件的paintComponent方法,例如JPanel
  2. 永远不需要致电getGraphics。如果您希望更改特定操作的绘图,您应该a)将逻辑编程为paintComponent b)更改操作中的逻辑c)调用组件上的repaint
  3. 例如:

    private JPanel panel = new JPanel(){
        @Override
        public void paintComponent(Graphics g){
            super.paintComponent(g);//call parent method first thing
            //paint here
        }
        @Override
        public Dimension getPreferredSize(){//provided so you can size this component as necessary
            return new Dimension(500,400);
        }
    };
    
    ....
    frame.add(panel);
    frame.pack();
    

    顺便说一句,我建议将所有调用放在EDT上的Swing组件中 - 这意味着使用SwingUtilities将Swing调用包装在main方法中。例如

    public static void main(String[] args) throws Exception {
        SwingUtilities.invokeAndWait(new Runnable(){
    
            @Override
            public void run() {
                 SumShapes frame = new SumShapes();
                 ....
            }
    
        });
    
    }