Repaint() not working with other JPanel? - swing

I am trying to make a program with 2 panels, and when the first panel is clicked it displays another color, and in the second panel the word changes to the color that is currently displayed
The problem is repaint() doesn't call paintComponent() again
class Fun extends JPanel{
public int i = 0;
A a = new A();
B b = new B();
public Fun(){
setLayout(new GridLayout(2, 2, 10, 10));
add(a);
add(b);
}
public void paintComponent(Graphics g){
setBackground(Color.WHITE);
super.paintComponent(g);
}
class A extends JPanel implements MouseListener{
public Color c = Color.BLUE;
CardLayout cl = new CardLayout();
JPanel c1 = new JPanel();
JPanel c2 = new JPanel();
JPanel c3 = new JPanel();
Color[] colors = {Color.BLUE, Color.GREEN, Color.RED};
public A(){
addMouseListener(this);
setLayout(cl);
c1.setBackground(Color.BLUE);
c2.setBackground(Color.GREEN);
c3.setBackground(Color.RED);
add(c1);
add(c2);
add(c3);
}
public void mouseClicked(MouseEvent e){
cl.next(this);
if (i==2){
i = 0;
}
else{
i++;
}
c = colors[i];
new B().go();
}
public void mouseEntered(MouseEvent e){}
public void mouseExited(MouseEvent e){}
public void mousePressed(MouseEvent e){}
public void mouseReleased(MouseEvent e){}
}
class B extends JPanel{
JLabel l = new JLabel("Play Baby!");
public B(){
add(l);
}
public void paintComponent(Graphics g){
System.out.println("repainted");
A apple = new A();
g.setColor(apple.colors[i]);
super.paintComponent(g);
}
public void go(){
repaint();
}
}
}

In your mouseClicked, you are calling go() on a new B. But the new B is never added to another component. You probably want to say, b.repaint(), using the B that was defined as a member variable.

Related

Libgdx Actor Scened2d Draw method does not draw nothing

I've started a very small Libgdx project based in Scene2d. I downloaed last version of LGDX. I have tried to find some imformation but nothing clear.
The problem is that I only get a Black Screen of the Death. Nothing happens
I have followed the code, with logs and I'm sure I arrive to Draw method in my Actor with no results:
Thank you in advance.
public class ActorBall extends Actor implements Disposable {
private Texture ballTexture;
private TextureRegion ballTextureRegion;
public ActorBall() {
bolaTexture = new Texture("redball.png");
ballTextureRegion = new TextureRegion(ballTexture, 300,300);
setSize(300,300);
}
#Override
public void dispose(){
bolaTexture.dispose();
}
#Override
public void draw(Batch batch, float parentAlpha) {
Color col = getColor();
batch.setColor(col.r,col.g, col.b,col.a * parentAlpha);
Gdx.app.log("App","where are you");
batch.draw(ballTextureRegion,getX(),getY(),getOriginX(),
getOriginY(),getWidth(), getHeight(), getScaleX(), getScaleY(),getRotation());
}
#Override
public void act(float delta) {
super.act(delta);
}
}
My screen class extended from Screen:
public class scene extends scenebase {
private final OrthographicCamera camera;
private MyGdxGame game ;
private Stage stage; // los Stages son inputprocessors
private ActorBall ball;
public scene(MyGdxGame game) {
super(game);
this.game = game;
camera = new OrthographicCamera();
camera.setToOrtho(false, 800, 480);
stage = new Stage(new ScreenViewport());
ball = new ActorBall();
ball.setPosition(0,0);
stage.addActor(ball);
}
#Override
public void render(float delta) {
// super.render(delta);
Gdx.gl.glClearColor(0,0,0.0f,1);
Gdx.gl.glClear (GL20.GL_COLOR_BUFFER_BIT);
camera.update();
// game.batch.setProjectionMatrix(camera.combined);
stage.draw();
stage.act();
}
#Override
public void resize(int width, int height) {
stage.getViewport().update (width,height);
}
}
And last my main game:
public class MyGdxGame extends Game {
private AssetManager manager;
private scene screenscene;
#Override
public void create() {
manager = new AssetManager();
manager.load("redball.png", Texture.class);
manager.finishLoading();
// Enter the loading screen to load the assets.
screenscene = new scene(this);
setScreen(screenscene);
}
#Override
public void render () {
super.render(); // This is very important!!!!!!!!
Gdx.gl.glClearColor(0, 0, 0.1f, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
}
public AssetManager getManager() {
return this.manager;
}
}
#Override
public void render () {
super.render(); // This is very important!!!!!!!!
Gdx.gl.glClearColor(0, 0, 0.1f, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
}
What this does is first render everything and then clear the screen. You need to first clear it and then render.

Swing repaint() not working

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);
}*/
}

Label connection with textField in java

I wanted to take some value in currently available in label and add(calculate) with number
and display on the text field but there is errors
private void ch13ActionPerformed(java.awt.event.ActionEvent evt)
r1=Integer.parseInt(tLabel.getText()); //r2 and r1 are integers
// error .. It says "Void type not allowed here"
r2 = Integer.parseInt(tLabel.setText(String.valueOf("3")));
result=r1+r2;
creaditTxt.setText(result+"");
}
Then how do i solve this problem?
setText() returns void. So by doing this
r2 = Integer.parseInt(tLabel.setText(String.valueOf("3")));
you're saying that r2 = void. That's not possible.
You may want to have 2 textfields instead and a label to display the result
public class AddFrame extends JFrame {
private JLabel result = new JLabel();
private JTextField number1 = new JTextField(10);
private JTextField number2 = new JTextField(10);
private JButton addBut = new JButton("Add");
public AddFrame(){
setLayout(new GridLayout(4, 1));
add(result);
add(number1);
add(number2);
add(addBut);
addBut.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
int num1 = Integer.parseInt(number1.getText());
int num2 = Integer.parseInt(number2.gettext());
int total = num1 + num2;
result.setText(String.valueOf(total));
}
});
}
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable(){
public void run(){
AddFrame frame = new AddFrame();
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}

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();
}
}
}
}