Not showing graphics in JPanel which is added to another JPanel - java

When adding a JPanel that has graphics to a JFrame, it's working fine. But when I try to add a JPanel in which I have added another JPanel with graphics, its not showing in the JFrame. Please see code below
package sample;
import java.awt.Graphics;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Main extends JFrame{
public static void main(String[] args) {
new Main();
}
public Main(){
setTitle("Sample");
setVisible(true);
setSize(500,500);
setDefaultCloseOperation(EXIT_ON_CLOSE);
add(new SamplePanel2());
}
}
class SamplePanel2 extends JPanel{
public SamplePanel2(){
add(new JButton("Hi"));
add(new SamplePanel());
}
}
class SamplePanel extends JPanel {
public SamplePanel(){
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawString("HHHHHHHHHHHH", 100, 100);
}
}

Please do watch the constructor of the Main Class, make this your habbit to follow the sequence as shown in this example. First add components to the JFrame then only make calls like pack(), setSize() or setVisible(...), not before that.
Always make it your habbit, that whenever you override paintcomponent() method, override getPreferredSize() method as well.
And always put calls like pack()/setVisible(...) inside the EDT - Event Dispatch Thread. Please read Concurrency in Swing, for more detail on the topic.
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Main extends JFrame{
public static void main(String[] args) {
new Main();
}
public Main(){
setTitle("Sample");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setContentPane(new SamplePanel2());
pack();
setVisible(true);
}
}
class SamplePanel2 extends JPanel{
public SamplePanel2(){
add(new JButton("Hi"));
add(new SamplePanel());
}
}
class SamplePanel extends JPanel {
public SamplePanel(){
}
#Override
public Dimension getPreferredSize()
{
return (new Dimension(300, 300));
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawString("HHHHHHHHHHHH", 100, 100);
}
}

Related

Why is JPanel still painted?

I am actually trying to create a JPanel, containing a bunch of ui elements for the user to manipulate the application. This panel is placed on top of Java3D scene. Therefore, I wanted the background of this JPanel to be transparent. Neither panel.setBackground(new Color(0,0,0,0)) nor popupPanel.setOpaque(false) nor both calls made the panel background transparent. So I decided to sub-class JPanel and play with paintComponent. No effect. Then I tried paint. Nothing. Then I got confused. So I overwrote literally every method I know of, related to painting a JPanel and left each method body blanc (see below). When I run the application, I still get the panel. How can that be? I placed some System.out.println to be sure that the class is the right one, and is called. It is the right one. Despite all this missing code, the only difference to a normal JPanel is that the button is only painted if the mouse enters the button bounds. What am I missing?
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Rectangle;
import javax.swing.JPanel;
public class TransparentPanel extends JPanel {
protected Color bg = new Color(0,0,0,0);
public TransparentPanel() {
super();
setOpaque(false);
}
#Override
protected void paintComponent(Graphics g) { }
#Override
public void paint(Graphics g) {
System.out.println(System.getProperty("java.vendor"));
System.out.println(System.getProperty("java.version"));
for(Component c: getComponents()) {
System.out.println(c.toString());
}
}
#Override
public void repaint(Rectangle r) {}
#Override
public void repaint(long tm,int x,int y,int width, int height) {}
#Override
protected void paintChildren(Graphics g) {}
#Override
protected void paintBorder(Graphics g) {}
#Override
public void paintImmediately(int x,int y,int width, int height) {}
#Override
public void paintImmediately(Rectangle r) {}
}
and
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.OverlayLayout;
public class OverlayoutTest extends JFrame {
public OverlayoutTest() {
super("Test");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(new Dimension(400, 300));
add(createPanel());
setLocationRelativeTo(null);
setVisible(true);
}
private JPanel createPanel() {
JPanel mainPanel = new JPanel(){
#Override
public boolean isOptimizedDrawingEnabled() {
return false;
}
};
mainPanel.setLayout(new OverlayLayout(mainPanel));
JComponent popupPanel = createPopupPanel();
popupPanel.setAlignmentX(1.0f);
popupPanel.setAlignmentY(0.0f);
mainPanel.add(popupPanel);
SpatialView view = new SpatialView(null); // A class extending JPanel containing a Java3D Canvas3D in a BorderLayout
mainPanel.add(view);
view.addScaledPlanetModel();
return mainPanel;
}
private JComponent createPopupPanel() {
TransparentPanel popupPanel = new TransparentPanel();
// popupPanel.setBackground(new Color(0,0,0,0));
// popupPanel.setOpaque(false);
popupPanel.setMaximumSize(new Dimension(250, 300));
JButton button = new JButton("HI there!"); // the button does nothing but is nice to spot
button.setForeground(Color.WHITE);
popupPanel.add(button );
return popupPanel;
}
public static void main(String[] args) {
new OverlayoutTest();
}
}
I am using OpenJDK version "11" 2018-09-25, build 11+28 and Java3D 1.7.0

