Change at runtime the background of a table added to a stage in the constructor - libgdx

I need at runtime to reload a background of a table added to a stage (the user can change it at runtime).
I'm doing this but the background will change only when I switch back from another Screen or reopen my game.
MyGame.java:
String backgroundFileName = "background1.jpg";
public class MyGame extends Game {
public void create() {
...
this.setScreen(new MainMenuScreen(this));
}
public void handleChoosenBackground(String _backgroundFileName) {
backgroundFileName = _backgroundFileName;
if(getScreen() instanceof MainMenuScreen) {
((MainMenuScreen)getScreen()).reloadBackground();
}
}
}
MainMenuScreen.java:
public class MainMenuScreen implements Screen, InputProcessor {
Stage stage;
Table table;
TextureRegionDrawable textureRegionDrawableBackground;
public MainMenuScreen(final MyGame game) {
...
stage = new Stage(new FillViewport(Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), new OrthographicCamera(Gdx.graphics.getWidth(), Gdx.graphics.getHeight())));
textureRegionDrawableBackground = new TextureRegionDrawable(new TextureRegion(new Texture(game.backgroundFileName)));
table = new Table();
table.setFillParent(true);
table.setBackground(textureRegionDrawableBackground);
stage.addActor(table);
}
public void reloadBackground() {
textureRegionDrawableBackground = new TextureRegionDrawable(new TextureRegion(new Texture(game.backgroundFileName)));
table.setBackground(textureRegionDrawableBackground);
// log prints here, so this method is reached, with the correct new backgroundFileName
}
}
I also tried this on MyGame class but it seems that does nothing because MainMenuScreen is already the active screen:
setScreen(new MainMenuScreen(this));
If, instead, I set textureRegionDrawableBackground to null, it works showing a white background:
public void reloadBackground() {
textureRegionDrawableBackground = null; // <<<<<
table.setBackground(textureRegionDrawableBackground);
}
Thanks!

I had a similar problem when I didn't run table.pack() once I finished putting all the things into the table - apparently the background size doesn't automatically resize to the table size, and you need to tell it to do so.
Hope that solves your problem :)

Related

Some Actions do not work

I want to make a text appear in the center of the screen, indicating
the current level. It should appear gradually and after a while disappear gradually. I'm using scene2d with stages, actors.. so i would use Actions.
This is what i have now:
public class TextActor extends Actor {
private BitmapFont font;
private CharSequence charSequence;
public TextActor(CharSequence charSequence) {
font = new BitmapFont(Gdx.files.internal("fonts/white_standard_font.fnt"));
this.charSequence = charSequence;
}
#Override
public void act(float delta) {
super.act(delta);
}
#Override
public void draw(Batch batch, float delta) {
super.draw(batch, delta);
font.draw(batch, charSequence, getX(), getY());
}
}
In the class that creates the TextActor..
textActor.addAction(Actions.sequence(Actions.fadeIn(1f), Actions.delay(1f), Actions.fadeOut(1f), new Action() {
#Override
public boolean act(float delta) {
textActor.remove();
transitionInProgress = false;
gameState = GameState.RUNNING;
Gdx.input.setInputProcessor(stage);
return true;
}
}));
gameTable.addActor(textActor);
fadeIn, fadeOut, alpha.. don't work. I tried with "moveBy" and it works, so it seems a problem concerning the appearance of the Actor. There is something that escapes me.
The fade actions modify the alpha value of the Actor's color (getColor().a). You're drawing the font directly without applying the color associated with the actor.
Take a look at how Label.draw is implemented for a better understanding. In the meantime, just try adding this above your font.draw(...) call:
font.setColor(getColor())
Or, if you don't want to modify the entire color, just the alpha, try this:
font.getColor().a = getColor().a;
UPDATE:
Also note that you should apply the parentAlpha (second parameter of draw - labelled as delta in your example) to the final alpha:
font.getColor().a = getColor().a * parentAlpha
This allows your actor to fade if you change the alpha of the stage or any parents.

JPanel.getGraphics equivalent in JavaFx to use with OpenCV

