Is there a way to add a JLabel from a class to another CardLayout? - swing

I'm doing a project for school and my goal here is to design a gallery on Swing. One of the features is the possibility to add new images to my gallery and display the new picture. I created a card where you can add your picture by browsing the file explorer on your computer and then it will copy and add the file to the folder of the app. For the moment this part works fine, but when I go back to my GalleryPage CardLayout the image is not displayed (because I don't know how to add it directly). What I'm trying to do is add this new image to the bottomPanel of my GalleryPage java class from newImg [JLabel] on my NewImage java class. Is there a way to do that? I've been browsing the Internet to find an answer but I can't find a solution.
Here is my code:
Gallery.java
public class Gallery extends JPanel {
private GalleryPage panelGalleryPage;
private NewImage newImage;
protected static CardLayout cardGal;
public Gallery() {
super();
setLayout(new CardLayout());
cardGal = (CardLayout) this.getLayout();
panelGalleryPage = new GalleryPage();
newImage = new NewImage();
add(panelGalleryPage, "GalleryPage");
add(newImage, "NewImage");
}
}
GalleryPage.java
public class GalleryPage extends JPanel {
// preparing my grid of images by sorting the filepath of each image.
File directory = new File("oop_2022/src/main/java/com/phone/common/png/Galery_images");
int fileCount = directory.list().length;
private JButton addImg, delImg;
private JLabel title;
private JLabel[] cache = new JLabel[fileCount];
private ImageIcon[] imgGrid = new ImageIcon[fileCount];
private ImageIcon imgTitle, imgAdd, imgDel;
private JSplitPane splitPanel;
private JPanel bottomPanel, topPanel;
private List<String> results;
public GalleryPage() {
super();
setBackground(PowerOn.userInterface.DARK_GREY);
initComponents();
}
public void initComponents() {
// create a split pane
splitPanel = new JSplitPane();
topPanel = new JPanel(); // top component
bottomPanel = new JPanel(); // bottom component
// configure splitPanel
splitPanel.setOrientation(JSplitPane.VERTICAL_SPLIT);
splitPanel.setDividerLocation(100);
splitPanel.setDividerSize(0);
splitPanel.setTopComponent(topPanel);
splitPanel.setBottomComponent(bottomPanel);
// create title
imgTitle = new ImageIcon("oop_2022/src/main/java/com/phone/common/png/images.png");
imgTitle.setImage(imgTitle.getImage().getScaledInstance(80, 80, Image.SCALE_DEFAULT));
title = new JLabel(imgTitle);
// create add Button
imgAdd = new ImageIcon("oop_2022/src/main/java/com/phone/common/png/add.png");
imgAdd.setImage(imgAdd.getImage().getScaledInstance(40, 40, Image.SCALE_DEFAULT));
addImg = new JButton(imgAdd);
addImg.setPreferredSize(new Dimension(60, 40));
// add Actionlisteneer to addImg Button
addImg.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
Gallery.cardGal.show(PowerOn.gallery, "NewImage");
}
});
// create delete Button
imgDel = new ImageIcon("oop_2022/src/main/java/com/phone/common/png/trash.png");
imgDel.setImage(imgDel.getImage().getScaledInstance(40, 40, Image.SCALE_DEFAULT));
delImg = new JButton(imgDel);
delImg.setPreferredSize(new Dimension(60, 40));
// Add title and buttons to the topPanel
topPanel.add(title);
topPanel.add(addImg);
topPanel.add(delImg);
// add the splitPanel to the frame
this.add(splitPanel);
// set top and bottom panel Background
topPanel.setBackground(PowerOn.userInterface.DARK_GREY);
bottomPanel.setBackground(PowerOn.userInterface.DARK_GREY);
// set a GridLayout for the bottomPanel
this.setLayout(new GridLayout());
GridLayout layout = new GridLayout(0, 3, 10, 10);
bottomPanel.setLayout(layout);
// creating an array of file
results = new ArrayList<String>();
File[] files = new File("oop_2022/src/main/java/com/phone/common/png/Galery_images").listFiles();
// retrieving the name of each images
for (File file : files) {
if (file.isFile()) {
results.add(file.getName());
}
}
// create an array of images
for (int i = 0; i < fileCount; i++) {
imgGrid[i] = new ImageIcon(files[i].toString());
}
// loop to sale and add the images to the bottomPanel
for (int i = 0; i < files.length; i++) {
// scaling the images
imgGrid[i].setImage(imgGrid[i].getImage().getScaledInstance(120, 120,
Image.SCALE_SMOOTH));
// add the images to the grid
cache[i] = new JLabel(imgGrid[i]);
bottomPanel.add(cache[i]);
}
}
}
NewImage.java
public class NewImage extends JPanel {
private JLabel title, newImg;
private ImageIcon cacheImg;
private JPanel display;
private JButton choose, back;
private JFileChooser file;
private File selectedFile;
private Gallery addNew;
public NewImage() {
super();
setBackground(PowerOn.userInterface.DARK_GREY);
initComponents();
}
public void initComponents() {
// configure title JLabel
title = new JLabel("Choose a new image to add (jpg or png only)");
title.setHorizontalAlignment(title.CENTER);
// configurin choose JButton + Actionlistener
choose = new JButton("Explore");
file = new JFileChooser();
choose.setPreferredSize(new Dimension(60, 60));
choose.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
int result = file.showOpenDialog(display);
if (result == JFileChooser.APPROVE_OPTION) {
selectedFile = file.getSelectedFile();
// check the type of the file only jpg and png accepted
String check = selectedFile.getAbsolutePath()
.substring(selectedFile.getAbsolutePath().length() - 3);
System.out.println(check);
// if the fil is ok add the file to the gallery directory
if (check.equals("png") || check.equals("jpg")) {
// retrieving the name of the file and copy on the galery folder
try {
String[] parts = selectedFile.getAbsolutePath().split(Pattern.quote(File.separator));
String dest = "oop_2022/src/main/java/com/phone/common/png/Galery_images/"
+ parts[parts.length - 1];
copyFile(selectedFile, new File(dest));
cacheImg = new ImageIcon(dest);
cacheImg.setImage(cacheImg.getImage().getScaledInstance(120, 120, Image.SCALE_DEFAULT));
newImg = new JLabel(cacheImg);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
JOptionPane.showMessageDialog(null, "Your image as been succesfully uploaded");
}
// if the file is not a png or a jpg display an error message
else {
JOptionPane.showMessageDialog(null, "You must choose a png or jpg file");
}
}
}
});
// configuring back JButton + Actionlistener
back = new JButton("Return to home page");
back.setPreferredSize(new Dimension(60, 60));
back.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
Gallery.cardGal.show(PowerOn.gallery, "GalleryPage");
}
});
// configure layout of panel
this.setLayout(new GridLayout());
// add panels
display = new JPanel();
display.setLayout(new GridLayout(0, 1));
this.add(display);
display.add(title);
display.add(choose);
display.add(back);
}
public static void copyFile(File from, File to) throws IOException {
Files.copy(from.toPath(), new FileOutputStream(to));
}
}
What I want is that the image I added is directly displayed without running the code again when I go back to my gallery page.
my gallery page

