String is not showing up in JFrame - java

I'm programming a little game where i want to show up a StartScreen and after clicking on it the game will start. But the String's don't show up.
The code is:
int nRows = 115;
int nCols = 42;
int[][] grid;
Font smallFont;
public hitit() {
setPreferredSize(new Dimension(1150,420));
setBackground(Color.orange);
setFont(new Font("SansSerif", Font.BOLD, 48));
smallFont = getFont().deriveFont(Font.BOLD,18);
setFocusable(true);
}
void drawStartScreen(Graphics2D g) {
g.setColor(Color.red);
g.setFont(smallFont);
g.drawString("hit it",600,100);
g.drawString("(click to start)", 250, 240);
}
public void paintComponent(Graphics2D gg) {
super.paintComponent(gg);
Graphics2D g = (Graphics2D) gg;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
drawStartScreen(g);
}
public static void main(String[] args) {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setTitle("hit it");
f.setResizable(true);
f.add(new hitit(), BorderLayout.CENTER);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}
I tried to implement a run-method but that didn't changed the problem

So I copy-pasted the code into a new file and now it's actually working
I don't know why, but the position for the two strings was not problem.
package testetetetet;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class hitit extends JPanel {
int nRows = 115;
int nCols = 42;
Font smallFont;
public hitit() {
setPreferredSize(new Dimension(1150, 420));
setBackground(Color.orange);
setFont(new Font("SansSerif", Font.BOLD, 48));
setFocusable(true);
smallFont = getFont().deriveFont(Font.BOLD, 18);
}
void drawStartScreen(Graphics2D g) {
g.setColor(Color.red);
g.setFont(smallFont);
g.drawString("hit it", 1150/2, 190);
g.drawString("(click to start)", 1150/2, 240);
}
public void paintComponent(Graphics gg) {
super.paintComponent(gg);
Graphics2D g = (Graphics2D) gg;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
drawStartScreen(g);
}
public static void main(String[] args) {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setTitle("hit it");
f.setResizable(false);
f.add(new hitit(), BorderLayout.CENTER);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}

There's so much wrong with this code I don't even know where to begin.
I guess for a start this mess won't compile. public hitit() is clearly missing a return type, and it's impossible to say what component are you using there and where does public void paintComponent(Graphics2D gg) method belong.
In general though the whole approach seems to be wrong - why do you want to draw text manually instead of using an available component like javax.swing.JLabel?

Related

How do you create a gradient for JPanel? Also, how do you call a class within a class in Java?

I am making a Java GUI and I have searched the internet for 2 hours on how make a gradient for a JPanel. The code below is that I have, but when run the gradient does not show. What is wrong?
I've tried many other posts from similar questions on this throughout the Internet but they don't work. I've tried numerous versions, but I also don't exactly know how to run a class within a class. Can someone help me please?
class TestPanel extends JPanel{
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
int w = getWidth();
int h = getHeight();
Color color1 = Color.BLUE;
Color color2 = Color.GREEN;
GradientPaint gp = new GradientPaint(0, 0, color1, 0, h, color2);
g2d.setPaint(gp);
g2d.fillRect(0, 0, w, h);
}
} //this is nested within the main class
//some code
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
CreateGUI cg = new CreateGUI();
cg.create(); //previous method (not mentioned here)
CreateGUI.TestPanel tp = cg.new TestPanel(); //problem
JPanel panel = new JPanel();
f.add(panel);
f.setSize(800, 600);
f.setLocationRelativeTo(null);
f.getContentPane().setLayout(null);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
});
}
I expect there to be a gradient but there is none; the background of the JPanel is still white
The instance of TestPanel is never added to anything
null layouts will prevent the component from been sized and positioned, so you won't see anything even if your did the previous step
You should, unless you're adding child components to it, provide a sizing hint, so that the layout managers have something to work with.
For example:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new TestPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
class TestPanel extends JPanel {
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
int w = getWidth();
int h = getHeight();
Color color1 = Color.BLUE;
Color color2 = Color.GREEN;
GradientPaint gp = new GradientPaint(0, 0, color1, 0, h, color2);
g2d.setPaint(gp);
g2d.fillRect(0, 0, w, h);
g2d.dispose();
}
}
}

Image appears on mouse click on the cursor location in JFrame

