Java绘图程序

Java drawing program

我正在尝试创建一个简单的绘图程序,其中包含一个工具栏和一个绘图区域。该程序的主要 window 是一个 JFrame。我添加了一个 JToolBar 和一个 JPanel (drawingPanel) 用于绘制。但是,这条线不是画在 drawingPanel 上而是画在它后面(当我删除 drawingPanel 时我可以看到这条线 - 只需注释掉 CreateDrawingPanel();)。如何在 drawingPanel 上画线?

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JToolBar;
import javax.swing.SwingUtilities;

public class UserInterface extends JPanel 
{
    static JFrame frame;
    static JPanel drawingPanel;

    public static void main(String[] args) 
    {
        SwingUtilities.invokeLater(new Runnable() 
        {
            public void run() 
            {
                CreateFrame();
            }
        });
    }

    private static void CreateFrame()
    {
        frame = new JFrame("Interface");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(500,500);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
        frame.setExtendedState(Frame.MAXIMIZED_BOTH);
        frame.add(new UserInterface());
    }

    public UserInterface()
    {
        setLayout(new BorderLayout());
        CreateToolBar();
        CreateDrawingPanel();
        repaint();
    }

    private void CreateToolBar()
    {
        JToolBar toolbar = new JToolBar(JToolBar.VERTICAL);
        JButton button = new JButton("Some button");
        toolbar.add(button);
        add(toolbar, BorderLayout.WEST);
        toolbar.setBackground(Color.black);
        toolbar.setFloatable(false);
    }

    private void CreateDrawingPanel()
    {
        drawingPanel = new JPanel();
        add(drawingPanel, BorderLayout.CENTER);
        drawingPanel.setBackground(Color.white);
    }

    public void paintComponent(Graphics g)
    {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g;
        g2.drawLine(100, 100, 120, 500);
    }

}

您的所有绘图都在 UserInterface 对象上,因为这是您覆盖 paintComponent().

的地方

删除 paintComponent() 覆盖,并更改 createDrawingPanel():

 private void CreateDrawingPanel()
{
    drawingPanel = new JPanel(){

        public void paintComponent(Graphics g)
        {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D) g;
            g2.drawLine(100, 100, 120, 500);
        }
    };

    add(drawingPanel, BorderLayout.CENTER);
    drawingPanel.setBackground(Color.white);
}

您可以像这样定义绘图面板:

drawingPanel = new JPanel(){
   protected void paintComponent(Graphics g){
       //Your draw Code
   }
};

或者您可以创建一个继承自 JPanel 的 class:

public class DrawingPanel extends JPanel{
    public DrawingPanel(){
        //...
    }

    protected void paintComponent(Graphics g){
       //Your draw Code
    }
}

并像这样使用它:

drawingPanel = new DrawingPanel();