Paint new things on JPanel - java

Ok, so I have a JPanel with the paintComponent method overrided.
it's simple, looks like this:
public class Panel1 extends JPanel {
public void paintComponent (Graphics g) {
super.paintComponent (g);
g.fillOval (0, 0, getWidth (), getHeight ());
}
}
Now, I add this JPanel as an attribute to another JPanel class, like:
public class Panel2 extends JPanel {
Panel1 panel;
public Panel2 (Panel1 panel) {
this.panel = panel;
}
protected void paintComponent (Graphics g) {
super.paintComponent (g);
panel.paint (g); //This isn't working.
// panel.paintComponent (g); //Tried this too
g.drawOval (100, 100, getWidth () - 200, getHeight () - 200);
}
}
What I want is Panel2 to be painted exactly the same as Panel1 (without hard-coding it) and maybe add other stuff (like a triangle or sth, I don't know).
Is this even possible? I looked into it but didn't find any way to do it. Thanks in advance for your help!!
The MAIN in case it helps:
public class Main {
public static void main (String[] args) {
JFrame frame = new JFrame ();
frame.setSize (500, 500);
frame.add (new Panel2 (new Panel1 ()));
frame.setVisible (true);
}
}
EDIT: just in case, I don't want to do it with inheritance; that's why I add it as an attribute, but if there is other way just let me now.

You could try to make paintComponent of Panel1 public and then call it in paintComponent of Panel2:
protected void paintComponent (Graphics g) {
panel1.paintComponent(g);
}
You could also create a method inside your Panel1 class that handles the painting for you
public void yourPainting(Graphics g){
//whatever you want to paint
}
and then call this method in the paintComponent methods of both your Panel1 and your Panel2

The reason it does not work the way seen in the question is that Panel1 has a size of 0x0. To get a sensible size, return a size from getPreferredSize(), then set the panel size to the preferred size.
import java.awt.*;
import javax.swing.*;
public class PaintUnrealized {
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception useDefault) {
}
JFrame f = new JFrame("Paint Unrealized Component");
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
f.setContentPane(new Panel2(new Panel1()));
f.pack();
f.setMinimumSize(f.getSize());
f.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
}
}
class Panel1 extends JPanel {
public Panel1() {
setBackground(Color.RED);
setSize(getPreferredSize());
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.fillOval(0, 0, getWidth(), getHeight());
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
}
class Panel2 extends JPanel {
Panel1 panel;
public Panel2(Panel1 panel) {
this.panel = panel;
setBackground(Color.YELLOW);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
panel.paintComponent(g); // This works
int pad = 25;
g.drawOval(pad, pad, getWidth()-(2*pad), getHeight()-(2*pad));
}
#Override
public Dimension getPreferredSize() {
return new Dimension(500, 300);
}
}

public class Panel2 extends JPanel {
private Panel1 panel1;
public Panel2 (Panel1 panel) {
this.panel1 = panel;
}
protected void paintComponent (Graphics g) {
panel1.paint(g);
}
}
I believe that should work

Related

Why is JPanel size is wrong?

There is constructor of class extending JFrame:
import java.awt.*;
import javax.swing.*;
public class ChessFrame extends JFrame {
public ChessFrame () {
setSize(520, 520);
setResizable(false);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(1, 1));
// Add components
getContentPane().add(new Board());
pack();
setVisible(true);
}
}
And class extending JPanel:
import javax.swing.*;
public class Board extends JPanel {
public Board() {
setSize(new Dimension(520, 520));
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.fillRect(0, 0, 520, 520);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(520, 520);
}
}
As a result rectangle smaller then 520x520.
Size of black rectangle is about 496x510. There is more:
getWidth() and getHegiht() written inside the Board class, returns 0 and 0 (so size of this JPanel into JFrame is 0x0)
If I remove pack(), size of frame becomes 496x510 (black rectangle size)
It's actually copypaste of official java tutorial: https://docs.oracle.com/javase/tutorial/uiswing/painting/step2.html.
Do I do something wrong or it's something related with java? If it's second, why does this happen?
Any help would be appreciated.
This example only tries to establish the panel size once the frame (and panel) are visible on-screen. It returns the exact size (300 pixels) set in the code.
import java.awt.*;
import javax.swing.*;
public class ChessBoard extends JPanel {
int size = 300;
JLabel sizeLabel = new JLabel();
ChessBoard() {
setBackground(Color.CYAN);
setLayout(new GridBagLayout());
add(sizeLabel);
}
public void showSize() {
sizeLabel.setText(String.format("%1sx%1s", getWidth(), getHeight()));
}
#Override
public Dimension getPreferredSize() {
return new Dimension(size,size);
}
public static void main(String[] args) {
Runnable r = () -> {
ChessBoard cb = new ChessBoard();
JFrame f = new JFrame(cb.getClass().getSimpleName());
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
f.setContentPane(cb);
f.pack();
f.setMinimumSize(f.getSize());
f.setVisible(true);
// delay showing size until app. is on-screen
Runnable r1 = cb::showSize;
SwingUtilities.invokeLater(r1);
};
SwingUtilities.invokeLater(r);
}
}