I am trying to make a GUI in Java. I have a JFrame and I create a JPanel in it. I add them manually when I click on "Design".
When a click with the mouse on the Panel then an icon should appear where I clicked. It should appear as many times as I click on the Panel. I try to use the answer given here but it does not work as the Panel there is not added manually:
Add image on mouse click? Java applet
I am using the same code and I try to adjust it to the event MouseClicked for the jPanel1 which I have added manually:
private Point drawPoint;
Graphics g;
private void jPanel1MouseClicked(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
System.out.println("I can click.");
Toolkit toolkit = Toolkit.getDefaultToolkit();
Image image = toolkit.getImage("Icons/p.png");
drawPoint = new Point(evt.getPoint());
repaint();
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
if (drawPoint != null) {
g2d.drawImage(image, drawPoint.x, drawPoint.y, this);
}
g2d.dispose();
}
It says that it cannot find symbol for:super.paintComponent(g)
If I use the given code in the example in a newly created class, it works fine without the fact that I want the image to appear again and again instead of removing it each time and appearing only once.
Does anyone know how to fix it?
EDIT
import javax.swing.JFrame;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.imageio.ImageIO;
import javax.swing.*;
public class editorPTnets{
private JButton b1;
private JButton b2;
private JButton b3;
private JButton b4;
public editorPTnets(){
JFrame f = new JFrame("P/T nets");
f.setSize(800, 500);
f.setLayout(null);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().setBackground(Color.gray);
f.add(new TestPane());
f.setLocationRelativeTo(null);
JPanel p = new JPanel();
p.setBounds(5, 50, 760, 400);
p.setBackground(Color.white);
f.add(p);
p.setVisible(true);
b1 = new JButton("");
b1.setBounds(5, 5, 40, 40);
b1.setVisible(true);
b1.setIcon(new
ImageIcon("C:\\Users\\Toshiba\\Desktop\\Java\\Icons\\new.png"));
f.add(b1);
b2 = new JButton("");
b2.setBounds(50, 5, 40, 40);
b2.setIcon(new
ImageIcon("C:\\Users\\Toshiba\\Desktop\\Java\\Icons\\open.png"));
b2.setVisible(true);
f.add(b2);
f.setVisible(true);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
new editorPTnets();
System.out.println("Hello, world");
public class TestPane extends JPanel {
Image image;
private Point drawPoint;
public TestPane() {
Toolkit toolkit = Toolkit.getDefaultToolkit();
image =
toolkit.getImage("C:\\Users\\Toshiba\\Desktop\\Java\\Icons\\p.png");
addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
drawPoint = new Point(e.getPoint());
repaint();
}
});
}
#Override
public Dimension getPreferredSize() {
return new Dimension(800, 500);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
if (drawPoint != null) {
g2d.drawImage(image, drawPoint.x, drawPoint.y, this);
}
g2d.dispose();
}
}
}
EDIT 2 FIXED
public mainFrame() {
JFrame f = new JFrame("Editor for graphs");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(800, 600);
f.getContentPane().setBackground(Color.blue);
f.setResizable(false);
f.setLayout(new BorderLayout());
f.add(new Panel1(), BorderLayout.SOUTH);
f.setLocationRelativeTo(null);
f.setVisible(true);
This helped me fix the problem.

Set Transparent Color for the Whole JPanel

I have a JPanel with a JLabel which owns an Icon picture.
how do I set a transparent red color at the top of the whole JPanel (including JLabel Icon)?
I have the transparent backgriound color on for the panel but I want the whole panel including the picture and everything get this transparent color. something like a transparent colorful glass at the top of the JPanel
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class TransparentJLabel {
private static final String IMAGE_PATH = "http://duke.kenai.com/Oracle/OracleStratSmall.png";
private static void createAndShowUI() {
JPanel panel = new JPanel();
panel.setBackground(Color.pink);
URL imageUrl;
try {
imageUrl = new URL(IMAGE_PATH);
BufferedImage image = ImageIO.read(imageUrl);
ImageIcon icon = new ImageIcon(image);
JLabel label = new JLabel(icon);
panel.add(label);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
JFrame frame = new JFrame("TransparentJLabel");
frame.getContentPane().add(panel);
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();
}
});
}
}
If you just need a layered panel over the whole contentPane, a simple glassPane will do fine (override it's paintComponent(...) method). For example:
JPanel glassPane = new JPanel() {
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g.create();
g2.setColor(new Color(0, 100, 0, 100));
g2.fillRect(0, 0, getWidth(), getHeight());
g2.dispose();
}
};
glassPane.setOpaque(false);
frame.setGlassPane(glassPane);
frame.getGlassPane().setVisible(true);
However, if you want a layered panel over only one JPanel, I would use JLayer combined with LayerUI, as MadProgrammer already mentioned. You will need a custom LayerUI in which you override the paint(Graphics g, JComponent c) method. I know that sounds dangerous, but I honestly don't know of another way of doing it...
I've provided an example below, this is the output:
As you can see, panel1 (or more accurately, the JLayer) is slighty transparent (RGBA = "0, 100, 0, 100") and panel2 is normal.
Code:
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.*;
import javax.swing.plaf.LayerUI;
public class Example {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new Example();
}
});
}
public Example() {
JFrame frame = new JFrame("Example");
JPanel panel1 = new JPanel();
panel1.add(new JButton("Panel 1"));
MyLayerUI layerUI = new MyLayerUI();
JLayer<JPanel> panel1Layer = new JLayer<JPanel>(panel1, layerUI);
panel1.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
if (layerUI.hasOverlay()) {
layerUI.setOverlay(false);
} else {
layerUI.setOverlay(true);
}
panel1Layer.repaint();
}
});
JPanel panel2 = new JPanel();
panel2.add(new JButton("Panel 2"));
JPanel contentPane = new JPanel(new GridLayout(2, 1));
contentPane.add(panel1Layer);
contentPane.add(panel2);
frame.setContentPane(contentPane);
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
class MyLayerUI extends LayerUI<JPanel> {
private boolean overlay = true;
#Override
public void paint(Graphics g, JComponent c) {
super.paint(g, c);
if (hasOverlay()) {
Graphics2D g2 = (Graphics2D) g.create();
g2.setColor(new Color(0, 100, 0, 100));
g2.fillRect(0, 0, c.getWidth(), c.getHeight());
g2.dispose();
}
}
public boolean hasOverlay() {
return overlay;
}
public void setOverlay(boolean overlay) {
this.overlay = overlay;
}
}

