I'm creating an application in which I have a class with a
main frame (JFrame), and a class which is a JPanel subclass called OvalPanelClass. I say
main frame because the user has the option to open up another JFrame (window). This
OvalPanelClass is dynamic and displays its images using a BufferStrategy. It is both
launched into a separate JFrame on some occasions and appears at the bottom right
section of the main frame at some points too, so I didn't feel it made sense to make
this class an inner class of the class containing the main
frame.
The problem is that as this JPanel is not
a part of a class with a JFrame it cannot make the call to get the BufferStrategy and so
on. So to get over this I tried passing a reference to the main frame to the
OvalPanelClass constructor but I'm not getting results. My question is what is flawed
with my
reasoning?
FrameClass
import
java.awt.BorderLayout;
import
java.awt.Dimension;
import
javax.swing.JFrame;
import
javax.swing.JPanel;
public class FrameClass extends
JFrame {
public static void main(String[] args) {
FrameClass test = new FrameClass();
test.setup();
}
void setup() {
setPreferredSize(new
Dimension(800, 800));
JPanel background = new JPanel(new
BorderLayout());
getContentPane().add(background);
setVisible(true);
OvalPanelCanvas shape = new
OvalPanelCanvas(this);
//shape.setup(this);
background.add(BorderLayout.CENTER, shape);
pack();
shape.repaint();
}
}
OvalPanelCanvas
import
java.awt.Color;
import java.awt.Graphics;
import
java.awt.image.BufferStrategy;
import
javax.swing.JFrame;
import javax.swing.JPanel;
public
class OvalPanelCanvas extends JPanel {
JFrame frame;
BufferStrategy bs;
public OvalPanelCanvas(JFrame frame) {
this.frame = frame;
setOpaque(false);
}
public void paintComponent(Graphics g) {
frame.createBufferStrategy(2);
bs = frame.getBufferStrategy();
Graphics bufferG = bs.getDrawGraphics();
for (int i = 0; i < 5; i++)
{
int width = 50;
int height = 50;
bufferG.setColor(new
Color(i*5,i*6,i*50));
bufferG.fillOval(0, 0, width*i,
height*i);
}
bufferG.dispose();
bs.show();
}
}
Thanks
for your time! I'm being vague about what the project is and have stripped away what I
felt were irrelevant details but if you need some more context let me
know.
No comments:
Post a Comment