Re: Canvas Wanted (simple question)
On 12/11/2011 2:02 PM, Pawe?? Lampe wrote:
Hi !
Recently, I have not too much time to google smth or read Thinking in
Java. I hope so, I will get answer for my question in O(1) here.
First, short story:
I designed some UML for my new project (Traffic Simulation). I started to
implement it, but I have reached the point that I need to draw some. In
"main" I added new JFrame, made it visible and then I getGraphics and
started to draw. However nothing appeard.
I think my delphi-like-approach is wrong so the question is : "how should
I do it well ?" and maybe "Where should I place main_drawing_loop?".
I suspect I need more classes to make whole GUI work fine, but got no
idea how to do it.
Pls help me or paste some links.
Thanks
Simplest way to do this is to add a JPanel to the JFrame and do your
drawing on that JPanel.
import java.awt.*;
import javax.swing.*;
public class test extends JPanel {
public test() {
// so the layout manager knows how big to make component
setPreferredSize(new Dimension(400,300));
}
// do all of your drawing in the overridden method paintComponent()
public void paintComponent(Graphics g) {
int w = getWidth();
int h = getHeight();
// draw background
g.setColor(Color.BLACK);
g.fillRect(0,0,w,h);
// draw 40x30 rect in middle
g.setColor(Color.WHITE);
g.drawRect(w/2-40,h/2-30,80,60);
}
public static void main(String[] args) {
// create GUI on EDT (event dispatch thread)
EventQueue.invokeLater(new Runnable() {
public void run() {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.add(new test(),BorderLayout.CENTER);
f.pack();
f.setVisible(true);
}
});
}
}
--
Knute Johnson