Java Swing, scrollable HBox

I'm writing a program where I'm trying to implement a scrollable HBox. Sadly the JSCrollPane doesn't seem to function at all and when the window gets too small the images just start to clip each other.
The pane with the images has the following code:
public class Caller extends JPanel {
public Caller() {
initPanel();
}
private void initPanel() {
this.setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
}
public void addBall(Ball ball) {
this.add(ball);
}
}
And the main frame:
public class GUI extends JFrame {
public GUI() throws HeadlessException {
super();
initMainFrame();
initCaller();
}
private void initCaller() {
Caller caller = new Caller();
JScrollPane scrollPane = new JScrollPane(caller, JScrollPane.VERTICAL_SCROLLBAR_NEVER, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
caller.addBall(new Ball(5));
caller.addBall(new Ball(16));
caller.addBall(new Ball(34));
caller.addBall(new Ball(34));
caller.addBall(new Ball(34));
this.add(scrollPane);
}
private void initMainFrame() {
this.setTitle("Main");
this.setSize(new Dimension(500,200));
}
}
Ball Draw Code:
#Override
public void paint(Graphics g) {
super.paint(g);
g.drawImage(ballImage, 0,0, this);
g.setFont(new Font("Arial Black", Font.BOLD, 20));
g.setColor(Color.WHITE);
g.drawString(designation, 20,ballImage.getHeight()/2);
}
Am I implementing the scroller in the wrong way?
It looks like your Ball JComponent is missing informations about its preferred/min/max sizes, so the Caller panel with the BoxLayout doesn't know what they are and when you reduce the width, your components will have their size reduced rather than the scrollpane reflecting the need for scrolling.
You will have to override the relevant methods of your Ball class e.g :
#Override
public Dimension getPreferredSize() {
return new Dimension(ballImage.width, ballImage.height);
}
#Override
public Dimension getMaximumSize() {
return new Dimension(ballImage.width, ballImage.height);
}
#Override
public Dimension getMinimumSize() {
return new Dimension(ballImage.width, ballImage.height);
}

Java Drawing to a JPanel (debugging)

I'm trying to draw a basic object to a JPanel
although it doesn't seem to be working.
I'm certain I am doing something wrong with where the paint method
is being called
import javax.swing.*;
import java.awt.*;
import java.awt.image.*;
public class testGui {
static colors gc_colors;
static gui gc_gui;
public static void main(String[] args) {
gc_colors = new colors();
gc_gui = new gui();
gc_gui.cv_frame.setVisible(true);
}
public static class colors {
Color cv_ltGrey;
Color cv_mdGrey;
Color cv_dkGrey;
public colors() {
cv_ltGrey = Color.decode("#DDDDDD");
cv_mdGrey = Color.decode("#CCCCCC");
cv_dkGrey = Color.decode("#111111");
}
}
public static class gui {
JFrame cv_frame;
JPanel cv_panel;
JPanel cv_content;
public gui() {
cv_frame = new JFrame();
cv_frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
cv_frame.setTitle("Test GUI");
cv_frame.setSize(600, 400);
cv_frame.setLayout(new FlowLayout());
cv_panel = new JPanel();
cv_panel.setBackground(gc_colors.cv_ltGrey);
cv_panel.setPreferredSize(new Dimension(500, 300));
cv_frame.add(cv_panel);
cv_content = new content();
cv_panel.add(cv_content);
}
}
public static class content extends JPanel {
public void paint(Graphics graphic) {
super.paint(graphic);
draw(graphic);
}
public void update() {
repaint();
}
public void draw(Graphics graphic) {
Graphics2D graphic2D = (Graphics2D) graphic;
graphic2D.setPaint(gc_colors.cv_ltGrey);
graphic2D.fillRect(10, 10, 100, 100);
}
}
}
I have a class for my gui which I am adding a JPanel to (a light grey one).
Which I am then trying to add my drawing to using a JPanel extended class
called content.
When I run it though it seems to create the grey JPanel which I want but
the drawing is just a tiny white square and I'm not sure why.
So, you content panel has a default preferred size of 0x0, FlowLayout honours the preferredSize of its components (with a little margin), hence the reason why you have a nice little small white rectangle.
What you need to do is override the getPreferredSize method of the content panel and return a suitable size, for example
public static class content extends JPanel {
#Override
public Dimension getPreferredSize() {
return new Dimension(120, 120);
}
public void paint(Graphics graphic) {
super.paint(graphic);
draw(graphic);
}
public void update() {
repaint();
}
public void draw(Graphics graphic) {
Graphics2D graphic2D = (Graphics2D) graphic;
graphic2D.setPaint(gc_colors.cv_ltGrey);
graphic2D.fillRect(10, 10, 100, 100);
}
}
I've decided to just leave out the second JPanel altogether.
It was too much of a hassle to put the JPanel inside of another JPanel
so instead I am only going to use a single JPanel
public static class gui {
JFrame cv_frame;
JPanel cv_panel;
JPanel cv_content;
public gui() {
cv_frame = new JFrame();
cv_frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
cv_frame.setTitle("Test GUI");
cv_frame.setSize(600, 400);
cv_frame.setLayout(new FlowLayout());
cv_content = new content();
cv_content.setBackground(gc_colors.cv_ltGrey);
cv_content.setPreferredSize(new Dimension(500, 300));
cv_frame.add(cv_content);
}
}

Java pass JPanel down to child class

i am exercising some OOP with java.
I just want to write a game with some graphic objects but i want to structure it with some classes.
The overall layout should look like this:
MainClass -> new MainPanel(extends JPanel)->new StartWindow(extends abstract GameWindow which contains the gameloop)
This way i should be able to create StartWindow, Level1Window, Level2Window and so on.
My StartWindow should now Draw the Layout for the first level.
The StartWindow will create other objects(Player, Enemy and so on) which will later be responsible for drawing themself.
So i want to create something like "every object is responsible to draw itself"
I hope i could make clear how this should work.
Problem is, i cant figure out how to delegate down this task.
My Code looks like this at the moment:
public class MainClass extends JFrame implements ActionListener {
//..... other stuff
public MainClass () {
MainPanel mainPanel = new MainPanel();
}
//.... other stuff
}
class MainPanel extends JPanel {
private GameWindow currentWindow;
public MainPanel () {
currentWindow = new StartWindow(this);
}
public void paintComponent(Graphics g) {
g.drawRect (10, 10, 200, 200); // <-- can see on the window
}
}
abstract class GameWindow {
// contains game loop and update functions and so on
}
public class StartWindow extends GameWindow {
GamePanel _parentWindow;
public StartWindow(GamePanel parentWindow) {
super();
_parentWindow = parentWindow;
}
public void paintComponent(Graphics g) {
//Does not work
g.drawRect (20, 20, 100, 100);
}
}
the "_parentWindow" contains the MainPanel, so i should have all the information that is needed to draw on its Panel, i just cant figure out how to do it.
Edit:
Minimum example thats working:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MainClass extends JFrame implements ActionListener {
public static void main(String[] args)
{
System.out.println("Program Window1");
MainClass glt = new MainClass();
glt.setVisible(true);
}
//..... other stuff
public MainClass () {
super("Fixed Timestep Game Loop Test");
Container cp = getContentPane();
cp.setLayout(new BorderLayout());
JPanel p = new JPanel();
p.setLayout(new GridLayout(1,2));
System.out.println("Program Window2");
MainPanel gamePanel= new MainPanel();
cp.add(gamePanel, BorderLayout.CENTER);
cp.add(p, BorderLayout.SOUTH);
setSize(500, 500);
}
//.... other stuff
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
}
class MainPanel extends JPanel {
private GameWindow currentWindow;
public MainPanel () {
currentWindow = new StartWindow(this);
}
public void paintComponent(Graphics g) {
g.drawRect (0, 0, 200, 200); // <-- can see on the window
}
}
abstract class GameWindow {
// contains game loop and update functions and so on
}
class StartWindow extends GameWindow {
MainPanel _parentWindow;
public StartWindow(MainPanel parentWindow) {
super();
_parentWindow = parentWindow;
}
public void paintComponent(Graphics g) {
//Does not work
g.drawRect (20, 20, 100, 100);
}
}
I would draw the sprites in your main drawing JComponent, e.g.,
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MainClass extends JFrame implements ActionListener {
public static void main(String[] args) {
System.out.println("Program Window1");
MainClass glt = new MainClass();
glt.setVisible(true);
}
// ..... other stuff
public MainClass() {
super("Fixed Timestep Game Loop Test");
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
Container cp = getContentPane();
cp.setLayout(new BorderLayout());
JPanel p = new JPanel();
p.setLayout(new GridLayout(1, 2));
System.out.println("Program Window2");
MainPanel gamePanel = new MainPanel();
cp.add(gamePanel, BorderLayout.CENTER);
cp.add(p, BorderLayout.SOUTH);
setSize(500, 500);
}
// .... other stuff
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
}
class MainPanel extends JPanel {
private GameWindow currentWindow;
public MainPanel() {
currentWindow = new StartWindow(this);
}
// public void paintComponent(Graphics g) {
// g.drawRect(0, 0, 200, 200); // <-- can see on the window
// }
// this should be protected, not public and should call super method
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawRect(0, 0, 200, 200); // <-- can see on the window
currentWindow.draw(g);
}
}
interface Drawable {
void draw(Graphics g);
}
abstract class GameWindow implements Drawable {
// contains game loop and update functions and so on
}
class StartWindow extends GameWindow {
MainPanel _parentWindow;
public StartWindow(MainPanel parentWindow) {
super();
_parentWindow = parentWindow;
}
#Override
public void draw(Graphics g) {
g.setColor(Color.red);
g.drawRect(20, 20, 100, 100);
}
}
but again, I reiterate that the game loop should not be inherited but rather its reference should be passed. Extension via composition rather than inheritance.
Or perhaps even better, have your model classes implement an interface, something like:
public interface Tickable {
void tick(int deltaTime);
}
Then a collection such as a List<Tickable> is held by the main model, and every time the game loop ticks, it iterates through the list calling tick(...) on each item in the List.
Try something like this inside the paintComponent method of your MainPanel class.
public void paintComponent(Graphics g) {
g.drawRect (10, 10, 200, 200); // <-- can see on the window
Graphics2D g2d = (Graphics2D) g.create();
((StartWindow) currentWindow).paintComponent(g2d);
g2d.dispose();
}

How do I draw on a JFrame, or any JComponent?

I am trying to draw something using paint() on my JFrame. I can't get it to show though. Why?
claass DrawOn extends JFrame{
public static void main(String args[]){
new DrawOn();
}
public DrawOn(){
setVisible(true);
pack();
}
paint(Graphics g){
g.drawOval(10,10,100,100);
}
}
You should draw in a JPanel:
JPanel panel = new JPanel()
{
#Override
protected void paintComponent(Graphics g)
{
// TODO Auto-generated method stub
super.paintComponent(g);
g.drawOval(10, 10, 100, 100);
}
};
Don't forget to add the JPanel to the JFrame:
add(panel);
Code:
public DrawOn()
{
JPanel panel = new JPanel()
{
#Override
protected void paintComponent(Graphics g)
{
// TODO Auto-generated method stub
super.paintComponent(g);
g.drawOval(10, 10, 100, 100);
}
};
add(panel);
setPreferredSize(new Dimension(200, 200));
setVisible(true);
pack();
}
Note: You could make a class that extends JPanel instead of using an anonymous class so your code is clearer.

Categories