Results 1 to 2 of 2
Thread: Why doesn't this work?
- 07-04-2009, 09:41 PM #1
Member
- Join Date
- Jul 2009
- Posts
- 1
- Rep Power
- 0
Why doesn't this work?
I am trying to get my program to draw a black rectangle in a frame. The frame pops up, but there is no rectangle. Could someone de-bug my program and tell me what I need to do to fix it?
I used Eclipse to write the program, and there were no errors found.
Thanks in advance.
import java.awt.*;
import javax.swing.*;
public class Main1 extends JFrame
{
public Main1()
{
super("Paint");
setSize(1000,500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void Paint(Graphics g)
{
g.setColor(Color.black);
g.fillRect(0, 0, 1000, 500);
}
public static void main(String[] args)
{
@SuppressWarnings("unused")
Main1 thisOne=new Main1();
}
}
-
To override it, your method's must match the old method's signature exactly, and the paint method of a JFrame is not static.
Other suggestions:
1) Don't draw on a JFrame. Instead draw in a JPanel or JComponent and add this to the JFrame's contentPane.
2) When drawing in the component above, override paintComponent, not paint as this will allow for Swing's automatic double buffering.
For instance:
Java Code:import java.awt.*; import java.awt.event.*; import javax.swing.*; public class MyPanel extends JPanel { @Override protected void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(Color.red); g.fillRect(100, 100, 100, 100); } public MyPanel() { setPreferredSize(new Dimension(300, 300)); setBackground(Color.black); } private static void createAndShowUI() { JFrame frame = new JFrame("MyPanel"); frame.getContentPane().add(new MyPanel()); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } public static void main(String[] args) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { createAndShowUI(); } }); } }Last edited by Fubarable; 07-04-2009 at 10:38 PM.
Similar Threads
-
Why won't this while loop work?
By trueblue in forum New To JavaReplies: 6Last Post: 05-23-2009, 08:10 PM -
I need help with my work assig Please
By tracy-london in forum New To JavaReplies: 3Last Post: 01-04-2009, 05:50 PM -
Synchronization Doesn't seem to work
By sherinpearl in forum Threads and SynchronizationReplies: 1Last Post: 04-23-2008, 06:30 PM -
Pass by ref. A work around?
By diRisig in forum New To JavaReplies: 0Last Post: 02-05-2008, 07:25 PM -
how would i get this to work...?
By deeadeed in forum New To JavaReplies: 6Last Post: 12-06-2007, 02:58 AM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks