简体   繁体   English

调用Java方法绘制图形

[英]calling a java method to draw graphics

I'm trying out to draw some simple graphics to a frame. 我正在尝试将一些简单的图形绘制到框架上。 I would also like to be able to adjust what I'm drawing from my main method. 我还希望能够调整主要方法中的绘制内容。 For example, setting a String variable to be printed, or the coordinates of a rectangle. 例如,设置要打印的String变量或矩形的坐标。

The problem I seem to be having is that the paintComponent method is called before I can set class variables. 我似乎遇到的问题是,在设置类变量之前会先调用paintComponent方法。 How would I change this code to be able to set up the JPanel / JFrame variables BEFORE it draws to screen? 如何在绘制到屏幕之前更改此代码,以便能够设置JPanel / JFrame变量?

Thanks 谢谢

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

public class Test {

    public static void main(String[] args) {
        FrameTest test_frame = new FrameTest();
        test_frame.test_string = "I WANT TO DRAW THIS STRING";
    }
}

class FrameTest extends JFrame{
    private static final long serialVersionUID = 1L;
    String test_string;

    public FrameTest(){
        this.test_string = "TEMP STRING FROM FRAME";
        JFrame gui = new JFrame();
        gui.setTitle("Test Title");
        gui.setSize(400,400);
        gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        Painting painting = new Painting();

        Container pane = gui.getContentPane();
        pane.setLayout(new GridLayout(1,1));

        pane.add(painting);
        gui.setVisible(true);

    }
}

class Painting extends JPanel{
    private static final long serialVersionUID = 1L;
    String test_string;

    public Painting(){
        setBackground(Color.WHITE);
        this.test_string = "TEMP STRING FROM PANEL";
    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);

        g.setColor(Color.RED);
        g.drawString(test_string, 20, 20);
    }
}

Here you are assigning aa string to test_string in FrameTest which is not updating the variable of the same name in Painting : 在这里,您要为test_string中的FrameTest分配一个字符串,这不会在Painting更新相同名称的变量:

test_frame.test_string = "I WANT TO DRAW THIS STRING";

Why not add an update method to FrameTest as you have a reference to this: 为什么不向FrameTest添加更新方法,因为您对此有一个参考:

public void setTestString(String test_string) {
    painting.setTestString(test_string);
}

and call: 并致电:

FrameTest test_frame = new FrameTest();
test_frame.setTestString("I WANT TO DRAW THIS STRING");

Note: Java uses CamelCase, eg testString 注意:Java使用CamelCase,例如testString

Remove test_string from FrameTest class. 从FrameTest类中删除test_string。 Set test_string directly using set method. 使用set方法直接设置test_string。 See example: 参见示例:

import java.awt.Color;
import java.awt.Container;
import java.awt.Graphics;
import java.awt.GridLayout;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class Test {

    public static void main(String[] args) {
        FrameTest1 test_frame = new FrameTest1();
        test_frame.setContentString("I WANT TO DRAW THIS STRING");
    }

}

class FrameTest1 extends JFrame {
    private static final long serialVersionUID = 1L;

    Painting painting = new Painting();

    public FrameTest1() {
        JFrame gui = new JFrame();
        gui.setTitle("Test Title");
        gui.setSize(400, 400);
        gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        Container pane = gui.getContentPane();
        pane.setLayout(new GridLayout(1, 1));

        pane.add(painting);
        gui.setVisible(true);

    }

    public void setContentString(String value) {
        painting.test_string = value;
    }
}

class Painting extends JPanel {
    private static final long serialVersionUID = 1L;
    String test_string;

    public Painting() {
        setBackground(Color.WHITE);
        this.test_string = "TEMP STRING FROM PANEL";
    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);

        g.setColor(Color.RED);
        g.drawString(test_string, 20, 20);
    }
}

You can pass the text you want to draw to the Painting class via constructor and pass the painting to FrameSet the same way as well. 您可以通过构造函数将要绘制的文本传递给Painting类,也可以将绘画以相同的方式传递给FrameSet。

