Convert a Swing Progress bar to JavaFx progressBar - swing

I have my Swing progress bar class as below:
public class MyProgessBar extends JDialog implements Runnable {
/**
* #param string
*/
private JProgressBar progressBar;
private boolean cancelled=false;
public static void main(String[] args) throws InterruptedException{
MyProgessBar p = new MyProgessBar("Test");
new Thread(p).start();
for(int i=0;i<500;i++){
p.setMsg("Its "+i+"%");
p.setDone(i);
Thread.sleep(200);
}
p.dispose();
}
public MyProgessBar(String title) {
setTitle(title);
progressBar = new JProgressBar();
progressBar.setValue(0);
progressBar.setStringPainted(true);
progressBar.setIndeterminate(true);
add(progressBar);
setSize(400, 50);
setLocationRelativeTo(null);
setModal(true);
SwingUtilities.invokeLater(this);
}
/**
* #param string
*/
public void setTaskName(String string) {
progressBar.setString(string);
setTitle(string);
}
/**
* #param string
*/
public void setMsg(String string) {
progressBar.setString(string);
}
/**
* #param rows
*/
public void setDone(int rows) {
progressBar.setValue(rows);
}
/**
*
*/
public void taskFinished() {
setVisible(false);
dispose();
}
public void run() {
setVisible(true);
progressBar.setVisible(true);
}
protected void processWindowEvent(WindowEvent e) {
if (e.getID() == WindowEvent.WINDOW_CLOSING) {
this.cancelled = true;
}
super.processWindowEvent(e);
}
public boolean isCancelled(){
return cancelled;
}
}
and I am calling my progress bar using the methods defined
MyProgess bar = new MyProgess("Test");
bar.setMsg("Test");
I need a way to convert the above class to purely javafx. I am a newbie Java and javafx and would appreciate any help I can get.

