Swing repaint() not working - swing

class ballbouncepanel extends JPanel
{
public void start()
{
Timer timer;
final int FREQ = 45;
timer = new Timer(FREQ, new ActionListener()
{
public void actionPerformed(ActionEvent evt)
{
repaint();
}
});
timer.start();
}
Rect rect = new Rect();
public Dimension getPreferredSize()
{
return new Dimension(250,200);
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
rect.draw(g);
rect.move(g);
rect.erase(g);
}
}
class Rect
{
public int xLocation = 0;
public int yLocation = 0;
public int xVelocity = 10;
public int yVelocity = 10;
public void draw(Graphics g)
{
g.setColor(Color.cyan);
g.fillRect(xLocation, yLocation, 20, 20);
}
public void move(Graphics g)
{
xLocation += xVelocity;
yLocation += yVelocity;
}
public void erase(Graphics g)
{
g.setColor(Color.white);
g.fillRect(xLocation, yLocation, 20, 20);
}
}
The new error is that now my repaint method isn't working.
Above is my code for the frame that I got that I want to paint on, I understand paint using a applet or JApplet, but I am trying to do what I did in a applet on Swing, and now im running into problems, I have looked up many tutorials on how to implement graphics in, but most of them is just running a main graphics, I need mine to be in this specific frame(BB). If anyone could help me understand or point me to a beginners tutorial for it, it would be appreciated.

I think you are just forgetting to call the start() method of your ballbouncepanel. Also a note: you're move() method does no painting, so take out the Graphics argument and just call it in the timer
Also not sure what the erase method is supposed to do, but I'm thinking you want to change color every tick of the timer. In that case, just keep a color variable, and just change that variable. You can see the example below
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class bounceballpanel extends JPanel {
public void start() {
Timer timer;
final int FREQ = 45;
timer = new Timer(FREQ, new ActionListener() {
public void actionPerformed(ActionEvent evt) {
rect.move();
rect.changeColor();
repaint();
}
});
timer.start();
}
Rect rect = new Rect();
public Dimension getPreferredSize() {
return new Dimension(250, 200);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
rect.draw(g);
//rect.erase(g);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
JFrame frame = new JFrame();
bounceballpanel panel = new bounceballpanel();
panel.start();
frame.add(panel);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
class Rect {
public int xLocation = 0;
public int yLocation = 0;
public int xVelocity = 10;
public int yVelocity = 10;
Color color = Color.cyan;
public void draw(Graphics g) {
g.setColor(color);
g.fillRect(xLocation, yLocation, 20, 20);
}
public void move() {
xLocation += xVelocity;
yLocation += yVelocity;
}
public void changeColor() {
if (color == Color.cyan) {
color = Color.white;
} else {
color = Color.cyan;
}
}
/*
public void erase(Graphics g) {
g.setColor(Color.white);
g.fillRect(xLocation, yLocation, 20, 20);
}*/
}

Related

New to libgdx; glitchy graphic when drawing scene with scene2D

I'm trying to display a simple text for a menu UI using scene2D, but for some reason nothing is being displayed here. The screen displays pure black.
public class ScreenMenu implements Screen {
MyGame myGame;
SpriteBatch batch;
Stage stage;
Label labelNewGame, labelContinue, labelCredits;
public ScreenMenu(MyGame myGame) {
this.myGame = myGame;
}
#Override
public void show() {
init();
BitmapFont font = initFont();
initLabels(font);
initStage();
}
private void init() {
batch = new SpriteBatch();
}
private BitmapFont initFont() {
return new FontLoader().getMichroma();
}
private void initLabels(BitmapFont font) {
Label.LabelStyle labelStyle = new Label.LabelStyle(font, Color.WHITE);
labelNewGame = new Label("New Game", labelStyle);
labelContinue = new Label("Continue", labelStyle);
labelCredits = new Label("Credits", labelStyle);
}
private void initStage() {
stage = new Stage(new ScreenViewport());
Gdx.input.setInputProcessor(stage);
stage.addActor(labelNewGame);
}
#Override
public void render(float delta) {
GlHelper.clearScreen();
stage.act(delta);
stage.draw();
}
#Override
public void resize(int width, int height) {
stage.getViewport().update(width, height, true);
}
#Override
public void pause() {
}
#Override
public void resume() {
}
#Override
public void hide() {
dispose();
}
#Override
public void dispose() {
myGame.dispose();
batch.dispose();
stage.dispose();
}
}
The following class contains the clearScreen function. If I don't run it, the entire screen becomes super glitchy, but I can see the New Game text.
public class GlHelper {
public static void clearScreen() {
Gdx.gl.glClearColor(0, 0, 0, 0);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
}
public static void clearScreen(float red, float green, float blue, float alpha) {
Gdx.gl.glClearColor(red, green, blue, alpha);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
}
}
Do you use?
setBounds(x, y, w, h);
before to add stage for example:
labelNewGame.setBounds(0, 0, 100, 100);
maybe he can help you.
I feel stupid now. In the FontLoader implementation I set the FreeTypeFontParameter color to Color.BLACK. Apparently it overrides the Color.WHITE argument from LabelStyle.

input listener in second stage not working in libgdx

I want to have two stages on the same screen, but the problem is, the input listener of the second stage(static_stage) is not responding but no problem in drawing its actors.The first stage(stage) works and responds fine. Here is the code,and please tell me where am i going wrong?
package com.amal.arrange;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.InputListener;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.ui.Label.LabelStyle;
public class gamescreen implements Screen {
final Mygame game;
OrthographicCamera camera;
Texture background;
Sprite sprite_back;
Stage stage;
Stage static_stage;
Label shuffle;
LabelStyle shuffle_style;
BitmapFont shuffle_font;
public gamescreen(final Mygame Game) {
game = Game;
camera = new OrthographicCamera();
camera.setToOrtho(false, Gdx.graphics.getWidth(),
Gdx.graphics.getHeight());
stage=new Stage();
static_stage=new Stage(stage.getViewport(),stage.getSpriteBatch());
static_stage.clear();
stage.clear();
Gdx.input.setInputProcessor(stage);
Gdx.input.setInputProcessor(static_stage);
Tile_manager.load();
}
#Override
public void render(float delta) {
Gdx.gl.glClearColor(0.85f, 0.85f, 0.85f, 0.85f);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
camera.update();
game.batch.setProjectionMatrix(camera.combined);
game.batch.begin();
game.batch.draw(sprite_back, 0, 0);
game.batch.end();
stage.draw();
static_stage.draw();
}
#Override
public void resize(int width, int height) {
static_stage.getViewport().update(width, height, true);
stage.getViewport().update(width, height, true);
}
#Override
public void show() {
//System.out.println("in show");
background=new Texture(Gdx.files.internal("background/background.png"));
sprite_back=new Sprite(background);
sprite_back.setBounds(0, 0, background.getWidth(), background.getHeight());
Tile_manager.generate_tile();
Tile_manager.add_listener();
stage=Tile_manager.get_tile_stage();
shuffle_font=new BitmapFont(Gdx.files.internal("fonts/shuffle.fnt"), false);
shuffle_style=new LabelStyle(shuffle_font, null);
shuffle=new Label("SHUFFLE", shuffle_style);
shuffle.setPosition(190, 1330);
shuffle.addListener(new InputListener(){
#Override
public boolean touchDown(InputEvent event, float x, float y,
int pointer, int button) {
System.out.println("in down");
return true;
}
#Override
public void touchUp(InputEvent event, float x, float y,
int pointer, int button) {
System.out.println("in up");
}
});
static_stage.addActor(shuffle);
}
#Override
public void hide() {
}
#Override
public void pause() {
}
#Override
public void resume() {
}
#Override
public void dispose() {
background.dispose();
stage.dispose();
}
}
I am facing the same problem. But to begin, you overright the input listener,
you have to set an inputmultiplexer to manage both the input
InputMultiplexer inputMultiplexer = new InputMultiplexer();
inputMultiplexer.addProcessor(stage);
inputMultiplexer.addProcessor(static_stage);
Gdx.input.setInputProcessor(inputMultiplexer);
But not sure this is enought...

Libgdx BitmapFont not displaying

I've looked at other Stackoverflow questions and done what the answers have told me, but I can't seem to get my class to display any text.
Here's my code where all the text is being displayed:
package com.frinkly.jumpcat;
import com.badlogic.gdx.math.Matrix4;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.OrthographicCamera;
public class WorldRenderer {
private static final float CAMERA_WIDTH = 12f;
private static final float CAMERA_HEIGHT = 20f;
private OrthographicCamera cam;
private SpriteBatch spriteBatch;
private int width;
private int height;
private float ppuX;
private float ppuY;
private BitmapFont font;
private World world;
private Cat cat;
ShapeRenderer debugRenderer = new ShapeRenderer();
public WorldRenderer(World newWorld) {
this.world = newWorld;
this.cat = world.getCat();
this.cam = new OrthographicCamera(CAMERA_WIDTH, CAMERA_HEIGHT);
this.cam.position.set(CAMERA_WIDTH / 2f, CAMERA_HEIGHT / 2f, 0);
spriteBatch = new SpriteBatch();
font = new BitmapFont(Gdx.files.internal("font/font.fnt"), false);
font.setColor(Color.BLACK);
this.cam.update();
spriteBatch.setProjectionMatrix(new Matrix4().setToOrtho2D(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()));
}
public void setSize(int newWidth, int newHeight) {
width = newWidth;
height = newHeight;
ppuX = (float) width / CAMERA_WIDTH;
ppuY = (float) height / CAMERA_HEIGHT;
}
public void render() {
cam.update();
spriteBatch.begin();
debugDraw();
drawPoints();
spriteBatch.end();
}
private void drawPoints() {
font.setColor(1.0f, 1.0f, 1.0f, 1.0f);
font.setScale(1, height/width);
font.draw(spriteBatch, Integer.toString(cat.getPoints()), 0.5f, height/width*0.5f);
}
private void debugDraw() {
debugRenderer.setProjectionMatrix(cam.combined);
debugRenderer.begin(ShapeType.Filled);
for(Block block : world.getBlocks()) {
Rectangle rect1 = block.getBounds1();
Rectangle rect2 = block.getBounds2();
float x1 = block.getPosition().x;//+block.getPosition().x
float y1 = block.getPosition().y;//+block.getPosition().y
debugRenderer.setColor(new Color(1, 0, 0, 1));
debugRenderer.rect(x1, y1, rect1.width, rect1.height);
debugRenderer.rect(x1, y1 + rect1.height + block.getSPACE(), rect2.width, rect2.height);
}
Rectangle rect = cat.getBounds();
float x1 = cat.getPosition().x + rect.x;
float y1 = cat.getPosition().y + rect.y;
debugRenderer.setColor(new Color(0, 1, 0, 1));
debugRenderer.rect(x1, y1, rect.width, rect.height);
debugRenderer.end();
}
private void drawBlocks() {
}
private void drawCat() {
}
}
Here's the GameScreen that calls the renderer to display the text:
package com.frinkly.jumpcat;
import com.badlogic.gdx.Application.ApplicationType;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.InputProcessor;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.Screen;
public class GameScreen implements Screen, InputProcessor{
private World world;
private WorldRenderer renderer;
private CatController catController;
private BlockController blockController;
private int screenWidth;
private int screenHeight;
#Override
public void render(float delta) {
Gdx.gl.glClearColor(1f, 1f, 1f, 1f);
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
blockController.update(delta);
catController.update(delta);
renderer.render();
}
#Override
public void resize(int width, int height) {
screenWidth = width;
screenHeight = height;
renderer.setSize(width, height);
}
#Override
public void show() {
loadAssets();
world = new World();
renderer = new WorldRenderer(world);
catController = new CatController(world);
blockController = new BlockController(world);
blockController.start();
Gdx.input.setInputProcessor(this);
}
private void loadAssets() {
}
#Override
public void hide() {
Gdx.input.setInputProcessor(null);
}
#Override
public void pause() {
Gdx.input.setInputProcessor(null);
}
#Override
public void resume() {
Gdx.input.setInputProcessor(this);
}
#Override
public void dispose() {
}
#Override
public boolean keyDown(int keycode) {
if(keycode == Keys.SPACE) {
catController.jumpPressed();
}
return true;
}
#Override
public boolean keyUp(int keycode) {
return false;
}
#Override
public boolean keyTyped(char character) {
return false;
}
#Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
if(!Gdx.app.getType().equals(ApplicationType.Android)) {
return false;
}
catController.jumpPressed();
return true;
}
#Override
public boolean touchUp(int screenX, int screenY, int pointer, int button) {
if(!Gdx.app.getType().equals(ApplicationType.Android)) {
return false;
}
return true;
}
#Override
public boolean touchDragged(int screenX, int screenY, int pointer) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean mouseMoved(int screenX, int screenY) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean scrolled(int amount) {
// TODO Auto-generated method stub
return false;
}
}
My fonts are in the right folder, and I used Hiero to generate the files. I used 150 size and it generated font1png-font5.png, which I've also put in my font folder.
The error should be in your render() method:
cam.update();
spriteBatch.begin();
debugDraw();
drawPoints();
spriteBatch.end();
Inside debugDraw() you begin() a ShapeRenderer. So 2 objects try to draw at the same time. Do the debugDraw() first and begin() your SpriteBatch after that:
cam.update();
debugDraw();
spriteBatch.begin();
drawPoints();
spriteBatch.end();
Hope it helps

Adding JTextArea to JFrame

If I have 1 main class and 2 subclasses
subclass 1: public class JPanel1 extends JPanel {....properly initialized}
subclass 2: public class JTextArea1 extends JTextArea {... properly initialized}
Why can I do jframe1.add(new JPanel1()) but not jframe1.add(new JTextArea1())? for a properly initialized JFrame jframe1 = new JFrame();?
My goal is to output data into both the jpanel and the jtextarea
Here on my side, the issue you raising, is working fine. Do let me know, if you think, this is not what you mean :-)
import java.awt.*;
import javax.swing.*;
public class SwingExample
{
private CustomPanel customPanel;
private CustomTextArea customTextArea;
private void displayGUI()
{
JFrame frame = new JFrame("Swing Example");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setLayout(new BorderLayout(5, 5));
contentPane.setBorder(
BorderFactory.createLineBorder(
Color.DARK_GRAY, 5));
customPanel = new CustomPanel();
customTextArea = new CustomTextArea();
contentPane.add(customPanel, BorderLayout.CENTER);
contentPane.add(customTextArea, BorderLayout.LINE_START);
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args)
{
Runnable runnable = new Runnable()
{
#Override
public void run()
{
new SwingExample().displayGUI();
}
};
EventQueue.invokeLater(runnable);
}
}
class CustomPanel extends JPanel
{
private static final int GAP = 5;
public CustomPanel()
{
setOpaque(true);
setBackground(Color.WHITE);
setBorder(BorderFactory.createLineBorder(
Color.BLUE, GAP, true));
}
#Override
public Dimension getPreferredSize()
{
return (new Dimension(300, 300));
}
}
class CustomTextArea extends JTextArea
{
private static final int GAP = 5;
public CustomTextArea()
{
setBorder(BorderFactory.createLineBorder(
Color.RED, GAP, true));
}
#Override
public Dimension getPreferredSize()
{
return (new Dimension(100, 30));
}
}
OUTPUT :