The title seems a little bit confusing, but I'll explain everything.
I'm developing a project where I show the image captured by a webcam in a JPanel, Java Swing. Now I have to integrate this with JavaFx.
I have a controller where I have the method startRecording, that would initialize the cameraThread and tell the class Camera to startRecording, inside Camera class a have a method DrawFrame(BufferedImage, JPanel panel) where I call the function drawImage from OpenCV to draw in the Panel:
Controller:
public void startRecording(){
cameraInstance.setCameraRGBPanel(windowsInstance.getCameraRGBPanel());
cameraInstance.setCameraHSVPanel(windowsInstance.getCameraHSVPanel());
cameraInstance.setCameraThresholdPanel(windowsInstance.getCameraThresholdPanel());
cameraInstance.setRecord(true);
cameraThread = new Thread(cameraInstance);
cameraThread.start();
}
Class camera:
private void drawFrame(BufferedImage buff, JPanel pane){
pane.getGraphics().drawImage(buff, 0, 0, null);
}
To start with, JavaFX has no JPanel and the Pane (an option) has no getGraphics, I've tried to use a SwingNode, add the JPanel and then do everything as usual, but the image simply won't be shown.
The following code was a test, that's why it seems to be so 'bad'.
public void start(Stage stage) throws Exception {
stage.setTitle("Tela Teste");
pCamera = new Pane();
SwingNode swing = new SwingNode();
pCamera.getChildren().add(swing);
createAndSetSeingContent(swing);
Group root = new Group();
root.getChildren().add(pCamera);
stage.setScene(new Scene(root , 500, 500));
stage.setResizable(true);
stage.show();
}
private void createAndSetSeingContent(SwingNode swing) {
ControllerCamera control = new ControllerCamera();
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
JPanel panel = new JPanel();
JLabel label = new JLabel("Abc");
//panel.add(label);
swing.setContent(panel);
Button teste = new Button("A");
pCamera.getChildren().add(teste);
teste.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
control.startRecording(panel);
System.out.println("abc");
}
});
}
I changed to method startRecording to something like:
public void startRecording(JPanel panel){
cameraInstance.setCameraRGBPanel(panel);
cameraInstance.setRecord(true);
cameraThread = new Thread(cameraInstance);
cameraThread.start();
}
Still nothing appears in the panel, but if I add a label or button, then it appear and works as intended to. The "abc" is always shown in the console.
I think that's all the code related to the problem. Something else I want to say is that yesterday was the first day I was dealing with FX, let's say the project is divided, the other guy is also working on the problem, but we haven't gotten anywhere so far, that's why I decided to ask you here.
Edit 1: everything was working perfectly before all this situation (everything works with Swing, but not in FX).
The simplest way to display an Image in JavaFX is with an ImageView. You can create a single ImageView and update its image by calling setImage(...), passing in a javafx.scene.image.Image. I don't know the camera API you are working with: you might be able to generate a JavaFX image directly, in which case your draw frame method looks as simple as:
private void drawFrame(Image image, ImageView imageView) {
imageView.setImage(image);
}
If you can only generate BufferedImages, you can do
private void drawFrame(BufferedImage buff, ImageView imageView) {
imageView.setImage(SwingFXUtils.toFXImage(buff, null));
}
In either case, you can just create the ImageView, put it in a Pane subclass of some kind, put the Pane in a scene and display it in the Stage:
public void start(Stage stage) throws Exception {
stage.setTitle("Tela Teste");
pCamera = new Pane();
ImageView imageView = new ImageView();
pCamera.getChildren().add(imageView);
Group root = new Group();
root.getChildren().add(pCamera);
stage.setScene(new Scene(root , 500, 500));
stage.setResizable(true);
stage.show();
}
Then just pass the imageView to your drawFrame method as needed.

Libgdx ScrollPane adding space at the top

