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.
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?
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);
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…