The code for JavaFX ProgressBar is given below. I referred it from JavaFX docs.
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.ProgressBar;
import javafx.scene.control.ProgressIndicator;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class Main extends Application {
final Float[] values = new Float[] {-1.0f, 0f, 0.6f, 1.0f};
final Label [] labels = new Label[values.length];
final ProgressBar[] pbs = new ProgressBar[values.length];
final ProgressIndicator[] pins = new ProgressIndicator[values.length];
final HBox hbs [] = new HBox [values.length];
#Override
public void start(Stage stage) {
Group root = new Group();
Scene scene = new Scene(root, 300, 150);
scene.getStylesheets().add("progresssample/Style.css");
stage.setScene(scene);
stage.setTitle("Progress Controls");
for (int i = 0; i < values.length; i++) {
final Label label = labels[i] = new Label();
label.setText("progress:" + values[i]);
final ProgressBar pb = pbs[i] = new ProgressBar();
pb.setProgress(values[i]);
final ProgressIndicator pin = pins[i] = new ProgressIndicator();
pin.setProgress(values[i]);
final HBox hb = hbs[i] = new HBox();
hb.setSpacing(5);
hb.setAlignment(Pos.CENTER);
hb.getChildren().addAll(label, pb, pin);
}
final VBox vb = new VBox();
vb.setSpacing(5);
vb.getChildren().addAll(hbs);
scene.setRoot(vb);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
I hope it helps you..

Related

Swing cascading panels with RelativeLayout

With Swing I try to maintain a dynamic list. To show the problem, I have broken down the case to a simple sample and will attach the code here.
The JFrame DynamicDisplaySubPanelMain implements the JPanel DynamicSubPanel2.
This JPanel display the content of a List row by row. At the end an additional row allows to add a String to the list. The JPanel shall then automaically show the longer list and provide a new line to add another String.
Adding Strings works fine - but the changed List is not displayed. Can anyone tell what the reason might be.
import java.awt.BorderLayout;
import javax.swing.JFrame;
public class DynamicSubPanelMain extends JFrame {
private static final long serialVersionUID = 1L;
public DynamicSubPanelMain() {
super("My Sample dynamic List");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(800, 500);
DynamicSubPanel2 myPane = new DynamicSubPanel2();
getContentPane().add(myPane, BorderLayout.CENTER);
}
public static void main(String[] args) throws Exception {
DynamicSubPanelMain menu = new DynamicSubPanelMain();
menu.setVisible(true);
}
}
And here the JPanel:
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingWorker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.brunchboy.util.swing.relativelayout.AttributeConstraint;
import com.brunchboy.util.swing.relativelayout.AttributeType;
import com.brunchboy.util.swing.relativelayout.DependencyManager;
import com.brunchboy.util.swing.relativelayout.RelativeLayout;
import de.gombers.tools.helpers.Tools;
public class DynamicSubPanel2 extends JPanel {
private static final long serialVersionUID = 1L;
static final Logger LOGGER = LoggerFactory.getLogger(Tools.getSimpleClassName());
private RelativeLayout relativeLayout = new RelativeLayout();
private int nextIndex=-1;
private int ARRAY_SIZE=100;
private JButton[] actionJB = new JButton[ARRAY_SIZE];
protected JTextField[] workspaceTF = new JTextField[ARRAY_SIZE];
private List<String> list = new ArrayList<>();
public DynamicSubPanel2() {
nextIndex=-1;
list.add("My first object");
list.add("My second object");
rebuildPanel();
}
private void rebuildPanel() {
relativeLayout = new RelativeLayout();
this.setLayout(relativeLayout);
String thisItem;
String aboveItem=DependencyManager.ROOT_NAME;
String prevItem=DependencyManager.ROOT_NAME;
int linespace= 0;
int boundary = 5;
int gap = 5;
int buttonWidth = 110;
for (String text : list) {
nextIndex++;
actionJB[nextIndex]= new JButton("Edit");
thisItem="editJB"+nextIndex;
actionJB[nextIndex].setActionCommand("Edit");
actionJB[nextIndex].addActionListener(new EditListener(text, nextIndex));
relativeLayout.addConstraint(thisItem, AttributeType.TOP,
new AttributeConstraint(aboveItem, AttributeType.TOP, linespace));
relativeLayout.addConstraint(thisItem, AttributeType.LEFT,
new AttributeConstraint(DependencyManager.ROOT_NAME, AttributeType.LEFT, boundary));
relativeLayout.addConstraint(thisItem, AttributeType.RIGHT,
new AttributeConstraint(thisItem, AttributeType.LEFT, buttonWidth));
this.add(actionJB[nextIndex], thisItem) ;
prevItem=thisItem;
aboveItem=thisItem;
workspaceTF[nextIndex]= new JTextField(text);
workspaceTF[nextIndex].setEditable(false);
thisItem="workspaceTF"+nextIndex;
workspaceTF[nextIndex].setEditable(false);
relativeLayout.addConstraint(thisItem, AttributeType.BOTTOM,
new AttributeConstraint(prevItem, AttributeType.BOTTOM));
relativeLayout.addConstraint(thisItem, AttributeType.LEFT,
new AttributeConstraint(prevItem, AttributeType.RIGHT, gap));
relativeLayout.addConstraint(thisItem, AttributeType.RIGHT,
new AttributeConstraint(DependencyManager.ROOT_NAME, AttributeType.RIGHT, -boundary));
this.add(workspaceTF[nextIndex], thisItem) ;
prevItem=thisItem;
linespace= 30;
}
nextIndex++;
actionJB[nextIndex] = new JButton("Add");
thisItem="addJB"+nextIndex;
actionJB[nextIndex].setActionCommand("Add");
actionJB[nextIndex].addActionListener(new AddListener(nextIndex));
relativeLayout.addConstraint(thisItem, AttributeType.TOP,
new AttributeConstraint(aboveItem, AttributeType.TOP, linespace));
relativeLayout.addConstraint(thisItem, AttributeType.LEFT,
new AttributeConstraint(DependencyManager.ROOT_NAME, AttributeType.LEFT, boundary));
relativeLayout.addConstraint(thisItem, AttributeType.RIGHT,
new AttributeConstraint(thisItem, AttributeType.LEFT, buttonWidth));
this.add(actionJB[nextIndex], thisItem) ;
prevItem=thisItem;
aboveItem=thisItem;
LOGGER.info("{}", list.size());
workspaceTF[nextIndex]= new JTextField(list.size());
thisItem="workspaceTF"+nextIndex;
relativeLayout.addConstraint(thisItem, AttributeType.BOTTOM,
new AttributeConstraint(prevItem, AttributeType.BOTTOM));
relativeLayout.addConstraint(thisItem, AttributeType.LEFT,
new AttributeConstraint(prevItem, AttributeType.RIGHT, gap));
relativeLayout.addConstraint(thisItem, AttributeType.RIGHT,
new AttributeConstraint(DependencyManager.ROOT_NAME, AttributeType.RIGHT, -boundary));
this.add(workspaceTF[nextIndex], thisItem) ;
prevItem=thisItem;
}
public JPanel getPanel() {
return this;
}
class EditListener implements ActionListener {
private String text;
private int tfIndex;
public EditListener(String text, int tfIndex) {
this.text = text;
this.tfIndex = tfIndex;
}
#Override
public void actionPerformed(ActionEvent event) {
if (event.getActionCommand().equals("Edit")) {
EditWorker worker = new EditWorker(tfIndex);
worker.execute();
}
else if (event.getActionCommand().equals("Save")) {
SaveWorker worker = new SaveWorker(text, tfIndex);
worker.execute();
}
}
}
class EditWorker extends SwingWorker {
private int tfIndex;
public EditWorker(int tfIndex) {
this.tfIndex = tfIndex;
}
public Object doInBackground() throws InterruptedException, IOException {
return null;
}
public void done() {
workspaceTF[tfIndex].setBackground(Color.WHITE);
workspaceTF[tfIndex].setEditable(true);
actionJB[tfIndex].setText("Save");
actionJB[tfIndex].setActionCommand("Save");
}
}
class SaveWorker extends SwingWorker {
private String text;
private int tfIndex;
public SaveWorker(String text, int tfIndex) {
this.text = text;
this.tfIndex = tfIndex;
}
public Object doInBackground() throws InterruptedException, IOException {
list.remove(text);
list.add(workspaceTF[tfIndex].getText());
return null;
}
public void done() {
workspaceTF[tfIndex].setEditable(false);
workspaceTF[tfIndex].setBackground(Color.LIGHT_GRAY);
actionJB[tfIndex].setText("Edit");
actionJB[tfIndex].setActionCommand("Edit");
}
}
class AddListener implements ActionListener {
private int tfIndex;
public AddListener(int tfIndex) {
this.tfIndex = tfIndex;
}
#Override
public void actionPerformed(ActionEvent event) {
AddWorker worker = new AddWorker(tfIndex, this);
worker.execute();
}
}
class AddWorker extends SwingWorker {
private int tfIndex;
private boolean success;
private AddListener listener;
public AddWorker(int tfIndex, AddListener listener) {
this.tfIndex = tfIndex;
this.listener = listener;
}
public Object doInBackground() throws InterruptedException, IOException {
list.add(workspaceTF[tfIndex].getText());
return null;
}
public void done() {
rebuildPanel();
getPanel().repaint();
}
}
}

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

Java swing jtable setvalueAt doesn't work

i searched in differet questions from others. But i didn't succeed.
I want to make my table editable. But i dont know how, to call "setValueAt()".
I have the following files:
MovieManager.java
import java.util.*;
public class MovieManager
{
private static List<Movie> movieList = new ArrayList<Movie>();
public static void main(String args[])
{
final Director david = new Director("David", "Finch", Gender.MALE);
final Movie film1 = new Movie("Fightclub", 140, "Amerika", "Best Movie ever!", david);
final Movie film2 = new Movie("Panic Room", 115, "Amerika", "Good Movie", david);
final Movie film3 = new Movie("Seven", 120, "Amerika", "Headless", david);
movieList.add(film1);
movieList.add(film2);
movieList.add(film3);
// start GUI
new MovieUI();
}
public static List<Movie> getMovieList()
{
return movieList;
}
public static void setMovieList(List<Movie> movieList)
{
MovieManager.movieList = movieList;
}
}
MovieUI.java
import javax.swing.JFrame;
import javax.swing.JPanel;
public class MovieUI extends JPanel
{
/**
*
*/
private static final long serialVersionUID = 1L;
public MovieUI()
{
//Create and set up the window.
final JFrame frame = new JFrame("Movie Manager");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
final Table newContentPane = new Table();
//newContentPane.setOpaque(true); //content panes must be opaque
frame.setContentPane(newContentPane);
//Display the window.
frame.pack();
frame.setVisible(true);
}
}
Table.java
import javax.swing.JPanel;
import javax.swing.JTable;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableRowSorter;
public class Table extends JPanel
{
/**
*
*/
private static final long serialVersionUID = 1L;
public Table()
{
super(new GridLayout(1,0));
final MovieTableModel model = new MovieTableModel();
final JTable table = new JTable(model);
final TableRowSorter<MovieTableModel> sorter = new TableRowSorter<MovieTableModel>();
table.setRowSorter(sorter);
sorter.setModel(model);
final JTableHeader header = table.getTableHeader();
setLayout(new BorderLayout());
add(header, BorderLayout.PAGE_START);
add(table, BorderLayout.CENTER);
}
}
and
MovieTableModel.java
import java.util.ArrayList;
import java.util.List;
import javax.swing.table.AbstractTableModel;
class MovieTableModel extends AbstractTableModel
{
/**
*
*/
private static final long serialVersionUID = 1L;
private final List<String[]> daten = new ArrayList<String[]>();
private final List<Movie> datenMov = new ArrayList<Movie>();
private final String[] columnNames = {"Id", "Name", "Time", "Language", "Description", "Place"};
public MovieTableModel()
{
for (Movie movie: MovieManager.getMovieList())
{
String[] list = {String.valueOf(movie.getNumber()), movie.getTitle(), String.valueOf(movie.getTime()), "DE", movie.getDescription(), movie.getPlace()};
datenMov.add(movie);
daten.add(list);
}
}
public int getColumnCount()
{
return columnNames.length;
}
public int getRowCount()
{
return daten.size();
}
public String getColumnName(int col)
{
return columnNames[col];
}
public Object getValueAt(int row, int col)
{
return daten.get(row)[col];
}
public boolean isCellEditable(int row, int col)
{
if (col < 1)
{
return false;
}
else
{
return true;
}
}
public void setValueAt(String value, int row, int col)
{
System.out.println("Ich werde aufgerufen");
String[] list = daten.get(row);
list[col] = value;
daten.set(row, list);
System.out.println(daten.get(row)[col]);
List<Movie> movieliste = MovieManager.getMovieList();
Movie mov = (Movie) movieliste.get(row);
switch( col )
{
case 1:
mov.setTitle(value);
break;
case 2:
int foo = Integer.parseInt(value);
mov.setTime(foo);
break;
case 4:
mov.setDescription(value);
break;
case 5:
mov.setPlace(value);
break;
}
movieliste.set(row, mov);
MovieManager.setMovieList(movieliste);
}
}
You TableModel is too complex. All you need to do is store a List of Movies. Then you getValueAt() and setValueAt() method should access the List.
Your constructor should simply be:
public MovieTableModel(List movies)
{
datenMov = movies;
}
The getValueAt() should be something like:
public Object getValueAt(int row, int column)
{
Movie movie = datenMov.get(row);
switch(column)
{
case 0: return movie.getNumber();
case 1: return movie.getTitle();
...
default: return null;
}
}
and the setValueAt() method something like:
#Override
public void setValueAt(Object value, int row, int column)
{
Movie movie = get(row);
switch (column)
{
case 0: movie.setNumber((String)value); break;
case 1: movie.setTitle((String)value); break;
...
}
}
Edit:
Also, in the setValueAt() method you need to invoke:
fireTableCellUpdated(row, column);
I encountered similar situation, and I finally solved it.
I found that, when we double click on a cell, it go to:
JTable.getDefaultEditor(Class<?> columnClass) function.
In my case, it go to the line :
return getDefaultEditor(columnClass.getSuperclass());
Since I returned int.class when overriding the getColumnClass() in my Table Model, so it returned null for the editor.
In short, the solution is,
Don't return any Primitive Data Types when overriding getColumnClass() in your table model !

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