Related

List app in java cant call to a function. pls

I have done all the details I have done, and I don't get an error but what I want to do doesn't work.
I tried to check on google, chatgpt, and friends. I was expected to a window with wait for input from the user, and the user writes a task and he enters "submit". Then, a window of DeadLine comes with an import calendar. So, the user chooses a DeadLine and he presses "OK". and then I created a constructor with the selected time and the task (to print the input) therefore, I called to the constructor and its doesn't call. Please help me. ):
The code:
import javax.swing.*;
import com.toedter.calendar.JCalendar;
import java.awt.*;
import java.awt.event.*;
import java.util.Calendar;
import java.util.Date;
public class List extends JFrame {
String todo = "TO DO: ";
ImageIcon icon1;
JButton button;
public static String task;
static JLabel label,label2,label3;
static JLabel titletaskLabel,titletaskLabel2,titletaskLabel3,titletaskLabel4;
static JFrame frame;
public static JTextField text;
static Font myFont = new Font("Ink Free", Font.BOLD, 30);
static Font yourFont = new Font("Ink Free", Font.HANGING_BASELINE, 20);
static JCalendar calendar;
static Date selectedDate;
List() {
frame = new JFrame("List");
icon1 = new ImageIcon("list.png");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 900);
frame.setIconImage(icon1.getImage());
frame.setLayout(null);
label = new JLabel("To Do List: ");
label.setBounds(50, 50, 200, 20);
label2 = new JLabel("Enter a task: ");
label2.setFont(myFont);
label2.setBounds(70, 460, 200, 40);
button = new JButton("Submit");
button.setBounds(470, 500, 80, 50);
button.setBackground(Color.green);
button.addActionListener(new ActionListener1());
text = new JTextField();
text.setBounds(70, 500, 370, 50);
text.setFont(myFont);
frame.add(text);
frame.add(button);
frame.add(label);
frame.add(label2);
frame.setVisible(true);
}
static void addDeadline() {
JDialog dialog = new JDialog(frame, "Choose a Due Date", true);
dialog.setSize(400, 400);
dialog.setLocationRelativeTo(frame);
JPanel calendarPanel = new JPanel();
calendarPanel.setBounds(70, 600, 370, 200);
calendar = new JCalendar();
calendarPanel.add(calendar);
JButton okButton = new JButton("OK");
okButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// Get the selected date
Calendar selectedCalendar = calendar.getCalendar();
selectedDate = selectedCalendar.getTime();
task = text.getText();
System.out.println(selectedDate);
dialog.setVisible(false);
tasks(); // add the new task to the frame
}
});
calendarPanel.add(okButton);
dialog.add(calendarPanel);
dialog.setVisible(true);
}
static void tasks() {
titletaskLabel = new JLabel(task + "The DeadLine is: " + selectedDate);
titletaskLabel.setBounds(50, 70, 200, 50);
frame.add(titletaskLabel);
}
static class ActionListener1 implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
addDeadline();
}
}
}
public class Main extends List{
public static void main(String[] args) {
new List();
}
}

