我正在尝试创建一个包含工具栏和绘图区域的简单绘图程序。该程序的主窗口是一个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);
}

关于java - Java绘图程序,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29060296/

10-09 03:38