Why is the background black? - java

The background worked before I added the paint method, I assume the paint method overrides the setBackground and setForeground methods in run, but I'm not sure how I can fix this problem.
import java.awt.Color;
import java.awt.DisplayMode;
import java.awt.Font;
import java.awt.Graphics;
import javax.swing.JFrame;
public class Afterworld extends JFrame{
public static void main(String[] args){
DisplayMode dm = new DisplayMode(800, 600, 16, DisplayMode.REFRESH_RATE_UNKNOWN);
Afterworld game = new Afterworld();
game.run(dm);
}
public void run(DisplayMode dm){
setBackground(Color.PINK);
setForeground(Color.WHITE);
setFont(new Font("Arial", Font.PLAIN, 24));
Screen screen = new Screen();
try{
screen.setFullScreen(dm, this);
try{
Thread.sleep(5000);
}catch(Exception ex){}
}finally{
screen.restoreScreen();
}
}
public void paint(Graphics g){
g.drawString("test", 200, 200);
}
}

You shoud change your paint method for:
public void paint(Graphics g){
super.paint(g);
g.drawString("test", 200, 200);
}
The call to super.paint(g); executes whatever code is in the superclass. That is exactly the code that painted the background before you added the paint method.
You can learn more about accessing superclass' members at http://docs.oracle.com/javase/tutorial/java/IandI/super.html

Related

Why are Graphics2D rectangles not displayed?

I need to be able to display filled rectangles for the program i am creating, however the following code produces the following GUI with only the black text 'test' after calling start then change, could anyone explayin why please?
package core;
import java.awt.Color;
import java.awt.Graphics2D;
import javax.swing.JFrame;
#SuppressWarnings("serial")
public class GUI extends JFrame{
private Graphics2D g;
private int[][][] clickable;
public void start(){
this.setSize(500, 500);
this.setTitle("Placeholder");
this.setVisible(true);
g = (Graphics2D) this.getGraphics();
}
public void change(String[] fields, int type[], boolean forwards){
g.setColor(new Color(28,35,57));
g.drawRect(0, 0, 100, 100);
g.drawRect(50, 50, 150, 150);
g.fillRect(0, 0, 100, 100);
g.drawString("test", 300, 300);
}
}
And here is what it looks like ..
Drawing on Swing components (like JFrame) works only in onPaint event.
The event can be fired using repaint() method.
This event fires automatically when frame needs to be painted.
To implement this event behavior override paint() method.
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
public class GUI extends JFrame{
private Graphics2D g;
public void start(){
this.setSize(500, 500);
this.setTitle("Placeholder");
this.setVisible(true);
}
public void change(){
g.setColor(new Color(28,35,57));
g.drawRect(0, 0, 100, 100);
g.drawRect(50, 50, 150, 150);
g.fillRect(0, 0, 100, 100);
g.drawString("test", 300, 300);
}
public void paint(Graphics g2d){
g = (Graphics2D) g2d;
change();
}
public static void main(String[] args){
GUI frame = new GUI();
frame.start();
}
}

Paint not showing up

I am using a JFrame and a pane and trying to draw a simple square.
My painting is not showing up. I made I set the color to black so it should be visible.
Code:
package W2;
import java.awt.Color;
import java.awt.Container;
import java.awt.Graphics;
import javax.swing.*;
public class W2 {
JFrame frame = new JFrame("W2");
public W2(){
Container pane = new Container();
frame.setContentPane(pane);
frame.setSize(750,500);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setVisible(true);
}
public void paint(Graphics g){
g.setColor(Color.BLACK);
g.fillRect(50, 50, 50, 50);
}
public static void main(String args[]){
new W2();
}
}
The paint method won't be called because it's not part of a object that can be painted.
See Performing Custom Painting for details about how painting is done in Swing
For example...
frame.setContentPane(new JPanel() {
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.BLACK);
g.fillRect(50, 50, 50, 50);
}
});

How to 'undraw' an Image?