To learn more read about java constructors and parameters read this: http://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html 要了解有关Java构造函数和参数的更多信息,请阅读以下内容: http : //docs.oracle.com/javase/tutorial/java/javaOO/constructors.html

I've modified your code to do what you needed, I haven't tested it though. 我已经修改了您的代码以执行所需的操作,但是我尚未对其进行测试。

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

public class Test {

    public static void main(String[] args) {
        Painting painting = new Painting("I WANT TO DRAW THIS STRING");
        FrameTest test_frame = new FrameTest(painting);
    }
}

class FrameTest extends JFrame{
    private static final long serialVersionUID = 1L;
    String test_string;

    public FrameTest(painting){
        super();
        this.test_string = "TEMP STRING FROM FRAME";
        JFrame gui = new JFrame();
        gui.setTitle("Test Title");
        gui.setSize(400,400);
        gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        Container pane = gui.getContentPane();
        pane.setLayout(new GridLayout(1,1));

        pane.add(painting);
        gui.setVisible(true);

    }
}

class Painting extends JPanel{
    private static final long serialVersionUID = 1L;
    String test_string;

    public Painting(String test_string){
        super();
        this.test_string = test_string;
        setBackground(Color.WHITE);
    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);

        g.setColor(Color.RED);
        g.drawString(test_string, 20, 20);
    }
}

For example, setting a String variable to be printed, or the coordinates of a rectangle. 例如,设置要打印的String变量或矩形的坐标。

Create a BufferedImage in main(String[]) , have a method to Painting.setImage(Image) , display the image in a JLabel . main(String[])创建一个BufferedImage ,具有一个Painting.setImage(Image) ,在JLabel显示图像。

This is more versatile in that it could accept an image of a string, or an image of an ellipse, or an image of a string over part of an ellipse over a gradient BG.. 这更具通用性,因为它可以接受字符串的图像或椭圆的图像,或者接受椭圆的一部分在梯度BG上的字符串的图像。

Displaying many images 显示许多图像

许多(OK 3)图像

import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.util.Random;

public class ImageViewer {

    JPanel gui;
    /** Displays the image. */
    JLabel imageCanvas;

    /** Set the image as icon of the image canvas (display it). */
    public void setImage(Image image) {
        imageCanvas.setIcon(new ImageIcon(image));
    }

    public void initComponents() {
        if (gui==null) { 
            gui = new JPanel(new BorderLayout());
            gui.setBorder(new EmptyBorder(5,5,5,5));
            imageCanvas = new JLabel();

            JPanel imageCenter = new JPanel(new GridBagLayout());
            imageCenter.add(imageCanvas);
            JScrollPane imageScroll = new JScrollPane(imageCenter);
            imageScroll.setPreferredSize(new Dimension(300,100));
            gui.add(imageScroll, BorderLayout.CENTER);
        }
    }

    public Container getGui() {
        initComponents();
        return gui;
    }

    public static Image getRandomImage(Random random) {
        int w = 100 + random.nextInt(400);
        int h = 50 + random.nextInt(200);
        BufferedImage bi = new BufferedImage(
                w,h,BufferedImage.TYPE_INT_RGB);

        return bi;
    }

    public static void main(String[] args) throws Exception {
        Runnable r = new Runnable() {
            @Override
            public void run() {
                JFrame f = new JFrame("Image Viewer");
                // TODO Fix kludge to kill the Timer
                f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

                final ImageViewer viewer = new ImageViewer();
                f.setContentPane(viewer.getGui());

                f.pack();
                f.setLocationByPlatform(true);
                f.setVisible(true);

                ActionListener animate = new ActionListener() {

                    Random random = new Random();

                    @Override
                    public void actionPerformed(ActionEvent arg0) {
                        viewer.setImage(getRandomImage(random));
                    }
                };
                Timer timer = new Timer(1500,animate);
                timer.start();
            }
        };
        SwingUtilities.invokeLater(r);
    }
}

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

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