I'm creating a store for my game and I'm having issues with the libgdx ScrollPane. It seems to be moving the table within it down by 155px. The effect it's having is that the table appears roughly 155px down from the top, and the last button is off the screen no matter how far down I scroll.
Here is the window when the "Store" first appears.
As you can see the top of the table is quite a bit below the top of the window. Code below, but the table only has 10px of padding.
Here is the window when I've scrolled down as far as I could go - sorry, the scroll pars disappeared before I could grab the screenshot.
You can see that the "Main Menu" button is about half way off the screen.
Here is the code that lays out the "Store".
table = new Table();
table.setFillParent(true);
table.defaults().expandX().fill().space(5f);
table.pad(10f);
// characters
table.add(new Label("Characters: ", skin, "default")).left().colspan(2);
table.row();
ButtonGroup characterGroup = new ButtonGroup();
characterGroup.setMaxCheckCount(1);
Button boyButton = createImageTextButton("Plain Boy", boyTexture);
Button catButton = createImageTextButton("Cat Girl", catTexture);
Button hornButton = createImageTextButton("Horn Girl", hornTexture);
Button pinkButton = createImageTextButton("Pink Girl", pinkTexture);
Button queenButton = createImageTextButton("Queen", queenTexture);
float minHeight = 130f; // only used to force scrolling.
table.add(boyButton).minHeight(minHeight);
table.add(catButton).minHeight(minHeight).row();
table.add(hornButton).minHeight(minHeight);
table.add(pinkButton).minHeight(minHeight).row();
table.add(queenButton).minHeight(minHeight).colspan(2);
table.row();
characterGroup.add(boyButton, catButton, hornButton, pinkButton, queenButton);
characterGroup.setChecked("Plain Boy");
// drills
ButtonGroup drillGroup = new ButtonGroup();
Button flappyButton = createImageTextButton("Flappy", null);
Button tappyButton = createImageTextButton("Tappy", null);
Button tiltyButton = createImageTextButton("Tilty", null);
table.add(new Label("Drills:", skin, "default")).left().padTop(20).colspan(2);
table.row();
table.add(flappyButton).minHeight(minHeight);
table.add(tappyButton).minHeight(minHeight).row();
table.add(tiltyButton).minHeight(minHeight);
drillGroup.add(flappyButton, tappyButton, tiltyButton);
drillGroup.setChecked("Flappy");
// main menu button
table.row();
Button mainMenuButton = createImageTextButton("Main Menu", null);
table.add(mainMenuButton).minHeight(minHeight).padTop(40).padBottom(10f).colspan(2);
ScrollPane scrollPane = new ScrollPane(table, skin);
scrollPane.setBounds(0, 0, stage.getWidth(), stage.getHeight());
addActor(scrollPane);
I debugged the desktop version and saw that the table's y position was set to -155 before I scroll, and set to 0 after I scroll to the bottom. However, even when it's set to 0, the last button is always partly off the screen.
As requested here is the code where I create the viewport and camera:
package com.example;
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.utils.viewport.ExtendViewport;
import com.badlogic.gdx.utils.viewport.Viewport;
import com.example.stages.GameStage;
public class MainGame extends ApplicationAdapter {
public static final int MIN_WIDTH = 480;
public static final int MIN_HEIGHT = 800;
public static SpriteBatch batch;
public static GameStage game;
public static Skin skin;
public static Viewport viewport;
public static Stage stage;
#Override
public void create() {
viewport = new ExtendViewport(MIN_WIDTH, MIN_HEIGHT);
batch = new SpriteBatch();
initSkin();
game = new GameStage(viewport, batch, skin);
setStage(game);
}
#Override
public void dispose() {
super.dispose();
game.dispose();
skin.dispose();
}
public void initSkin() {
skin = new Skin(Gdx.files.internal("skins/uiskin.json"));
}
#Override
public void render() {
stage.act(Gdx.graphics.getDeltaTime());
stage.draw();
}
#Override
public void resize(int width, int height) {
viewport.update(width, height, true);
}
public Skin getSkin() {
return skin;
}
public static void setStage(Stage stage) {
MainGame.stage = stage;
Gdx.input.setInputProcessor(stage);
}
}
Ok, finally figured it out. Turns out the Table within the ScrollPane cannot be set to fill parent.
table.setFillParent(true);
Causes the issue. Not sure why it's doing that, but removing the setFillParent(true) fixes the issue.

Why JScrollPane does not react to mouse wheel events?