MouseListener overriding Paint Component

I'm trying to make a a program in MVC architecture which simply opens a frame (JFrame) with some certain design and when clicked somewhere with a mouse simply prints to the console : "sth" notifying that the action went through successfully but it seems that the Input.java class when added to the frame before the Ouput.java class is overridden by the latter and disables MouseListener, or the former overrides the latter where you're able to activate MouseListener executing a certain program when clicked on the frame but doesn't show the design made in Output
Here are the mentioned class files:
input.java:
package MouseListenerTest;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JPanel;
public class Input extends JPanel implements MouseListener
{
Input()
{
addMouseListener(this);
}
public void mouseClicked(MouseEvent e) {
System.out.println("Ej Adiiiii");
}
public void mousePressed(MouseEvent e)
{
}
public void mouseReleased(MouseEvent e)
{
}
public void mouseEntered(MouseEvent e)
{
}
public void mouseExited(MouseEvent e)
{
}
}
Output.java
package MouseListenerTest;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;
public class Output extends JPanel
{
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor(Color.red);
g.fillRect(0, 0, 500, 500);
}
}
Frame.java
package MouseListenerTest;
import javax.swing.*;
public class Frame
{
Frame()
{
JFrame frame = new JFrame();
frame.getContentPane().add(new Output());
frame.getContentPane().add(new Input());
frame.setSize(500,500);
frame.setVisible(true);
frame.setTitle("MouseListener test");
}
}
Controller.java
package MouseListenerTest;
public class Controller
{
public static void main(String[] args)
{
new Frame();
}
}
How do I fix this problem?
the problem in your code is because the way you added the elements to frame and I changed to a GridLayout and added them to frame to see both:
frame.setLayout(new GridLayout(2, 1));
frame.getContentPane().add(new Output());
frame.getContentPane().add(new Input());
more info about Layout Manager
You will have to learn at least the basics about laying out components.

Java swing: i called once drawString and it printed my string multiple times

I'm new in java swing programming. What i'm trying to do is paint a string to a specific location in a JPanel. The JPanel is very large and so i add it to a JScrollpane, but when i draw the string it is printed not just in the specified location but also in others.
The first image represents the bottom of the panel where i decided to draw the string and this is correct. But if you observe whole the panel you can find the string too in others locations (see second image).
Can someone tell me why this happen? How can i prevent it?
import java.util.*;
import java.io.*;
import javax.swing.*;
import java.awt.*;
class Example extends JFrame
{
private MyPanel gg=new MyPanel();
Example(){
add(new JScrollPane(gg));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setExtendedState(MAXIMIZED_BOTH);
}
public static void main(String argv[]){
EventQueue.invokeLater(new Runnable() {
public void run() {
Example test=new Example();
test.setVisible(true);
}
});
return;
}
}
class MyPanel extends JPanel
{
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2d=(Graphics2D)g;
g2d.drawString("HI I LOVE ELON MUSK", 90, 300035);
return;
}
public Dimension getPreferredSize() {
return new Dimension(500, 300060);
}
}
Your code ran fine on my Windows 10 system. I have a Java 13 JDK that I compile at Java 8.
I made a few changes to your main class. Maybe these changes stabilized the display. Run my code on your system and see.
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
public class LongJPanelExample {
public LongJPanelExample() {
JFrame frame = new JFrame("Long JPanel Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
MyPanel gg = new MyPanel();
frame.add(new JScrollPane(gg));
frame.pack();
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setVisible(true);
}
public static void main(String argv[]) {
EventQueue.invokeLater(new Runnable() {
public void run() {
new LongJPanelExample();
}
});
}
}
class MyPanel extends JPanel {
private static final long serialVersionUID = 1L;
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.drawString("HI I LOVE ELON MUSK", 90, 300035);
return;
}
public Dimension getPreferredSize() {
return new Dimension(500, 300060);
}
}

