How to rename tab's text on double click in JavaFX 2? - tabs

I have a simple code to add tab(s) to a tabPane
#FXML
private void addNewWorkspaceTab(ActionEvent event) {
Tab workspaceTab = new Tab();
workspaceTab.setText("New Workspace");
tabpaneWorkspace.getTabs().addAll(workspaceTab);
tabpaneWorkspace.setTabClosingPolicy(TabPane.TabClosingPolicy.SELECTED_TAB);
}
By double left mouse click on a tab I would like to rename (by typing a new text) the selected tab: how can I do this?

Here is a solution for my question:
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.control.Label;
import javafx.scene.control.Tab;
import javafx.scene.control.TextField;
import javafx.scene.input.MouseEvent;
/**
*
* #author utente
*/
public class TabSetText {
public Tab createEditableTab(String text) {
final Label label = new Label(text);
final Tab tab = new Tab();
tab.setGraphic(label);
final TextField textField = new TextField();
label.setOnMouseClicked(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
if (event.getClickCount()==2) {
textField.setText(label.getText());
tab.setGraphic(textField);
textField.selectAll();
textField.requestFocus();
}
}
});
textField.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
label.setText(textField.getText());
tab.setGraphic(label);
}
});
textField.focusedProperty().addListener(new ChangeListener<Boolean>() {
#Override
public void changed(ObservableValue<? extends Boolean> observable,
Boolean oldValue, Boolean newValue) {
if (! newValue) {
label.setText(textField.getText());
tab.setGraphic(label);
}
}
});
return tab ;
}
}

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

Convert a Swing Progress bar to JavaFx progressBar

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..

Drop down menu without JMenuBar

Is there a way to implement drop down button in Java, but without implementing JMenuBar?
I need to import a button with popup menu. How can I do that?
As #DavidKroukamp stated, a JPopupMenu should do the trick.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JPopupMenu;
import javax.swing.JToggleButton;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
public class MenuButton extends JToggleButton {
JPopupMenu popup;
public MenuButton(String name, JPopupMenu menu) {
super(name);
this.popup = menu;
addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ev) {
JToggleButton b = MenuButton.this;
if (b.isSelected()) {
popup.show(b, 0, b.getBounds().height);
} else {
popup.setVisible(false);
}
}
});
popup.addPopupMenuListener(new PopupMenuListener() {
#Override
public void popupMenuWillBecomeVisible(PopupMenuEvent e) {}
#Override
public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
MenuButton.this.setSelected(false);
}
#Override
public void popupMenuCanceled(PopupMenuEvent e) {}
});
}
}

select JPanel parent at the back

Below is SSCCE to describe my problem.
import java.awt.Color;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JPanel;
public class APanel extends JPanel{
public APanel() {
this.setVisible(true);
this.setBackground(Color.red);
this.addMouseListener(new MouseListener() {
public void mouseClicked(MouseEvent e) {
if(e.getClickCount()==2)
{
}
System.out.println("Child panel clicked!");
}
public void mousePressed(MouseEvent e) { }
public void mouseReleased(MouseEvent e) {}
public void mouseEntered(MouseEvent e) { }
public void mouseExited(MouseEvent e) {}
});
}
}
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class PPanel extends JPanel{
private APanel panel1;
private APanel panel2;
private APanel panel3;
public PPanel() {
this.setLayout(new GridLayout(0,1));
panel1 = new APanel();
panel2 = new APanel();
panel2.setBackground(Color.yellow);
panel3 = new APanel();
panel3.setBackground(Color.green);
this.add(panel1);
this.add(panel2);
this.add(panel3);
this.setBackground(Color.blue);
this.addMouseListener(new MouseListener() {
public void mouseClicked(MouseEvent e) {
System.out.println("Parent panel clicked!");
}
public void mousePressed(MouseEvent e) { }
public void mouseReleased(MouseEvent e) {}
public void mouseEntered(MouseEvent e) { }
public void mouseExited(MouseEvent e) {}
});
}
public static void main(String[] args) {
JFrame frame = new JFrame();
PPanel panel = new PPanel();
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(new Dimension(350, 300));
frame.setTitle("Demo");
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
How can I do the following:
If e.getClickCount()==1 then the parent MouseListener will active and it will print "parent panel clicked!".
If e.getClickCount()==2 then the children MouseListner will active and print out "child panel clicked!".
Edit1: Closer to the proposed solution.
import java.awt.*;
import java.awt.event.*;
import javax.swing.JPanel;
import javax.swing.Timer;
public class APanel extends JPanel {
private static final long serialVersionUID = 1L;
private Point pt;
public APanel() {
timer.setRepeats(false);
addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
if (timer.isRunning() && !e.isConsumed() && e.getClickCount() > 1) {
System.out.println("double from child");
pt = null;
timer.stop();
} else {
pt = e.getPoint();
Component component = (Component)e.getSource();
component.getParent().dispatchEvent(e);
timer.restart();
}
}
});
setBackground(Color.red);
setVisible(true);
}
private Timer timer = new Timer(200, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//System.out.println("single from child");
}
});
}
In case, a mouseEvent needs to pass through multiplevel of containers, this link might be of interest.
If you elect to interpret double clicks, consider using the user's preferred interval, as suggested here.
Toolkit.getDefaultToolkit().getDesktopProperty("awt.multiClickInterval");
I think (as I know) that not is possible redirect Mouse event from child to its parent, just get parent from Component that is under the MouseCursor, or get parent from Component that's received Events from MouseClick
sure maybe someone can help you with that :-), but here is code which you needed for success with that
parent:
import java.awt.*;
import javax.swing.*;
public class PPanel extends JPanel {
private static final long serialVersionUID = 1L;
private APanel panel1;
private APanel panel2;
private APanel panel3;
public PPanel() {
setLayout(new GridLayout(0, 1));
panel1 = new APanel();
panel2 = new APanel();
panel2.setBackground(Color.yellow);
panel3 = new APanel();
panel3.setBackground(Color.green);
add(panel1);
add(panel2);
add(panel3);
setBackground(Color.blue);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
PPanel panel = new PPanel();
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension(350, 300));
frame.setTitle("Demo");
frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
}
});
}
}
Child:
import java.awt.*;
import java.awt.event.*;
import javax.swing.JPanel;
import javax.swing.Timer;
public class APanel extends JPanel {
private static final long serialVersionUID = 1L;
private Point pt;
public APanel() {
timer.setRepeats(false);
addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
if (timer.isRunning() && !e.isConsumed() && e.getClickCount() > 1) {
System.out.println("double from child");
pt = null;
timer.stop();
} else {
pt = e.getPoint();
timer.restart();
}
}
});
setBackground(Color.red);
setVisible(true);
}
private Timer timer = new Timer(400, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("single from child");
}
});
}

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