在 JPanel 上绘画

发布于 2024-10-22 08:54:54 字数 718 浏览 7 评论 0原文

我正在编写一个程序,它只是一个简单的形状生成器,我应该有我的主面板 ShapeMakerPanel,以及该面板上的 2 个面板,controlPanel(其中包含用于选择形状和清除形状的按钮等)和绘图区域(实际绘制形状的地方),但无论我做什么,我都无法让油漆显示在绘图区域上。如果我只使用paintComponent并注释掉add(drawingArea),那么绘图功能就可以工作,但是在底层,我如何在drawingArea Jpanel上绘图。另外,当我绘制形状时,我一次只能有一个,因为每次我开始一个新的形状时,面板都会被擦干净`

    super.paintComponent(g);
    g.setColor(penColor);
    if (p1 != null && p2 != null)
    {
        if (shapeChoice.getSelectedItem().equals("Line"))
        {
            Line line = new Line(p1.x, p1.y, p2.x, p2.y);
            line.draw(g);
        }
    }

我知道它的 super.paintComponent(g) 搞乱了我,但没有那个,当我拖动鼠标时,它会绘制数百条线。

如果您想知道 Line 类,我们必须为我们绘制的每个形状创建一个类,draw() 方法仅使用线条的坐标并将它们放入 drawLine() 中。

I'm writing a program that will be just a simple shape maker, I'm supposed to my main panel, ShapeMakerPanel, along with 2 panels on that one, controlPanel(which holds buttons for choosing the shape and clearing it, etc) and drawingArea (where the shapes are actually drawn), but no matter what I do, I can't get the paint to show up on drawingArea. If I just use paintComponent and comment out add(drawingArea) then the drawing stuff works, but on the bottom layer, how can I paint on the drawingArea Jpanel. Also, when I do draw the shapes, I can only have one at a time, because every time I start a new one, the panel is wiped clean`

    super.paintComponent(g);
    g.setColor(penColor);
    if (p1 != null && p2 != null)
    {
        if (shapeChoice.getSelectedItem().equals("Line"))
        {
            Line line = new Line(p1.x, p1.y, p2.x, p2.y);
            line.draw(g);
        }
    }

I know its the super.paintComponent(g) messing me up, but without that, as I drag the mouse, it draws hundreds of lines.

If you were wondering about the Line class, we had to make a class for each shape we drew, the draw() method just uses the coordinates of the line and puts them into drawLine().

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

听,心雨的声音 2024-10-29 08:54:54

不要重写 ShapeMakerPanel 中的paintComponent();在drawingArea 的类中覆盖它(如果drawingArea 是普通的JPanel,则创建JPanel 的新子类)。一般来说,您需要对要在其上绘制的组件进行子类化。

Don't override paintComponent() in ShapeMakerPanel; override it in drawingArea's class (if drawingArea is a plain JPanel, then create a new subclass of JPanel). In general you need to subclass the component on which you're going to paint.

天煞孤星 2024-10-29 08:54:54

此外,当我绘制形状时,一次只能绘制一个,因为每次我开始一个新形状时,面板都会被擦干净`

请参阅自定义绘画方法了解解决此问题的几种方法。

Also, when I do draw the shapes, I can only have one at a time, because every time I start a new one, the panel is wiped clean`

See Custom Painting Approaches for a couple of ways to solve this.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文