自定义绘制 AWT 组件

发布于 2024-10-18 21:12:34 字数 176 浏览 1 评论 0原文

我试图使用 java.awt.Graphics.drawLine() 在其 java.awt.Component.getGraphics() 上绘制一系列线条,从而在 AWT 组件上产生渐变效果 方法,但这永远不会保持绘制状态。有谁知道如何将这些图形提交给组件,以便它们在调整大小和调用重绘的其他事件中保持不变?

I am trying to make a gradient effect on an AWT component using a series of lines drawn on its java.awt.Component.getGraphics() using the java.awt.Graphics.drawLine() method, but this never stays painted. Does anyone know how to commit these graphics to the component so they stay through resizing and other events that invoke repainting?

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

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

发布评论

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

评论(2

时光病人 2024-10-25 21:12:34

您是否仅限于 AWT 组件?如果没有,我建议您使用 Swing 组件(以 "J" 开头的组件。对于自定义绘制,您可以重写 paintComponent 方法,例如:

import java.awt.Graphics;

import javax.swing.JPanel;

public class CustomPaintingComponent extends JPanel
{
    @Override
    protected void paintComponent(Graphics g)
    {
        super.paintComponent(g);    // This will clear everything...

        // ... now you can apply your custom painting, for example:
        g.drawLine(10, 10, getWidth() - 10, getHeight() - 10);  // A line from upper left to lower right corner
    }
}

Are you limited to AWT components? If not I suggest you go with Swing components (the ones starting with "J". For custom painting you override the paintComponent method, for example:

import java.awt.Graphics;

import javax.swing.JPanel;

public class CustomPaintingComponent extends JPanel
{
    @Override
    protected void paintComponent(Graphics g)
    {
        super.paintComponent(g);    // This will clear everything...

        // ... now you can apply your custom painting, for example:
        g.drawLine(10, 10, getWidth() - 10, getHeight() - 10);  // A line from upper left to lower right corner
    }
}
空城仅有旧梦在 2024-10-25 21:12:34

您需要重写组件的paint方法。否则,如果您仅使用图形对象并向其写入一次线条,则下次调用组件绘制方法时,它将重新绘制所有更改。

you need to override the paint method of the component. Otherwise, if you just use a graphics object and write lines to it a single time, the next time the component paint method is called, it will redraw over all your changes.

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