Why is Java Graphics not painting?

I'm a bit new to programming right now and am trying to make Pong in java. However I'm not able to make any graphics show up.
Main Class
public class Pong1 {
public static Frame frame = new Frame();
public static Panel panel = new Panel();
public static void main(String[] args) {
initUI();
}
public static void initUI(){
frame.setLayout(new BorderLayout());
frame.add(BorderLayout.CENTER, panel);
frame.pack();
frame.setVisible(true);
}
public static int getPanelWidth(){
return panel.getWidth();
}
public static int getPanelHeight(){
return panel.getHeight();
}
}
JFrame Class
package pong1;
import java.awt.Dimension;
import javax.swing.JFrame;
public class Frame extends JFrame{
Frame(){
setTitle("Pong");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setResizable(true);
setMinimumSize(new Dimension(800,500));
setLocationRelativeTo(null);
}
}
In this final class is the JPanel class where I override and call paintComponent. However, nothing shows up.
public class Panel extends JPanel{
Panel(){
setPreferredSize(new Dimension(800,500));
setMinimumSize(new Dimension(800,500));
}
#Override
protected void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.blue);
g2.fillOval(100,100,100,100);
}
I've looked at dozens of other posts and I've tried many different things, and yet nothing shows up. Does anyone know what is going on?
I run you posted code and it seemed to work just fine, however, the reliance on static is very worrying and is likely to lead into some very interesting problems, best to avoid it.
Also, you should ensure that your UI is created within the context of the Event Dispatching Thread to reduce possible thread violation issues which could cause more problems.
Finally, you don't really need to extend JFrame, you're not really adding any value to the class and you could use a factory or builder pattern to achieve the same thing with less complexity
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Pong1 {
public static void main(String[] args) {
new Pong1();
}
public Pong1() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Pong");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new Panel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class Panel extends JPanel {
public Panel() {
}
#Override
public Dimension getPreferredSize() {
return new Dimension(800, 500);
}
#Override
public Dimension getMinimumSize() {
return getPreferredSize();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
System.out.println("...");
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.blue);
g2.fillOval(100, 100, 100, 100);
}
}
}
Oh, and you really should avoid using setPreferred/Minimum/MaximumSize, see Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing? for more discussions on the subject

Java's drawImage method doesn't show the image

I'm just beginner at Java Programming and am using NetBeans. The code below runs and No Error is displayed but no image is seen! This image is in the "frame" package beside this two classes.
package frame;
import javax.swing.JPanel;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
public class Screen extends JPanel{
private BufferedImage image;
public Screen(){
try {
System.out.println("OK");
image = ImageIO.read(getClass().getResourceAsStream("phantomPDF.png"));
} catch(IOException e) {
e.printStackTrace();
}
repaint();
}
public void paint(Graphics g){
g.drawImage(image, 100, 100, null);
System.out.println("Yes");
}
}
and this is my frame and main method :
package frame;
import java.awt.GridLayout;
import javax.swing.*;
public class Frame extends JFrame{
Screen s;
public Frame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 600);
setResizable(false);
setTitle("Graphics");
setVisible(true);
init();
}
public void init(){
setLocationRelativeTo(null);
setLayout(new GridLayout(1, 1, 0, 0));
s = new Screen();
add(s);
}
public static void main(String[] args){
new Frame();
}
}
I had to put "try - catch" statement into "paint" class so that works fine now ... but why should i do that?

Categories

Resources