我正在尝试在框架上绘制一些简单的图形。我还希望能够调整我从主要方法中绘制的内容。例如,设置要打印的字符串变量,或者矩形的坐标。
我似乎遇到的问题paintComponent
是在我设置类变量之前调用了该方法。我将如何更改此代码以便能够在它绘制到屏幕之前设置JPanel
/变量?JFrame
谢谢
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);
}
}