java jlabel working in windows but not in linux showing old, formats on screen, openjdk?

So I have written a Java application, that provides a transparent Heads up display at the top of the screen, it works perfectly on windows, but on my kubuntu 16.04 machine it does not clear the old label when you change the labels text, you end up with a ton of overlapping mess.
because a picture is worth a thousand words, the top is how it looks in windows, the bottom is how it looks under kubuntu:
https://s23.postimg.org/yra0vvlvf/rawr.png
here is the code:
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.net.URL;
import javax.swing.*;
import java.io.*;
public class spob extends JFrame implements WindowFocusListener
{
public spob()
{
if (!SystemTray.isSupported()) {
System.out.println("SystemTray is not supported");
return;
}
final TrayIcon trayIcon = new TrayIcon((new ImageIcon("icon.png", "trayicon")).getImage());
final SystemTray tray = SystemTray.getSystemTray();
trayIcon.setImageAutoSize(true);
trayIcon.setToolTip("spO2 pr monitor");
try {
tray.add(trayIcon);
} catch (AWTException e) {
System.out.println("TrayIcon could not be added.");
return;
}
setType(javax.swing.JFrame.Type.UTILITY);
setUndecorated(true);
getContentPane().setBackground(new Color(1.0f,1.0f,1.0f,0.0f));
setBackground(new Color(1.0f,1.0f,1.0f,0.0f));
setSize(400, 35);
JLabel label = new JLabel("Loading...");
label.setFont(new Font("Tahoma", Font.BOLD, 28));
label.setForeground(Color.GREEN);
add(label);
setLocation(800, 0);
addWindowFocusListener(this);
setAlwaysOnTop( true );
this.setFocusable(true);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setVisible(true);
URL url = null;
BufferedReader in = null;
String[] anArray = new String[10];
anArray[0] = "<html><font color=green>- spO2:91 pr:65</font></html>";
anArray[1] = "<html><font color=red>+ spO2:85 pr:77</font></html>";
anArray[2] = "<html><font color=green>- spO2:90 pr:68</font></html>";
anArray[3] = "<html><font color=orange>+ spO2:89 pr:76</font></html>";
anArray[4] = "<html><font color=orange>- spO2:89 pr:72</font></html>";
anArray[5] = "<html><font color=orange>+ spO2:88 pr:73</font></html>";
anArray[6] = "<html><font color=red>- spO2:87 pr:78</font></html>";
anArray[7] = "<html><font color=red>+ spO2:86 pr:73</font></html>";
anArray[8] = "<html><font color=green>- spO2:92 pr:74</font></html>";
anArray[9] = "<html><font color=green>+ spO2:90 pr:71</font></html>";
while (true){
try {
Thread.sleep(200);
//url = new URL("http://192.168.1.153/stat.php");
//in = new BufferedReader(new InputStreamReader(url.openStream()));
//label.setText(in.readLine().toString());
Random randomno = new Random();
label.setText(anArray[randomno.nextInt(9 - 1) + 1]);
} catch (Exception ex) {
} finally {
//try {
// in.close();
//} catch (IOException e) {
//}
}
}
}
public void windowGainedFocus(WindowEvent e){}
public void windowLostFocus(WindowEvent e)
{
if(e.getNewState()!=e.WINDOW_CLOSED){
setAlwaysOnTop(false);
setAlwaysOnTop(true);
}
}
public static void main(String[] args)
{
new spob();
}
}
So, a number of issues
You're violating the single threaded rules of Swing, essentially, updating the UI from outside the context of the EDT, this can cause issues if the system is trying to paint something while you're trying to update it
getContentPane().setBackground(new Color(1.0f,1.0f,1.0f,0.0f)); - Swing doesn't know how to deal with opaque components which have an alpha based color, it tends to not to update the any of the components beneath it.
Transparent windows are ... fun ... they tend to introduce their own issues beyond what we would normally expect.
On my Mac system I was able to reproduce the issue, but inconsistently. This was especially apparent, because the Mac OS keeps rendering a shadow around the text.
The first thing I got rid of was setType(javax.swing.JFrame.Type.UTILITY);, I also added a repaint request of the label's parent container which seems to have solved the symptoms of the problem, but again, I was able to execute the code without at times.
If you want to update the UI periodically, you should use a Swing Timer, see How to use Swing Timers for more details. If you need to do something in the background and then update the UI, you should use a SwingWorker, have a look Worker Threads and SwingWorker for more details
(wow is me, it doesn't like my animated gif :()
The example deliberately uses a translucent background, it's intended to show the frame. Change pane.setAlpha(0.5f); to pane.setAlpha(0.0f); to make it fully transparent (I've tested that as well).
If you have issues, uncomment the line label.getParent().repaint(); in the Timer and see if that helps
public class Test {
public static void main(String[] args) {
new Test();
}
private JLabel label;
private String[] anArray = {
"<html><font color=green>- spO2:91 pr:65</font></html>",
"<html><font color=red>+ spO2:85 pr:77</font></html>",
"<html><font color=green>- spO2:90 pr:68</font></html>",
"<html><font color=orange>+ spO2:89 pr:76</font></html>",
"<html><font color=orange>- spO2:89 pr:72</font></html>",
"<html><font color=orange>+ spO2:88 pr:73</font></html>",
"<html><font color=red>- spO2:87 pr:78</font></html>",
"<html><font color=red>+ spO2:86 pr:73</font></html>",
"<html><font color=green>- spO2:92 pr:74</font></html>",
"<html><font color=green>+ spO2:90 pr:71</font></html>"
};
private Random randomno = new Random();
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setUndecorated(true);
frame.setAlwaysOnTop(true);
// Transparent window...
frame.setBackground(new Color(255, 255, 255, 0));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
BackgroundPane pane = new BackgroundPane();
// Set this to 0.0f to make it fully transparent
pane.setAlpha(0.5f);
pane.setLayout(new BorderLayout());
pane.setBorder(new EmptyBorder(10, 10, 10, 10));
frame.setContentPane(pane);
label = new JLabel("Loading...");
label.setFont(new Font("Tahoma", Font.BOLD, 28));
label.setForeground(Color.GREEN);
frame.add(label);
frame.pack();
Dimension size = frame.getSize();
size.width = 400;
frame.setSize(size);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
Timer timer = new Timer(200, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
label.setText(anArray[randomno.nextInt(9 - 1) + 1]);
// label.getParent().repaint();
}
});
timer.start();
}
});
}
public class BackgroundPane extends JPanel {
private float alpha;
public BackgroundPane() {
setOpaque(false);
}
public void setAlpha(float alpha) {
this.alpha = alpha;
repaint();
}
public float getAlpha() {
return alpha;
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.setColor(getBackground());
g2d.setComposite(AlphaComposite.SrcOver.derive(getAlpha()));
g2d.fillRect(0, 0, getWidth(), getHeight());
g2d.dispose();
}
}
}
nb I'm not using openJDK, I'm using Java 8, that might make a difference
Testing for capabilities
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
public class Test {
public static void main(String[] args) {
GraphicsEnvironment ge
= GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gd = ge.getDefaultScreenDevice();
boolean isUniformTranslucencySupported
= gd.isWindowTranslucencySupported(GraphicsDevice.WindowTranslucency.TRANSLUCENT);
boolean isPerPixelTranslucencySupported
= gd.isWindowTranslucencySupported(GraphicsDevice.WindowTranslucency.PERPIXEL_TRANSLUCENT);
boolean isShapedWindowSupported
= gd.isWindowTranslucencySupported(GraphicsDevice.WindowTranslucency.PERPIXEL_TRANSPARENT);
System.out.println("isUniformTranslucencySupported = " + isUniformTranslucencySupported);
System.out.println("isPerPixelTranslucencySupported = " + isPerPixelTranslucencySupported);
System.out.println("isShapedWindowSupported = " + isShapedWindowSupported);
}
}

