Code wont run. I know there is no main class, but this is from a book. Is it wrong??
import java.awt.*;
import javax.swing.*;
import java.awt.color.*;
public class ColorPanel extends JPanel{
public ColorPanel(Color backColor)
{
setBackground(backColor);
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor(Color.blue);
g.drawRect(10, 5, 120, 20);
g.setColor(Color.red);
g.drawString("Hello", 20, 20);
}
}
Re: Code wont run. I know there is no main class, but this is from a book. Is it wro
You need a main method, and you need to add that JPanel to something. I guess the book assumed you knew that part, as this is just a piece of a larger program. Does the book show you how to add JPanels to a JFrame, for example? And how to run a program that displays that JFrame? It's your job to put those pieces together.
Re: Code wont run. I know there is no main class, but this is from a book. Is it wro
u must add something like this:
Code :
public class Main {
public static void main(String[] args) {
final JFrame fr = new JFrame();
JPanel pan = new ColorPanel(Color.black);
fr.add(pan);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
fr.setSize(200, 200);
fr.setVisible(true);
}
});
}
}
Re: Code wont run. I know there is no main class, but this is from a book. Is it wro
Quote:
Originally Posted by
remigio
u must add something like this:
Recommended reading: http://www.javaprogrammingforums.com...n-feeding.html
Re: Code wont run. I know there is no main class, but this is from a book. Is it wro
i understand :)
do not paste code...
btw. im new on this page..:)
Re: Code wont run. I know there is no main class, but this is from a book. Is it wro
Also, I think paintComponent() is a protected method of JPanel.
Yep. I checked to make sure and it is, though it's not a JPanel method directly. It's a JComponent method that JPanel inherited.
Re: Code wont run. I know there is no main class, but this is from a book. Is it wro
Quote:
Originally Posted by
javapenguin
Also, I think paintComponent() is a protected method of JPanel.
Yep. I checked to make sure and it is, though it's not a JPanel method directly. It's a JComponent method that JPanel inherited.
Sorry, but what does that have to do with anything?