I am trying to make a simple game in Java, All i need to do is draw an im onto the screen and then wait for 5 seconds then 'undraw it'.
Code (this class draws the image on the screen):
package com.mainwindow.draw;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
#SuppressWarnings("serial")
public class MainWindow extends JPanel{
Image Menu;
String LogoSource = "Logo.png";
public MainWindow() {
ImageIcon ii = new ImageIcon(this.getClass().getResource(LogoSource));
Menu = ii.getImage();
Timer timer = new Timer(5, new ActionListener() {
public void actionPerformed(ActionEvent e) {
repaint();
}
});
timer.start();
}
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2 = (Graphics2D) g;
g2.drawImage(Menu, 0, 0, getWidth(), getHeight(), null);
}
}
Code #2 (this creates the JFrame)
package com.mainwindow.draw;
import javax.swing.JFrame;
#SuppressWarnings("serial")
public class Frame extends JFrame {
public Frame() {
add(new MainWindow());
setTitle("Game Inviroment Graphics Test");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(640, 480);
setLocationRelativeTo(null);
setVisible(true);
setResizable(false);
}
public static void main(String[] args) {
new Frame();
}
}
Use some kind of flag to determine if the image should be drawn or not and simply change it's state as needed...
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
if (draw) {
g2.drawImage(Menu, 0, 0, getWidth(), getHeight(), null);
}
}
Then change the state of the flag when you need to...
Timer timer = new Timer(5, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
draw = false;
repaint();
}
});
Note: It's not recommended to to override paint, paint is at the top of the paint change and can easily break how the paint process works, causing no end of issues. Instead, it's normally recommended to use paintComponent instead. See Performing Custom Painting for more details
Also note: javax.swing.Timer expects the delay in milliseconds...5 is kind of fast...

about drawing a Polygon in java

hi there i'm trying to improve myself about java2D and first of all i'm dealing with drawing polygons. However, i can not see the polygon on frame. I read some tutorials and examples but as i said i face with problems. here is the sample code of drawing a polygon;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Polygon;
import javax.swing.JFrame;
public class jRisk extends JFrame {
private JFrame mainMap;
private Polygon poly;
public jRisk(){
initComponents();
}
private void initComponents(){
mainMap = new JFrame();
mainMap.setSize(800, 600);
mainMap.setResizable(false);
mainMap.setVisible(true);
mainMap.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
int xPoly[] = {150,250,325,375,450,275,100};
int yPoly[] = {150,100,125,225,250,375,300};
poly = new Polygon(xPoly, yPoly, xPoly.length);
}
protected void paintComponent(Graphics g){
super.paintComponents(g);
g.setColor(Color.BLUE);
g.drawPolygon(poly);
}
/**
* #param args
*/
public static void main(String[] args) {
new jRisk();
}
}
JFrame does not have a paintComponent(Graphics g) method. Add the #Override annotation and you will get a compile time error.
1) Use JPanel and override paintComponent (you would than add JPanel to the JFrame viad JFrame#add(..))
2) Override getPreferredSize() to return correct Dimensions which fit your drawing on Graphics object or else they wont be seen as JPanel size without components is 0,0
3) dont call setSize on JFrame... rather use a correct LayoutManager and/or override getPrefferedSize() and call pack() on JFrame after adding all components but before setting it visible
4) Have a read on Concurrency in Swing specifically about Event Dispatch Thread
5) watch class naming scheme should begin with a capital letter and every first letter of a new word thereafter should be capitalized
6) Also you extend JFrame and have a variable JFrame? Take away the extend JFrame and keep the JFrame variable as we dont want 2 JFrames and its not good practice to extend JFrame unless adding functionality
Here is your code with above fixes (excuse picture quality but had to resize or it was going to 800x600):
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Polygon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class JRisk {
private JFrame mainMap;
private Polygon poly;
public JRisk() {
initComponents();
}
private void initComponents() {
mainMap = new JFrame();
mainMap.setResizable(false);
mainMap.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
int xPoly[] = {150, 250, 325, 375, 450, 275, 100};
int yPoly[] = {150, 100, 125, 225, 250, 375, 300};
poly = new Polygon(xPoly, yPoly, xPoly.length);
JPanel p = new JPanel() {
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.BLUE);
g.drawPolygon(poly);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(800, 600);
}
};
mainMap.add(p);
mainMap.pack();
mainMap.setVisible(true);
}
/**
* #param args
*/
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new JRisk();
}
});
}
}
As per your comment:
i am preparing a map which includes lots of polygons and yesterday i
used a JPanel over a JFrame and i tried to check if mouse was inside
of the polygon with MouseListener. later i saw that mouseListener gave
false responds (like mouse is not inside of the polygon but it acts
like it was inside the polygon). so i deleted the JPanel and then it
worked
Here is updated code with MouseAdapter and overridden mouseClicked to check if click was within polygon.
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Polygon;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class JRisk {
private JFrame mainMap;
private Polygon poly;
public JRisk() {
initComponents();
}
private void initComponents() {
mainMap = new JFrame();
mainMap.setResizable(false);
mainMap.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
int xPoly[] = {150, 250, 325, 375, 450, 275, 100};
int yPoly[] = {150, 100, 125, 225, 250, 375, 300};
poly = new Polygon(xPoly, yPoly, xPoly.length);
JPanel p = new JPanel() {
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.BLUE);
g.drawPolygon(poly);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(800, 600);
}
};
MouseAdapter ma = new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent me) {
super.mouseClicked(me);
if (poly.contains(me.getPoint())) {
System.out.println("Clicked polygon");
}
}
};
p.addMouseListener(ma);//add listener to panel
mainMap.add(p);
mainMap.pack();
mainMap.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new JRisk();
}
});
}
}
JFrame does not extend JComponent so does not override paintComponent. You can check this by adding the #Override annotation.
To get this functionality extract paintComponent to a new class which extends JComponent. Don't forget to call super.paintComponent(g) rather than super.paintComponents(g).
Replace
protected void paintComponent(Graphics g){
super.paintComponents(g);
g.setColor(Color.BLUE);
g.drawPolygon(poly);
}
With
protected void paint(Graphics g){
super.paint(g);
g.setColor(Color.BLUE);
g.drawPolygon(poly);
}

