Java | previous frame doesn't disappear - java

I'm writing a small game in java but I have a little problem. All the rendered frames stay on the screen, so if I move the image, it just keeps rendering more images, but I want my image to move over the screen. What am I doing wrong?
public void tick(){
balk.tick();
}
public void render(){
BufferStrategy bs = this.getBufferStrategy();
if(bs==null){
createBufferStrategy(2);
return;
}
Font myFont = new Font ("Courier New", 1, 50);
Graphics g = bs.getDrawGraphics();
///////////////////////////////
g.drawImage(balk.getBalk(), balk.getX(), 900, this);
g.setFont(myFont);
g.drawString("Score: " + 0, 50, 100);
///////////////////////////////
//g.dispose();
bs.show();
}
public void init(){
frame = new JFrame();
WIDTH = (int)Toolkit.getDefaultToolkit().getScreenSize().getWidth();
HEIGHT = (int)Toolkit.getDefaultToolkit().getScreenSize().getHeight();
}
public static void main(String[] args){
Game game = new Game();
game.init();
game.setPreferredSize(new Dimension(WIDTH, HEIGHT));
game.setMaximumSize(new Dimension(WIDTH, HEIGHT));
game.setMinimumSize(new Dimension(WIDTH, HEIGHT));
frame.add(game);
frame.setUndecorated(true);
frame.setTitle("Ping Pong");
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setLayout(null);
frame.addKeyListener(new KeyListener(){
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if(key == KeyEvent.VK_A){
balk.setVelX(-5);
}
if(key == KeyEvent.VK_D){
balk.setVelX(5);
}
}
public void keyReleased(KeyEvent e) {
balk.setVelX(0);
}
public void keyTyped(KeyEvent arg0) {}
});
frame.setVisible(true);
game.start();
}
}

Clear the screen before drawing anything with a fillRect that fills yours window, in a color you like.
g.setColor(Color.black);
g.fillRect(0, 0, width, height);
//draw here
Something like this.

Related

Failing to call a call paintcomponent method :(

What I am trying to achieve is that the program would draw a line in the middle of the frame as soon as the user has clicked draw. But sadly nothing is happening other than "frame 3" is disappearing. Any ideas about how I could fix the problem?
Here is the method:
Windowj is my frame. Frame3 is the previous frame please don't worry about it.
public static void graf() {
frame3.setVisible(false);
windowj.setSize(400, 500);
windowj.setLocationRelativeTo(null);
windowj.setResizable(false);
windowj.setLayout(null);
windowj.setVisible(true);
windowj.setTitle("Graphs");
windowj.setDefaultCloseOperation(EXIT_ON_CLOSE);
xinwindow.setBounds(30,40, 90, 40);
yinwindow.setBounds(100,100,90,40);
thefunction.setBounds(200,300,90,40);
draw.setBounds(300,200,90,40 );
windowj.add(xinwindow);
windowj.add(yinwindow);
windowj.add(thefunction);
windowj.add(draw);
c.setPreferredSize(new Dimension(300,200));
draw.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
windowj.add(c);
c.revalidate();
c.repaint();
}
And here is the paintcomponent method:
private static Component c = new JComponent() {
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.black);
g.drawLine(50, 0, 70 , 100);
}
};
Any help would be appreciated, and please try to keep it simple, I am a beginner. :)
I will assume you use windowj as your JFrame and that what will happen when you click draw button your use windowj.setVisible(false) and that will make your window disappear
so remove it
2nd thing is you need to put your Component in windowj as windowj.add(c); in your draw ActionListener at actionPerformed before c.revalidate();
and here a little code that I wrote to understand what I mean:
public class DrawLine {
private JFrame windowj = new JFrame();
private JButton draw = new JButton();
private static int width = 640, height = 480;
private static JComponent c = new JComponent() {
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.black);
g.drawLine((width/2) - 1, 0, (width/2) +1 , height);
}
};
public DrawLine() {
windowj.setDefaultCloseOperation(windowj.EXIT_ON_CLOSE);
windowj.setSize(width, height);
windowj.setLayout(new FlowLayout());
windowj.setResizable(false);
windowj.setLocationRelativeTo(null);
windowj.setVisible(true);
draw = new JButton("Draw");
draw.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//i don't know why you set windowj(windowj) false but that will close your window
//windowj.setVisible(false);
//add component to windowj(windowj)
windowj.add(c);
c.revalidate();
c.repaint();
}
});
c.setPreferredSize(new Dimension(width, height-100));
windowj.add(draw);
}
public static void main(String[] args) {
new DrawLine();
}
}
Here is the modified code:
private JFrame frame3, windowj;
private JPanel xinwindow, yinwindow,thefunction;
private JButton draw;
private static Component c = new JComponent() {
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.black);
g.drawLine(50, 0, 70 , 100);
}
};
public DrawLine() {
xinwindow = new JPanel();
yinwindow = new JPanel();
thefunction = new JPanel();
draw = new JButton("Draw");
//i ignored frame3 as you said so just ignore my implementation here
frame3 = new JFrame();
frame3.setVisible(false);
windowj = new JFrame();
windowj.setSize(400, 500);
windowj.setLocationRelativeTo(null);
windowj.setResizable(false);
windowj.setLayout(null);
windowj.setVisible(true);
windowj.setTitle("Graphs");
windowj.setDefaultCloseOperation(EXIT_ON_CLOSE);
/*i used setBackground(Color.anycolor); to make it easier for me to know where
your window is in your frame*/
xinwindow.setBackground(Color.RED);
xinwindow.setBounds(30,40, 90, 40);
yinwindow.setBackground(Color.yellow);
yinwindow.setBounds(100,100,90,40);
thefunction.setBounds(200,300,90,40);
thefunction.setBackground(Color.green);
draw.setBounds(300,200,90,40 );
windowj.add(xinwindow);
windowj.add(yinwindow);
windowj.add(thefunction);
windowj.add(draw);
//here use setBonds instead of setPreferredSize
c.setBounds(100, 200, 200, 200);
draw.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
windowj.add(c);
c.revalidate();
c.repaint();
}
});
}
public static void main(String[] args) {
new DrawLine();
}
hope that solve your problem.