I have a JScrollPane containing a panel with a BoxLayout (PAGE AXIS).
My problem is that the JScrollPane does not react to mouse wheel events. To make it scroll using the mouse wheel i need to be on the JScrollBar.
I found this thread and i have no MouseMotionListener or MouseWheelListener, only a MouseListener. I think my problem come from the fact that my JScrollPane act on a JPanel that contains other panels itself. So when the mouse is on a panel within the JScrollPane it seems that the event is consumed by this panel i never seen by the scroll pane.
Is there a correct way to make the events caught by the children of the scroll pane visible to this scroll pane?
SSCCE:
Here a simple test case trying to show when i try to do in my Swing application.
The frame:
public class NewJFrame extends javax.swing.JFrame {
public NewJFrame() {
initComponents();
for (int i = 0; i < 50; i++) {
jPanel1.add(new TestPanel());
}
}
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
jPanel1 = new javax.swing.JPanel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel1.setLayout(new javax.swing.BoxLayout(jPanel1, javax.swing.BoxLayout.PAGE_AXIS));
jScrollPane1.setViewportView(jPanel1);
getContentPane().add(jScrollPane1, java.awt.BorderLayout.CENTER);
pack();
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new NewJFrame().setVisible(true);
}
});
}
}
And the TestPanel definition:
public class TestPanel extends javax.swing.JPanel {
public TestPanel() {
initComponents();
}
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
jLabel1.setText("jLabel1");
setBackground(new java.awt.Color(255, 51, 51));
setLayout(new java.awt.BorderLayout());
jLabel2.setText("TEST LABEL");
jLabel2.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
add(jLabel2, java.awt.BorderLayout.PAGE_START);
jTextArea1.setEditable(false);
jTextArea1.setColumns(20);
jTextArea1.setRows(5);
jTextArea1.setFocusable(false);
jScrollPane1.setViewportView(jTextArea1);
add(jScrollPane1, java.awt.BorderLayout.CENTER);
}
}
The JTextArea seems to consume the event since when the mouse cursor is inside it, the scrolling using wheel does not work. I have to put the mouse cursor outside the text area to make it works again.
Walter beat me to analysing the issue :-)
Adding a bit of detail:
It's correct that a JScrollPane supports mouseWheelHandling. According to the rules of mouseEvent dispatching, the top-most (in z-order) component gets the event, and that's the scrollPane around the textArea. So if wheeling the textarea is not required, a simple solution might be to disable the wheel-support in its scrollPane. And JScrollPane even has api for doing it:
scrollPane.setWheelScrollingEnabled(false);
Unfortunately, that doesn't work. Reason it's not working is that this property has no effect in the event dispatch chain which ultimately calls into eventTypeEnabled:
case MouseEvent.MOUSE_WHEEL:
if ((eventMask & AWTEvent.MOUSE_WHEEL_EVENT_MASK) != 0 ||
mouseWheelListener != null) {
return true;
}
This returns true if a mouseWheelListener is installed - which is done unconditionally by BasicScrollPaneUI, and not removed when the wheelEnabled property is changed (the ui doesn't even listen to that property ...) Plus the listener simply does nothing if the property is false. At least one of those facts is a bug, the ui should
either remove/add the listener depending on wheelEnabled
or: implement the listener such that it dispatches the event up the chain (as Walter does in his example)
The first option can be handled by application code:
scrollPane = new JScrollPane();
scrollPane.removeMouseWheelListener(scrollPane.getMouseWheelListeners()[0]);
it's a bit of a hack (as bug-workarounds always are :-), production code would have to listen to the wheelEnable to re-install if needed plus listen to LAF changes to update/re-remove the listeners installed by the ui.
Implementing the second option in slight modification (as to Walter's dispatching) by subclassing the JScrollPane and dispatch the event to parent if the wheelEnabled is false:
scrollPane = new JScrollPane() {
#Override
protected void processMouseWheelEvent(MouseWheelEvent e) {
if (!isWheelScrollingEnabled()) {
if (getParent() != null)
getParent().dispatchEvent(
SwingUtilities.convertMouseEvent(this, e, getParent()));
return;
}
super.processMouseWheelEvent(e);
}
};
scrollPane.setWheelScrollingEnabled(false);
The mouse wheel event gets consumed by the scroll pane around the text area. You can try to manually pass the event to the parent scroll pane like this:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TestScrollPane2 {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
// might want to use a http://tips4java.wordpress.com/2009/12/20/scrollable-panel/
JPanel panel = new JPanel(new GridLayout(0, 1));
for (int i = 0; i < 10; i++) {
panel.add(new JScrollPane(new JTextArea(3, 40)) {
#Override
protected void processMouseWheelEvent(MouseWheelEvent e) {
Point oldPosition = getViewport().getViewPosition();
super.processMouseWheelEvent(e);
if(getViewport().getViewPosition().y == oldPosition.y) {
delegateToParent(e);
}
}
private void delegateToParent(MouseWheelEvent e) {
// even with scroll bar set to never the event doesn't reach the parent scroll frame
JScrollPane ancestor = (JScrollPane) SwingUtilities.getAncestorOfClass(
JScrollPane.class, this);
if (ancestor != null) {
MouseWheelEvent converted = null;
for (MouseWheelListener listener : ancestor
.getMouseWheelListeners()) {
listener.mouseWheelMoved(converted != null ? converted
: (converted = (MouseWheelEvent) SwingUtilities
.convertMouseEvent(this, e, ancestor)));
}
}
}
});
}
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(new JScrollPane(panel));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}

Refreshing picture in drawingPanel extends JPanel

I have to load a small icon on the botton of my software. just to have a loading/ok/error icon. as sudgested on "http://www.particle.kth.se/~lindsey/JavaCourse/Book/Part1/Java/Chapter06/images.html" i create a dwowing panel extending JPanel.
class drawingPanel extends JPanel
{
Image img;
drawingPanel (Image img){
this.img = img;
}
public void paintComponent (Graphics g) {
super.paintComponent (g);
// Use the image width & height to find the starting point
int imgX = getSize ().width/2 - img.getWidth (this);
int imgY = getSize ().height/2 - img.getHeight (this);
//Draw image centered in the middle of the panel
g.drawImage (img, imgX, imgY, this);
} // paintComponent
}
I initialize the component in the following way:
// Grab the image.
Image img = new ImageIcon(iconPath+"ok.png").getImage();
// Create an instance of DrawingPanel
iconPanel = new drawingPanel(img);
all works well but at runtime i want to be able to change the icon within the pannel. i tryed all the fo;llowing but none managed to view the new picture:
Image img = new ImageIcon(iconPath+"loading.gif").getImage();
// Create a new instance of DrawingPanel
this.iconPanel = new drawingPanel(img);
this.iconPanel.repaint();
this.iconPanel.revalidate();
this.iconPanel.repaint();
this.repaint();
this.revalidate();
(i tryed this because the class in whic i am writing the code is another extension of JPanel that contains IconPanel. Any idea about why i do not manage to change the picture?
Thanks,
Stefano
First thing don't start class name with small name. Rename drawingPanel to DrawingPanel.
I have tried making a simple demo based on your description and it works fine. The image in panel is changing perfectly.
public class Demo {
public Demo() {
JFrame frame = new JFrame();
frame.setSize(400, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
// Grab the image.
Image img = new ImageIcon("1.png").getImage();
// Create an instance of DrawingPanel
final DrawingPanel iconPanel = new DrawingPanel(img);
frame.add(iconPanel, BorderLayout.CENTER);
JButton button = new JButton("Change image..");
frame.add(button, BorderLayout.NORTH);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
iconPanel.setImg(new ImageIcon("2.png").getImage());
iconPanel.repaint();
}
});
frame.setVisible(true);
}
public static void main(String[] args){
new Demo();
}
}
class DrawingPanel extends JPanel {
Image img;
DrawingPanel(Image img) {
this.img = img;
}
public void setImg(Image img) {
this.img = img;
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
// Use the image width & height to find the starting point
int imgX = getSize().width / 2 - img.getWidth(this);
int imgY = getSize().height / 2 - img.getHeight(this);
// Draw image centered in the middle of the panel
g.drawImage(img, imgX, imgY, this);
} // paintComponent
}
The changes I have made is add a setter method of img in DrawingPanel class. So instead of creating new DrawingPanel you just have to call setImg() with new Image and then call reapint to paint the new image.