libGDX 1.4.1 button listener on a secondary screen

I have two screens, a MainActivity in my core folder, that has the render() method split into a few switch cases. On game-over, this part of the switch case gets triggered, which calls the render part of my game-over class:
case STOPPED:
// Exit and clean the game
gameOverScreen.render(Gdx.graphics.getDeltaTime());
break;
...
This is my GameOverScreen class:
public class GameOverScreen implements Screen {
private SpriteBatch gameOverBatch;
private FreeTypeFontGenerator gameOverFontGen;
private FreeTypeFontGenerator.FreeTypeFontParameter gameOverLogoParam;
private FreeTypeFontGenerator.FreeTypeFontParameter gameOverButtonParam;
private final MainActivity mainActivity;
private OrthographicCamera camera;
private BitmapFont bitmapLogoFont;
private BitmapFont bitmapButtonFont;
private Button exitGameButton;
private Button gameRestartButton;
private Sound buttonSound;
private Stage stage;
private float w;
private float h;
// Constructor
public GameOverScreen(MainActivity mainActivity) {
w = Gdx.graphics.getWidth();
h = Gdx.graphics.getHeight();
gameOverBatch = new SpriteBatch();
this.mainActivity = mainActivity;
camera = new OrthographicCamera();
camera.setToOrtho(false, 300, 300);
// Instantiate the font for this screen from file
gameOverFontGen = new FreeTypeFontGenerator(Gdx.files.internal("fonts/SF_Wonder_Comic.ttf"));
gameOverLogoParam = new FreeTypeFontGenerator.FreeTypeFontParameter();
gameOverLogoParam.size = 110;
gameOverButtonParam = new FreeTypeFontGenerator.FreeTypeFontParameter();
gameOverButtonParam.size = 40;
// Font for the logo
bitmapLogoFont = new BitmapFont();
bitmapLogoFont = gameOverFontGen.generateFont(gameOverLogoParam);
// Font for the buttons
bitmapButtonFont = new BitmapFont();
bitmapButtonFont = gameOverFontGen.generateFont(gameOverButtonParam);
// Instantiate the buttonSound
buttonSound = Gdx.audio.newSound(Gdx.files.internal("sounds/pauseBtn_sound.ogg"));
/*************************************** Create a Stage *******************************************/
stage = new Stage();
// Add some actors as the buttons
exitGameButton = new Button(new TextureRegionDrawable(
new TextureRegion(new Texture(Gdx.files.internal("images/off_red.png")))),
new TextureRegionDrawable(new TextureRegion(new Texture(Gdx.files.internal("images/off_white.png")))));
//exitGameButton.setX((w, 150));
//pauseButton.setY(flipCoordinates(h, 150));
exitGameButton.setOrigin(exitGameButton.getWidth() / 2, exitGameButton.getHeight() / 2);
exitGameButton.setBounds(w / 2 + 100, h / 2 - 60, exitGameButton.getWidth(), exitGameButton.getHeight());
exitGameButton.act(Gdx.graphics.getDeltaTime());
stage.addActor(exitGameButton);
exitGameButton.addListener(new ChangeListener() {
#Override
public void changed (ChangeEvent event, Actor actor) {
buttonSound.play();
}
});
// Add some actors as the buttons
TextButton.TextButtonStyle restartStyle = new TextButton.TextButtonStyle();
restartStyle.font = bitmapButtonFont;
restartStyle.up = new TextureRegionDrawable(new TextureRegion(new Texture(Gdx.files.internal("images/back_red.png"))));
restartStyle.down = new TextureRegionDrawable(new TextureRegion(new Texture(Gdx.files.internal("images/back_white.png"))));
gameRestartButton = new Button(new TextButton.TextButtonStyle(restartStyle));
gameRestartButton.setOrigin(gameRestartButton.getWidth() / 2, gameRestartButton.getHeight() / 2);
gameRestartButton.setBounds(w / 2 - 100, h / 2 - 60, gameRestartButton.getWidth(), gameRestartButton.getHeight());
gameRestartButton.act(Gdx.graphics.getDeltaTime());
stage.addActor(gameRestartButton);
// Capture the event listener for the return button
gameRestartButton.addListener(new ChangeListener() {
#Override
public void changed(ChangeEvent event, Actor actor) {
// Do something on restart
//MainActivity.state = MainActivity.State.RUN;
Gdx.app.log("GameRestartButton", " has been pressed");
}
});
gameRestartButton.act(Gdx.graphics.getDeltaTime());
//stage.addActor(exitGameButton);
//stage.addActor(gameRestartButton);
}
#Override
public void render(float delta) {
Gdx.gl.glClearColor(0, 0, 0, 0);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
camera.update();
gameOverBatch.begin();
bitmapLogoFont.setColor(Color.RED);
bitmapLogoFont.draw(gameOverBatch, "Game Over", w / 2 - 210, h / 2 + 150f);
gameOverBatch.end();
exitGameButton.act(Gdx.graphics.getDeltaTime());
stage.act(Gdx.graphics.getDeltaTime());
stage.draw();
}
#Override
public void resize(int width, int height) {
}
#Override
public void show() {
}
#Override
public void hide() {
}
#Override
public void pause() {
}
#Override
public void resume() {
}
#Override
public void dispose() {
gameOverFontGen.dispose();
}
}
In GameOverScreen constructor I have two buttons (exitGameButton and gameReturnButton) I'd like to be able to trigger their event-listeners, but I can't seem to be able to do it. Neither of my buttons responds to the event listener. What am I doing wrong? Do I need to add something else on to my MainActivity class for these buttons to work ? Thanks much.
I figured it out, on the second screen I was missing from the constructor this: Gdx.input.setInputProcessor(stage); , of course, that only works if a stage has been previously created.
try this in your class GameOverScreen
.//
public Stage getStageGameOverScreen(){
return this.stage;
}
your Case:
case STOPPED:
// Exit and clean the game
Gdx.input.setInputProcessor(gameOverScreen.getStageGameOverScreen());
gameOverScreen.render(Gdx.graphics.getDeltaTime());
break;
...