Getting blank window in swing gui [duplicate]

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
paintComponent () never executes on a JFrame
I am using the following code to dispaly two strings and i'm drawing them directly on jfame instead of adding them as component or to a jpanel.But Why am i getting a blank window instead of getting Strings.Where am i wrong?
import java.awt.Color;
import java.awt.Container;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class SimpleAttributes extends JFrame{
SimpleAttributes()
{
super("Simple Attributes");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 200);
//setUndecorated(true);
Container cp=this.getContentPane();
cp.setBackground(new Color(0,200,0,0));
setVisible(true);
}
public void paintComponent(Graphics g)
{
Graphics2D g2=(Graphics2D)g.create();
g2.setColor(Color.RED);
g2.drawString("One", 10, 10);
g.drawString("Two", 10,40);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
SwingUtilities.invokeLater(new Runnable(){public void run(){new SimpleAttributes();}});
}
}
JFrame is not a component, therefor there's no paintComponent() function for it. See the API documentation.
As mentioned the above is incorrect there is no such method, (I was to fast at typing) and thinking about JPanels.
what you can do is create your own Container and override the paint() method then use that as your ContentPane by frame.setContentPane(Container con):
import java.awt.Color;
import java.awt.Container;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class SimpleAttributes extends JFrame {
SimpleAttributes() {
super("Simple Attributes");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 200);
//setUndecorated(true);
setContentPane(new MyContainer());
getContentPane().setBackground(new Color(0, 200, 0, 0));
setVisible(true);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new SimpleAttributes();
}
});
}
}
class MyContainer extends Container {
#Override
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2 = (Graphics2D) g.create();
g2.setColor(Color.RED);
g2.drawString("One", 10, 10);
g.drawString("Two", 10, 40);
}
}
as noted in a comment on one answer you can use the paint() of the JFrame just compensate for the offset of the dialog's header :
import java.awt.Color;
import java.awt.Container;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class SimpleAttributes extends JFrame {
SimpleAttributes() {
super("Simple Attributes");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 200);
//setUndecorated(true);
getContentPane().setBackground(new Color(0, 200, 0, 0));
setVisible(true);
}
#Override
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2 = (Graphics2D) g.create();
g2.setColor(Color.RED);
g2.drawString("One", 10, 10);//wont show
g2.drawString("One", 50, 50);//will show
g.drawString("Two", 40, 40);//will show
}
public static void main(String[] args) {
// TODO Auto-generated method stub
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new SimpleAttributes();
}
});
}
}
but all of thats just going to give you more headaches why not just do it the preferred way? A JPanel and override paintComponent(Graphics g);

Categories