调用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.
我似乎遇到的问题是 paintComponent
方法在我可以设置类变量之前被调用.我将如何更改此代码以在它绘制到屏幕之前设置 JPanel
/JFrame
变量?
The problem I seem to be having is that the paintComponent
method is called before I can set class variables. How would I change this code to be able to set up the JPanel
/JFrame
variables BEFORE it draws to screen?
谢谢
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);
}
}
推荐答案
从 FrameTest 类中删除 test_string.使用 set 方法直接设置 test_string.见示例:
Remove test_string from FrameTest class. Set test_string directly using set method. 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);
}
}
这篇关于调用java方法绘制图形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!