Firefox 'Open new tab' on JTabbedPane

I want to add a button to JTabbedPane's title bar (similar to the 'open new tab' ('+') button in Firefox)
I have tried to add to the glass pane of JTabbedPane's container. but since my tabbedpane contains within a JPanel seems it doesn't work for me.
Any suggestion will be a great help for me.
Thank you.
Instead of adding a button I have tried it in a different way and worked for me... I have added a JLabel (with '+') as a hidden tab and when user tries to select that tab i'll be adding a new tab.
public class AddTabButtonDemo extends JFrame{
private JTabbedPane tabbedPane = new JTabbedPane();
public AddTabButtonDemo() {
JLabel tab1Label = new JLabel("tab1");
JPanel tab1 = new JPanel();
tab1.add(tab1Label);
tabbedPane.addTab("tab1", tab1);
tabbedPane.addTab("+", new JLabel());
tabbedPane.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
if (tabbedPane.getSelectedComponent() instanceof JLabel) {
int count = tabbedPane.getTabCount();
JLabel newTabLabel = new JLabel("tab" + count);
JPanel newTab = new JPanel();
newTab.add(newTabLabel);
tabbedPane.add(newTab, count - 1);
tabbedPane.setTitleAt(count - 1, "tab" + count);
tabbedPane.setSelectedComponent(newTab);
}
}
});
this.add(tabbedPane, BorderLayout.CENTER);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.pack();
this.setMinimumSize(new Dimension(300, 300));
this.setVisible(true);
}
public static void main(String[] args) {
new AddTabButtonDemo();
}
}

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.