How to fill the whole window in awt

I'm using java awt to render a simple rectangle. I also have a rectangle to be used as the background of the window. The thing is, even though the background rectangle is set to the window's width and height, it still doesn't fit the whole thing. I've tried to Google this, but found results irrelevant to my needs. What's causing this?
import java.awt.Canvas;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.event.MouseAdapter;
import java.awt.image.BufferStrategy;
import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Game implements Runnable{
final int WIDTH = 640;
final int HEIGHT = 480;
JFrame frame;
Canvas canvas;
BufferStrategy bufferStrategy;
boolean running = false;
public Game(){
frame = new JFrame("Prototyping");
JPanel panel = (JPanel) frame.getContentPane();
panel.setPreferredSize(new Dimension(WIDTH, HEIGHT));
panel.setLayout(null);
canvas = new Canvas();
canvas.setBounds(0, 0, WIDTH, HEIGHT);
canvas.setIgnoreRepaint(true);
panel.add(canvas);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setResizable(false);
frame.setVisible(true);
canvas.createBufferStrategy(2);
bufferStrategy = canvas.getBufferStrategy();
canvas.requestFocus();
}
public void run(){
running = true;
while(running)
render();
}
private void render() {
Graphics2D g = (Graphics2D) bufferStrategy.getDrawGraphics();
g.clearRect(0, 0, WIDTH, HEIGHT);
render(g);
g.dispose();
bufferStrategy.show();
}
protected void update(){
}
protected void render(Graphics2D g){
g.setColor(Color.GRAY);
g.fillRect(0, 0, WIDTH, HEIGHT);
g.setColor(Color.BLUE);
g.fillRect(100, 0, 200, 200);
}
public static void main(String [] args){
Game game = new Game();
new Thread(game).start();
}
}
This works flawlessly here. Go through it carefully for differences, since I've forgotten what is changed.
import java.awt.*;
import java.awt.image.BufferStrategy;
import javax.swing.*;
public class Game implements Runnable{
final int WIDTH = 640;
final int HEIGHT = 480;
JFrame frame;
Canvas canvas;
BufferStrategy bufferStrategy;
boolean running = false;
public Game(){
frame = new JFrame("Prototyping");
JPanel panel = (JPanel) frame.getContentPane();
panel.setPreferredSize(new Dimension(WIDTH, HEIGHT));
panel.setLayout(new GridLayout());
canvas = new Canvas();
//canvas.setBounds(0, 0, WIDTH, HEIGHT);
canvas.setIgnoreRepaint(true);
panel.add(canvas);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setResizable(false);
frame.setVisible(true);
canvas.createBufferStrategy(2);
bufferStrategy = canvas.getBufferStrategy();
canvas.requestFocus();
}
public void run(){
running = true;
while(running)
render();
}
private void render() {
Graphics2D g = (Graphics2D) bufferStrategy.getDrawGraphics();
g.clearRect(0, 0, WIDTH, HEIGHT);
render(g);
g.dispose();
bufferStrategy.show();
}
protected void render(Graphics2D g){
g.setColor(Color.GRAY);
g.fillRect(0, 0, WIDTH, HEIGHT);
g.setColor(Color.BLUE);
g.fillRect(100, 0, 200, 200);
}
public static void main(String [] args){
Game game = new Game();
new Thread(game).start();
}
}

How to restart?

I have this code and I want the user to be able to restart the game by pressing R, but I do not know how to do this, I've tried to call the main method again, which obviously didn't work, but I don't know any other way to restart it, this is the main class code:
import javax.swing.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
public class Main extends JPanel implements KeyListener {
long startT = System.currentTimeMillis();
long elapsedTimeMillis;
float elapsedT;
private Player player;
private Stage stage;
private boolean isGameOver = false;
private EnemyManager manager;
public Main() {
setSize(800,600);
setPreferredSize(new Dimension(800,600));
setFocusable(true);
addKeyListener(this);
stage = new Stage();
player = new Player(this, 200, 500);
manager = new EnemyManager(this, 10);
}
#Override
public void update(Graphics g){
paint(g);
}
public void paint(Graphics g){
g.setColor(Color.BLACK);
g.fillRect(0, 0, getWidth(), getHeight());
if(!isGameOver){
player.draw(g);
manager.draw(g);
stage.draw(g);
long elapsedTimeMillis = System.currentTimeMillis() - startT;
elapsedT = elapsedTimeMillis/1000F;
g.setColor(Color.white);
g.setFont(new Font("Century Gothic", Font.BOLD, 24));
g.drawString("You're alive for: " + elapsedT, 400, 50);
}else {
g.setFont(new Font("Century Gothic", Font.BOLD, 55));
g.setColor(Color.RED);
g.drawString("Game Over" , 250, 150);
g.setColor(Color.ORANGE);
g.setFont(new Font("Century Gothic", Font.BOLD, 24));
g.drawString("You lasted for: ", 300, 250);
g.drawString("Press to restart", 300, 300);
g.setColor(Color.white);
g.drawString("" + elapsedT, 480, 250);
g.drawString("R", 364, 300);
}
g.dispose();
repaint();
}
#Override
public void keyPressed(KeyEvent e) {
int code = e.getKeyCode();
if (code == KeyEvent.VK_W){
}
if (code == KeyEvent.VK_A){
player.setdirectionX(-1);
}
if (code == KeyEvent.VK_S){
}
if (code == KeyEvent.VK_D){
player.setdirectionX(1);
}
if (code == KeyEvent.VK_R){
}
}
public void setGameOver(boolean flag){
isGameOver = flag;
}
#Override
public void keyReleased(KeyEvent e){
player.setdirectionX(0);
player.setdirectionY(0);
}
#Override
public void keyTyped(KeyEvent e) {
}
public Stage getStage(){
return stage;
}
public EnemyManager getEnemyManager(){
return manager;
}
public static void main(String[] args){
JFrame frame = new JFrame();
frame.setTitle("Dodge the bloody rectangles");
frame.add(new Main());
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(new Dimension(800,600));
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
public void restart() {
stage = new Stage();
player = new Player(this, 200, 500);
manager = new EnemyManager(this, 10);
isGameOver = false;
}
...
#Override
public void keyPressed(KeyEvent e) {
...
if (code == KeyEvent.VK_R){
restart();
}
}

Swing app not drawing JComponent inside JPanel

I am currently writing a Java painting program using the Swing libraries and Graphics2D to paint. My main GUI class extends JComponent, and I am trying to put it inside a JPanel, and the JPanel inside a JFrame, in order to show it on the screen. When starting up the program though, the JComponent appears to be just a black line (the border, which is set to be a black line around the component). I cannot see why this is happening, and I've been debugging it for hours. If somebody could find the error in this program, I'd be very happy. Thanks in advance.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class PaintGUI extends JComponent {
private static final long serialVersionUID = 1L;
JButton red, green, blue, clear;
Image img;
Graphics2D gfx;
JFrame drawFrame;
JPanel btnPan, drawPan;
MyListener ml;
Action act;
int x, y, prevX, prevY;
public PaintGUI(){
//Initialisering av panel, frame og content
drawFrame = new JFrame("IFIPaint");
drawFrame.setLayout(new BorderLayout());
btnPan = new JPanel();
drawPan = new JPanel();
btnPan.setLayout(new FlowLayout());
drawPan.setLayout(new BorderLayout());
this.setEnabled(true);
//Setter størrelser
btnPan.setPreferredSize(new Dimension(30, 60));
btnPan.setMinimumSize(new Dimension(30, 60));
btnPan.setMaximumSize(new Dimension(30, 60));
//Ordner knappene
red = new JButton("Rød");
green = new JButton("Grønn");
blue = new JButton("Blå");
clear = new JButton("Slett alt");
//Putter knappene på panelet
btnPan.add(red);
btnPan.add(green);
btnPan.add(blue);
btnPan.add(clear);
//Legger på action listeners
act = new Action();
red.addActionListener(act);
green.addActionListener(act);
blue.addActionListener(act);
clear.addActionListener(act);
//Fullfører vindu og setter synlighet
drawFrame.setSize(500, 500);
drawPan.setBounds(0, 0, 400, 400);
this.setBounds(0, 0, 400, 400);
drawPan.add(this);
this.setBackground(Color.RED);
drawFrame.add(drawPan, BorderLayout.NORTH);
drawFrame.add(btnPan, BorderLayout.SOUTH);
this.setBorder(BorderFactory.createLineBorder(Color.BLACK));
this.setVisible(true);
drawPan.setVisible(true);
btnPan.setVisible(true);
drawFrame.setVisible(true);
this.paintComponent(gfx);
drawFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
draw();
}
public void draw() {
ml = new MyListener();
this.addMouseListener(ml);
this.addMouseMotionListener(ml);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
if(img == null){
img = createImage(this.getWidth(),this.getHeight());
gfx = (Graphics2D) img.getGraphics();
gfx.setPaint(Color.RED);
gfx.fillRect(0, 0, this.getSize().width, this.getSize().height);
gfx.setPaint(Color.RED);
gfx.dispose();
}
gfx.drawImage(img, 0, 0, this);
}
class Action implements ActionListener {
public void actionPerformed(ActionEvent e) {
if(e.getSource() == red){
gfx.setPaint(Color.RED);
repaint();
} else if (e.getSource() == green){
gfx.setPaint(Color.GREEN);
repaint();
} else if (e.getSource() == blue) {
gfx.setPaint(Color.BLUE);
repaint();
} else if (e.getSource() == clear) {
gfx.clearRect(0, 0, drawFrame.getWidth(), drawFrame.getHeight());
repaint();
}
}
}
class MyListener extends MouseAdapter {
public void mousePressed(MouseEvent e) {
prevX = e.getX();
prevY = e.getY();
System.out.println("o ye");
}
public void mouseDragged(MouseEvent e) {
x = e.getX();
y = e.getY();
gfx.drawLine(prevX, prevY, x, y);
repaint();
prevX = x;
prevY = y;
}
}
}
You added the PaintGUI to frame but LayoutManager don't know the size and can't set desired size.
Either set the preferred size (or override getPreferredSize to return desired size)
or add to the PaintGUI instance some component(s) with preferred size (e.g. buttons)

Translucent JPopupMenu inside a Translucent Window - alternative?

I'm not sure if this is possible, but is there a way to safely allow popups to be translucent even when the parent container is also translucent?
If not, what would be wise alternative to use or extend instead of JPopupMenu?
Note: Translucent refers to a component not 'having a background', similar to the effect of setOpaque(false);. Thanks.
From a forum answer by user camickr in 2009:
I don't know if transparency painting has changed in 1.6.0_10. Prior
to that I believe transparency can only be achieved in lightweight
components (ie. Swing does all the painting). JFrame, JWindow and
JDialog are not lightweight because they use OS components.
In the case of a popup, it is lightweight when entirely contained
within its parent frame. But a lightweight popup can not be painted
outside the bounds of the frame so a JWindow (I believe) is used as
the popup, which can't be transparent.
SSCCE: Showing translucent JWindow over the top of translucent JFrame
import com.sun.awt.AWTUtilities;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class OpaqueWindowSSCCE {
private int countdown = 5;
public static void main(String[] args) {
new OpaqueWindowSSCCE();
}
public OpaqueWindowSSCCE() {
final JFrame frame = new JFrame("OpaqueWindowSSCCE");
final JWindow window = new JWindow();
new Timer(1000, new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
if(--countdown == 0){
frame.dispose();
window.dispose();
System.exit(0);
} else {
frame.repaint();
}
}
}).start();
frame.setContentPane(new JPanel() {
#Override
public void paintComponent(Graphics paramGraphics) {
super.paintComponent(paramGraphics);
Graphics2D g = (Graphics2D) paramGraphics.create();
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setColor(new Color(50, 50, 50));
g.fillRoundRect(0, 0, getWidth(), getHeight(), 10, 10);
g.setColor(new Color(180, 180, 180));
g.drawString("Closing in " + countdown + " seconds", 20, 25);
}
});
window.setContentPane(new JPanel() {
#Override
public void paintComponent(Graphics paramGraphics) {
super.paintComponent(paramGraphics);
Graphics2D g = (Graphics2D) paramGraphics.create();
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setColor(new Color(180, 180, 180));
g.fillRoundRect(0, 0, getWidth(), getHeight(), 10, 10);
}
});
frame.setUndecorated(true);
((JComponent) frame.getContentPane()).setOpaque(false);
((JComponent) window.getContentPane()).setOpaque(false);
AWTUtilities.setWindowOpaque(frame, false);
AWTUtilities.setWindowOpaque(window, false);
window.setAlwaysOnTop(true);
frame.setBounds(200,200,500,500);
window.setBounds(600,600,200,200);
frame.setVisible(true);
window.setVisible(true);
}
}
Try this code part, I had used JWindow though
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class WindowExample
{
private JWindow window;
private JLabel updateLabel;
private int count = 5;
private Timer timer;
private int x;
private int y;
private ActionListener timerAction = new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
updateLabel.setText("Closing Window in " + count + " seconds...");
count--;
if (count == 0)
{
timer.stop();
window.setVisible(false);
window.dispose();
}
}
};
private void createAndDisplayGUI()
{
final JFrame frame = new JFrame("Window Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setUndecorated(true);
frame.setOpacity(0.5f);
frame.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent me)
{
x = me.getX();
y = me.getY();
window = new JWindow();
JPanel contentPane = new JPanel();
JLabel positionLabel = new JLabel(
"X : " + me.getX() + " Y : " + me.getY());
updateLabel = new JLabel("TImer");
contentPane.setLayout(new BorderLayout(5, 5));
contentPane.add(updateLabel, BorderLayout.CENTER);
contentPane.add(positionLabel, BorderLayout.PAGE_END);
window.setContentPane(contentPane);
window.setOpacity(0.5f);
window.setSize(200, 100);
window.setLocation(x + window.getWidth(), y + window.getHeight());
window.setVisible(true);
count = 5;
timer = new Timer(1000, timerAction);
timer.start();
}
});
frame.setSize(500, 500);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new WindowExample().createAndDisplayGUI();
}
});
}
}
And here is the output :
WARNING I AM GETTING
C:\Mine\JAVA\J2SE>javac -d classes src\OpaqueWindowSSCCE.java
src\OpaqueWindowSSCCE.java:1: warning: AWTUtilities is internal proprietary API and may be removed i
n a future release
import com.sun.awt.AWTUtilities;
^
src\OpaqueWindowSSCCE.java:68: warning: AWTUtilities is internal proprietary API and may be removed
in a future release
AWTUtilities.setWindowOpaque(frame, false);
^
src\OpaqueWindowSSCCE.java:69: warning: AWTUtilities is internal proprietary API and may be removed
in a future release
AWTUtilities.setWindowOpaque(window, false);
^
3 warnings

Categories