ImageIcon is displayed as a small square

where is the problem. It does not show image properly.
default.png = *********
what i see = *********
I dont think there is a problem with png. It is also in my src and I refreshed it on eclipse.
codes:
import java.awt.*;
import javax.swing.*;
public class Main {
public static void main(String[] args) {
JFrame jf = new JFrame();
jf.setTitle( "test");
jf.setLayout( new FlowLayout());
jf.setSize(350, 450);
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.add(new Panel());
}
}
panel:
import java.awt.Graphics;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
public class Panel extends JPanel {
// PROPERTIES
public ImageIcon icon;
// CONSTRUCTORS
public Panel() {
icon = new ImageIcon(this.getClass().getResource("default.png"));
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawImage(icon.getImage(), 0, 0, null);
}
}
This answer addresses my criticism of the answer by the OP. The example incorporates the advice added in various comments.
import java.awt.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.border.LineBorder;
public class Main {
public static void main(String[] args) throws Exception {
URL url = new URL("http://i.imgur.com/o0E0aGD.png");
BufferedImage bi = ImageIO.read(url);
JFrame jf = new JFrame();
jf.setTitle("test");
jf.setLayout(new FlowLayout());
//jf.setSize(350, 450); just pack()
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.add(new BackgroundImagePanel(bi));
jf.pack();
jf.setMinimumSize(jf.getSize());
jf.setVisible(true);
}
}
class BackgroundImagePanel extends JPanel {
public Image img;
// CONSTRUCTOR
public BackgroundImagePanel(Image img) {
this.img = img;
this.setBorder(new LineBorder(Color.RED, 2));
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(img, 0, 0, this);
// g.drawImage(img, 0, 0, getWidth(), getHeight(), this); // Better!
}
#Override
public Dimension getPreferredSize() {
Dimension d = super.getPreferredSize();
int w = d.width>img.getWidth(this) ? d.width : img.getWidth(this);
int h = d.height>img.getHeight(this) ? d.height : img.getHeight(this);
return new Dimension(w, h);
}
}
I solved this by adding at Panel class constructor:
setPreferredSize(new Dimension( 500, 500 ));

Paint method java - Rectangle with outline

I want to create a wall with a blue line outline and black filling. I have only a blue wall now and I tried a couple of the Graphics methods but wasn't working.
public void paint(Graphics g) {
g.setColor(Color.blue);
g.fillRect(x, y, size, size);
}
Use Graphics#drawRect to draw the outline: -
g.setColor(Color.black);
g.fillRect(x, y, size, size);
g.setColor(Color.blue);
g.drawRect(x, y, size, size);
First, override paintComponent, not paint. Second, there's no need to re-invent the wheel like that. Instead, use an existing Swing component (e.g. JPanel),
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class Main
{
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable(){
#Override
public void run() {
createAndShowGUI();
}
});
}
private static void createAndShowGUI()
{
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new FlowLayout());
frame.add(getWallComponent());
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private static JPanel getWallComponent()
{
JPanel panel = new JPanel();
panel.setBackground(Color.black);
panel.setBorder(BorderFactory.createLineBorder(Color.blue, 5));
panel.setPreferredSize(new Dimension(200, 200)); // for demo purposes only
return panel;
}
}
Just paint another rectangle over the blue one, smaller than the blue one, like below
public void paint(Graphics g) {
g.setColor(Color.blue);
g.fillRect(x, y, size, size);
g.setColor(Color.black);
g.fillRect(x-width/2,y-width/x,size-width,size-with);
}
package painting;
import java.awt.*;
import javax.swing.*;
public class RectangleOutline extends JPanel {
int x = 100;
int y = 200;
public void paintComponent(Graphics g) {
super.paintComponent(g);
outline(g);
}
public void outline(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setColor(new Color(255, 0, 0));
g2.fillRect(x, y, 30, 30);
g2.setStroke(new BasicStroke(5));
g2.setColor(new Color(0, 0, 0));
g2.drawRect(x, y, 30, 30);
}
public static void main(String[] args){
JFrame f = new JFrame();
RectangleOutline graphics = new RectangleOutline();
f.add(graphics);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
f.setSize(400, 400);
}
}

Categories