I'm making a game in Java and whenever I try to bring up my in game menu the program minimizes?

The menu is displayed on game startup and works fine, but once in game you can hit escape to bring up the menu again and this will cause the program to minimize. After I unminimize the game I can hit escape again and the menu screen will appear as intended. The return button also works as intended. What is going on here?
EDIT
Here is my SSCCE:
You will just need to add the imports and unimplemented methods for BullsEyePanel. I hope this helps!
public class Board {
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
public static void createAndShowGUI() {
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
int B_WIDTH = (int) dim.getWidth();
int B_HEIGHT = (int) dim.getHeight();
JFrame f = new JFrame("Children of The Ape");
f.setDefaultCloseOperation(f.EXIT_ON_CLOSE);
f.setUndecorated(true);
f.pack();
f.setBackground(Color.BLACK);
f.setVisible(true);
f.setResizable(false);
// Get graphics configuration...
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gd = ge.getDefaultScreenDevice();
// Change to full screen
gd.setFullScreenWindow(f);
if (gd.isDisplayChangeSupported()) {
gd.setDisplayMode(new DisplayMode(B_WIDTH, B_HEIGHT, 32, DisplayMode.REFRESH_RATE_UNKNOWN));
}
MenuPanel menu = new MenuPanel(f);
f.getContentPane().add(menu);
f.validate();
}
}
class BullsEyePanel extends JPanel implements MouseInputListener, ActionListener {
JFrame frame;
public BullsEyePanel(JFrame f) {
frame = f;
addKeyListener(new TAdapter());
setFocusable(true);
setVisible(true);
repaint();
}
private void openMenu() {
frame.getContentPane().add(new MenuPanel(this));
setVisible(false);
}
private class TAdapter extends KeyAdapter {
public void keyPressed(KeyEvent arg0) {
if (arg0.getKeyCode() == 27) {
openMenu();
}
}
}
}
class MenuPanel extends JPanel {
JButton btnExit;
JButton btnNewGame;
JFrame f;
BullsEyePanel panel;
MenuPanel(JFrame frame) { //this menu constructor is only called on program startup
f = frame;
setBackground(Color.black);
setFocusable(true);
btnNewGame = new JButton("New Game");
btnExit = new JButton("Exit");
btnNewGame.addActionListener(new newGameListener());
btnExit.addActionListener(new exitListener());
add(btnNewGame);
add(btnExit);
setVisible(true);
}
MenuPanel(BullsEyePanel bullsEyePanel) { //this menu constructor is called when ESC is typed
f = bullsEyePanel.frame;
setBackground(Color.black);
setFocusable(true);
btnNewGame = new JButton("New Game");
btnExit = new JButton("Exit");
btnNewGame.addActionListener(new newGameListener());
btnExit.addActionListener(new exitListener());
add(btnNewGame);
add(btnExit);
setVisible(true);
}
public class exitListener implements ActionListener {
public void actionPerformed(ActionEvent arg0) {
System.exit(0);
}
}
public class newGameListener implements ActionListener {
public void actionPerformed(ActionEvent arg0) {
setVisible(false);
f.getContentPane().add(new BullsEyePanel(f), BorderLayout.CENTER);
}
}
}
Instead of variant constructors, let the menu panel undertake its removal and restoration, as suggested below. See also this related example.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Board {
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Board().createAndShowGUI();
}
});
}
public void createAndShowGUI() {
JFrame f = new JFrame("Children of The Board");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setBackground(Color.BLACK);
MenuPanel menu = new MenuPanel(f);
f.add(menu, BorderLayout.NORTH);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}
class MenuPanel extends JPanel {
private JButton btnExit = new JButton("Exit");
private JButton btnNewGame = new JButton("New Game");
private BullsEyePanel gamePanel;
private JFrame parent;
MenuPanel(JFrame parent) {
this.gamePanel = new BullsEyePanel(this);
this.parent = parent;
this.setBackground(Color.black);
this.setFocusable(true);
btnNewGame.addActionListener(new newGameListener());
btnExit.addActionListener(new exitListener());
this.add(btnNewGame);
this.add(btnExit);
this.setVisible(true);
}
public void restore() {
parent.remove(gamePanel);
parent.add(this, BorderLayout.NORTH);
parent.pack();
parent.setLocationRelativeTo(null);
}
private class exitListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent arg0) {
System.exit(0);
}
}
private class newGameListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent arg0) {
parent.remove(MenuPanel.this);
parent.add(gamePanel, BorderLayout.CENTER);
parent.pack();
parent.setLocationRelativeTo(null);
gamePanel.requestFocus();
}
}
}
class BullsEyePanel extends JPanel {
private MenuPanel menuPanel;
public BullsEyePanel(MenuPanel menu) {
this.menuPanel = menu;
this.setFocusable(true);
this.addKeyListener(new TAdapter());
this.setPreferredSize(new Dimension(320, 240)); // placeholder
this.setVisible(true);
}
private class TAdapter extends KeyAdapter {
#Override
public void keyPressed(KeyEvent code) {
if (code.getKeyCode() == KeyEvent.VK_ESCAPE) {
menuPanel.restore();
}
}
}
}