简体   繁体   English

Java图形-无法正确绘制

[英]Java graphics - failing to paint properly

Learning to use graphics in java and currently at the moment i'm trying to add some graphics to the screen but failing. 学习在Java中使用图形,目前我正尝试在屏幕上添加一些图形,但是失败了。 I've tried different approaches in a trial and error fashion yet had no luck. 我已经尝试并尝试了不同的方法,但还是没有运气。 The code shown, the structure cannot change in terms of having paint method in a separate class for example. 所示代码的结构不能更改,例如,在单独的类中使用paint方法。 Its a simplified version on a project I'm working on. 它是我正在研究的项目的简化版本。

Other questions on stackoverflow have helped to an extend and similar with the oracle website but I'm still facing issues hence why I am asking here. 关于stackoverflow的其他问题已经扩大了范围,与oracle网站类似,但是我仍然遇到问题,因此为什么在这里提问。

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class test
{
    public static void main(String Args[])
    {
    panelme p1 = new panelme();
    }

}

class panelme
{
    JFrame mainPanel;

    panelme ()
    {
    mainPanel = new JFrame();
    mainPanel.setSize(1000,1000);
    mainPanel.setDefaultCloseOperation(mainPanel.EXIT_ON_CLOSE);
    //paintFrame();
    //paintFrame(g);
    //paintFrame(null);
    mainPanel.setVisible(true);
    }

    public void paintFrame(Graphics g)
    {
    g.drawString("This is a string!", 30, 40);
    //repaint();
    }
}

Start by taking a look at Painting in AWT and Swing and Performing Custom Painting for more details about how painting works in Swing 首先查看AWT和Swing中的 绘画以及执行自定义绘画,以获取有关在Swing中绘画如何工作的更多详细信息

Next, take a look at 2D Graphics trail 接下来,看一下2D Graphics轨迹

Next, create your self a custom class which extends from JPanel and then override it's paintComponent method and place your custom painting within it... 接下来,为您自己创建一个自JPanel扩展的自定义类,然后覆盖它的paintComponent方法并将自定义绘画放入其中。

public class PaintPane extends JPanel {
    @Override
    public Dimension getPreferredSize() {
        return new Dimension(200, 200);
    }

    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawString("This is a string!", 30, 40);
    }
}

Next, add your custom panel to a window... 接下来,将您的自定义面板添加到窗口中...

EventQueue.invokeLater(new Runnable() {
    @Override
    public void run() {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
            ex.printStackTrace();
        }

        JFrame frame = new JFrame("Testing");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(new PaintPane());
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM