no luck with javax timer with Jlabel - java

I'm still having issues with updating the JLabel using a timer. I can't seem to figure out what I am missing. the global second variable stays at zero so I am guessing the timers working but not updating the GUI window?
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class Globals
{
public static int seconds = 0;
}
class main
{
public static void main(String Args[])
{
//text timeline = new text();
JFrame testing = new JFrame();
frame textdes = new frame();
testing.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
testing.setSize(1000,1000);
testing.setVisible(true);
Countdown timer = new Countdown();
Timer countdown = new Timer(5000, timer);
countdown.start();
JLabel countdowntext = new JLabel();
countdowntext.setText("Now its :" + Globals.seconds);
testing.add(countdowntext);
testing.add(textdes);
}
}
class frame extends JFrame
{
class Countdown implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
Globals.seconds++;
}
}
}

You're setting the text of the label only once in the program. Then the timer changes the value of a variable, but doesn't do anything with the label. It should do:
Globals.seconds++;
countdowntext.setText("Now its :" + Globals.seconds);
Here's a complete example:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class Globals {
public static int seconds = 0;
}
class Main {
public static void main(String Args[]) {
//text timeline = new text();
JFrame testing = new JFrame();
testing.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
testing.setSize(1000,1000);
testing.setVisible(true);
JLabel countDownLabel = new JLabel();
countDownLabel.setText("Now it's : " + Globals.seconds);
testing.add(countDownLabel);
CountDown countdown = new CountDown(countDownLabel);
Timer timer = new Timer(5000, countDown);
timer.start();
}
}
class CountDown implements ActionListener {
private JLabel countDownLabel;
public CountDown(JLabel countDownLabel) {
this.countDownLabel = countDownLabel;
}
#Override
public void actionPerformed(ActionEvent e) {
Globals.seconds++;
this.countDownLabel.setText("Now it's : " + Globals.seconds);
}
}

Try this -
public class MainFrame{
JFrame frame = new JFrame("Main frame");
JPanel panel = new JPanel();
JLabel countdownText = new JLabel();
int seconds = 0;
public MainFrame() {
Timer timer = new Timer(5000, new Countdown());
timer.start();
panel.add(countdownText);
frame.getContentPane().add(panel);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setPreferredSize(new Dimension(320,240));
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
countdownText.setText("Now its :" + seconds);
}
class Countdown implements ActionListener {
public void actionPerformed(ActionEvent e) {
seconds++;
countdownText.setText("Now its :" + seconds);
}
}
public static void main(String [] args){
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new MainFrame();
}
});
}
}

Related

JFrame suddenly freaks out

i'm making a tiny program where you have 3 timers and when you press start it gives a progress bar until time is over, but JFrame decided to do this after I pressed start:
Here is my code:
package com.company;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Main {
static int getTime(JFrame frame){
String ts = JOptionPane.showInputDialog(frame, "Set time: ", "time", 1);
return Integer.parseInt(ts);
}
public static class globalVars{
public static int time1 = 5;
public static int time2 = 5;
public static int time3 = 5;
}
static void startTimer(JFrame frame) {
int time = globalVars.time1+globalVars.time2+globalVars.time3;
int timeF = Math.toIntExact(System.currentTimeMillis() / 1000l);
JProgressBar bar = new JProgressBar(0, time);
frame.add(bar);
frame.pack();
int i=0;
while (System.currentTimeMillis()!=timeF+time* 60L){
bar.setValue((timeF+time*60-Math.toIntExact(System.currentTimeMillis() / 1000l))/60);
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("Timer");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new FlowLayout());
//-----------------------------------------------------------//
Icon icon1 = new ImageIcon("placeholder.png");
String button1Text = "Button1, ";
JButton button1 = new JButton(String.format("%s%dmin", button1Text, globalVars.time1));
button1.setIcon(icon1);
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
globalVars.time1=getTime(frame);
button1.setText(String.format("%s%dmin", button1Text, globalVars.time1));
}
});
frame.add(button1);
//-----------------------------------------------------------//
Icon icon2 = new ImageIcon("placeholder.png");
String button2Text = "Button2, ";
JButton button2 = new JButton(String.format("%s%dmin", button2Text, globalVars.time2));
button2.setIcon(icon2);
button2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
globalVars.time2=getTime(frame);
button2.setText(String.format("%s%dmin", button2Text, globalVars.time2));
}
});
frame.add(button2);
//-----------------------------------------------------------//
Icon icon3 = new ImageIcon("placeholder.png");
String button3Text = "Button3, ";
JButton button3 = new JButton(String.format("%s%dmin", button3Text, globalVars.time3));
button3.setIcon(icon3);
button3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
globalVars.time3=getTime(frame);
button3.setText(String.format("%s%dmin", button3Text, globalVars.time3));
}
});
frame.add(button3);
//-----------------------------------------------------------//
JButton buttonStart = new JButton("Start");
buttonStart.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
buttonStart.removeActionListener(this);
startTimer(frame);
}
});
frame.add(buttonStart);
//-----------------------------------------------------------//
frame.pack();
frame.setSize(400, 200);
frame.setVisible(true);
}
}
I know it is a very inefficient way of doing things and I will improve it but now I'm more worried about the black screen. Tnx!

Java Thread Start-Stop-Start on same button click

I am creating a simple java program with a GUI built with the help of window builder. The GUI consists of just a button.
On button click,start a thread that will print to the random number infinitely until it is stopped by clicking the same button again.
Here is my code
LoopTest.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class LoopTest extends JFrame implements ActionListener {//******
private JButton startB, stopB;
private JTextArea oa;
Start sta;
public LoopTest(){
super("Final Exam: Question ");
Container c = getContentPane();
c.setLayout(new FlowLayout());
startB = new JButton("START"); c.add(startB);
stopB = new JButton("STOP"); c.add(stopB);
oa = new JTextArea(5,20); c.add(oa);
c.add(new JScrollPane(oa));
registerEvents();
sta = new Start("Loop", oa);
}
public void registerEvents(){
startB.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent ae){
if(startB.isEnabled() == true )
sta.setLoopFlag(true);
if(!sta.isAlive())
sta.start();
startB.setEnabled(false);
}
}
);
stopB.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent ae){
if(stopB.isEnabled()==true){
sta.setLoopFlag(false);
}
}
}
);
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
public static void main(String[] args){
LoopTest app = new LoopTest();
app.setSize(300,300);
app.setLocationRelativeTo(null);
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
app.setVisible(true);
}
}
Start.java
public class Start extends Thread {
private JTextArea ta;
private boolean loopFlag;
public Start(String name, JTextArea ta){
super(name);
this.ta = ta;
ta.setText("");
loopFlag = true;
}
public void run(){
int num=0;
while(true)
while(loopFlag){
num = 1+ (int)(Math.random()*100);
ta.append(num + "\n");
}
}
public void setLoopFlag(boolean value){
loopFlag = value;
}
}
Stop.java
public class Stop extends Thread {
public Stop( String name ){
super(name);
}
public void run(){
}
}
Thanks in advance.
Your code breaks Swing threading rules as you're making mutational changes to Swing components off of the Swing event thread.
Suggestions:
Never extend Thread. It's almost always better to implement Runnable and use the Runnable in a Thread.
Avoid making Swing calls, other than repaint() off of the Swing event thread.
Your while (true) is a "tight" loop -- it has no Thread.sleep within it, and that means that it risks typing up the CPU in its tight loop, something that can hamper your program and your computer.
Best to avoid using direct background threading altogether here as your code issue can be solved much more easily and cleanly by using a Swing Timer. Please check the Swing Timer Tutorial
You can easily start and stop this Timer by calling its start() and stop() methods.
I would also use a JList preferentially over a JTextArea since it can more easily handle large amounts of data.
I also like using AbstractActions rather than ActionListeners for my JButton, and this problem lends itself nicely to their use. You can create an Action for start and one for stop and simply swap out the button's actions.
For example:
import java.awt.BorderLayout;
import java.awt.event.*;
import javax.swing.*;
#SuppressWarnings("serial")
public class StartStop extends JPanel {
private static final int TIMER_DELAY = 300;
private StartAction startAction = new StartAction();
private StopAction stopAction = new StopAction();
private JButton button = new JButton(startAction);
private DefaultListModel<Integer> model = new DefaultListModel<>();
private JList<Integer> jList = new JList<>(model);
private Timer timer = new Timer(TIMER_DELAY, new TimerListener());
public StartStop() {
JPanel btnPanel = new JPanel();
btnPanel.add(button);
jList.setFocusable(false);
jList.setVisibleRowCount(10);
jList.setPrototypeCellValue(100000);
JScrollPane scrollPane = new JScrollPane(jList);
setLayout(new BorderLayout());
add(scrollPane, BorderLayout.CENTER);
add(btnPanel, BorderLayout.PAGE_END);
}
private class TimerListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
int num = 1 + (int) (Math.random() * 100);
model.addElement(num);
}
}
private class StartAction extends AbstractAction {
public StartAction() {
super("Start");
putValue(MNEMONIC_KEY, KeyEvent.VK_S);
}
#Override
public void actionPerformed(ActionEvent e) {
timer.start();
button.setAction(stopAction);
}
}
private class StopAction extends AbstractAction {
public StopAction() {
super("Stop");
putValue(MNEMONIC_KEY, KeyEvent.VK_S);
}
#Override
public void actionPerformed(ActionEvent e) {
timer.stop();
button.setAction(startAction);
}
}
private static void createAndShowGui() {
JFrame frame = new JFrame("Start Stop");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new StartStop());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}

JPanel visibility (true) not showing

I got a mainframe and a strartscreen with a timer counting down from 3, 2, 1.
I've set the mainframe main.setVisible(false) but when the timer reaches 0 I want it to be main.setVisible(true). I did this but it doesnt seem to work and I dont know what I am doing wrong. This is what I have so far:
*Mainframe:
public class MainPanel extends JPanel {
public JLabel welkom, vraag, vraagnr, minimize, close;
public JButton btnVolgende, btnExit, btnVraag;
public ImageIcon icon;
public MainPanel() {
setLayout(null);
setVisible(false); // visibility false
Timerframe:
MainPanel main = new MainPanel();
Vraag1 vraag1 = new Vraag1();
ActionListener listener = new ActionListener()
{
int seconden = 3;
public void actionPerformed(ActionEvent e) {
seconden--;
if(seconden > 0)
{
countdown.setText("" + seconden);
}
else if(seconden == 0)
{
main.setVisible(true); //setframe visible
vraag1.setVisible(true);
setVisible(false);
}
}
};
afteller = new Timer(1000, listener);
afteller.start();
}
And here is my JFrame:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseListener;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import com.sun.glass.events.MouseEvent;
public class Frame {
static JFrame frame;
static MainPanel paneel;
static Vraag1 vraag1;
static StartScherm start;
public static void main(String[] args) {
// TODO Auto-generated method stub
frame = new JFrame();
frame.setLayout(null);
frame.setTitle("Voetbal quiz - Edward Kerckhof");
frame.setSize(1191,677);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ImageIcon icon = new ImageIcon("src/images/voetbal.PNG");
frame.setIconImage(icon.getImage());
vraag1 = new Vraag1();
vraag1.setBounds(0,0,1191,677);
frame.add(vraag1);
paneel = new MainPanel();
paneel.setBounds(0,0,1191,677);
frame.add(paneel);
start = new StartScherm();
start.setBounds(0,0,1191,677);
frame.add(start);
frame.setVisible(true);
}
}

Removing JPanel from a JFrame

I am trying to remove a JPanel not hide it but i can't find anything that works.
This is the code in the panel that needs to remove itself when a button is pressed:
play.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Frame frame = new Frame(); //referencing to my JFrame class (this class is a JPanel)
//need to remove this panel on this line
frame.ThreeD(); // adds a new panel
}
});
UPDATED
This is the full code:
package ThreeD;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.UIManager;
import Run.Frame;
public class Launcher extends JPanel{
private JButton play, options, help, mainMenu;
private Rectangle rplay, roptions, rhelp, rmainMenu;
private int buttonWidthLocation, buttonWidth, buttonHeight;
private int width = 1280;
public Launcher() {
this.setLayout(null);
drawButtons();
}
private void drawButtons() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch(Exception e) {
e.printStackTrace();
}
play = new JButton("Play");
options = new JButton("Options");
help = new JButton("Help");
mainMenu = new JButton("Main Menu");
buttonWidthLocation = (width / 2) - (buttonWidth / 2);
buttonWidth = 80;
buttonHeight = 40;
rplay = new Rectangle(buttonWidthLocation, 150, buttonWidth, buttonHeight);
roptions = new Rectangle(buttonWidthLocation, 300, buttonWidth, buttonHeight);
rhelp = new Rectangle(buttonWidthLocation, 450, buttonWidth, buttonHeight);
rmainMenu = new Rectangle(buttonWidthLocation, 600, buttonWidth, buttonHeight);
play.setBounds(rplay);
options.setBounds(roptions);
help.setBounds(rhelp);
mainMenu.setBounds(rmainMenu);
add(play);
add(options);
add(help);
add(mainMenu);
play.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Frame frame = new Frame();
//need to remove this panel here
frame.ThreeD();
}
});
options.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("options");
}
});
help.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("help");
}
});
mainMenu.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("mainMenu");
}
});
}
}
And this is my Frame class:
package Run;
import javax.swing.*;
import ThreeD.Display;
import ThreeD.Launcher;
import TowerDefence.Window;
import java.awt.*;
import java.awt.image.BufferedImage;
public class Frame extends JFrame{
public static String title = "Game";
/*public static int GetScreenWorkingWidth() {
return java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds().width;
}*/
/*public static int GetScreenWorkingHeight() {
return java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds().height;
}*/
//public static Dimension size = new Dimension(GetScreenWorkingWidth(), GetScreenWorkingHeight());
public static Dimension size = new Dimension(1280, 774);
public static void main(String args[]) {
Frame frame = new Frame();
System.out.println("Width of the Frame Size is "+size.width+" pixels");
System.out.println("Height of the Frame Size is "+size.height+" pixels");
}
public Frame() {
setTitle(title);
setSize(size);
setResizable(false);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ThreeDLauncher();
}
public void ThreeDLauncher() {
Launcher launcher = new Launcher();
add(launcher);
setVisible(true);
}
public void TowerDefence() {
setLayout(new GridLayout(1, 1, 0, 0));
Window window = new Window(this);
add(window);
setVisible(true);
}
public void ThreeD() {
BufferedImage cursor = new BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB);
Cursor blank = Toolkit.getDefaultToolkit().createCustomCursor(cursor, new Point(0, 0), "blank");
getContentPane().setCursor(blank);
Display display = new Display();
add(display);
setVisible(true);
display.start();
}
}
Basically - you are creating new instance of Frame in line:
Frame frame = new Frame(); //referencing to my JFrame class (this class is a JPanel)
New instance of Frame is not visible, and you're try to remove your Launcher from not visible new Frame. But this is wrong - you should remove Launcher from Frame that you created previously in main function (that is: parent of Launcher component).
Here goes an example:
public class TestFrame extends JFrame {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
TestFrame frame = new TestFrame();
frame.getContentPane().add(new MyPanel(frame));
frame.setSize(200, 200);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
And MyPanel class:
public class MyPanel extends JPanel {
public MyPanel(final TestFrame frame) {
JButton b = new JButton("Play");
add(b);
b.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Container pane = frame.getContentPane();
pane.remove(MyPanel.this);
JPanel otherPanel = new JPanel();
otherPanel.add(new JLabel("OtherPanel"));
pane.add(otherPanel);
pane.revalidate();
}
});
}
}
In your example you should add a reference to Frame in your Launcher constructor:
public Launcher(Frame frame) {
this.frame = frame;
...
Init Launcher:
public void ThreeDLauncher() {
Launcher launcher = new Launcher(this);
and use:
play.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//need to remove this panel here
frame.getContentPane().remove(Launcher.this);
frame.ThreeD();
}
});
Say your panel is myPanel you can remove it from the main frame by:
frame.getContentPane().remove(myPanel);

GUI multiple frames switch

I am writing a program for a black jack game. It is an assignment we are not to use gui's but I am doing it for extra credit I have created two frames ant they are working. On the second frame I want to be able to switch back to the first when a button is pressed. How do I do this?
first window.............
import javax.swing.* ;
import java.awt.event.* ;
import java.awt.* ;
import java.util.* ;
public class BlackJackWindow1 extends JFrame implements ActionListener
{
private JButton play = new JButton("Play");
private JButton exit = new JButton("Exit");
private JPanel pane=new JPanel();
private JLabel lbl ;
public BlackJackWindow1()
{
super();
JPanel pane=new JPanel();
setTitle ("Black Jack!!!!!") ;
JFrame frame = new JFrame("");
setVisible(true);
setSize (380, 260) ;
setLocation (450, 200) ;
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE) ;
setLayout(new FlowLayout());
play = new JButton("Start");
exit = new JButton("exit");
lbl = new JLabel ("Welcome to Theodores Black Jack!!!!!");
add (lbl) ;
add(play, BorderLayout.CENTER);
play.addActionListener (this);
add(exit,BorderLayout.CENTER);
exit.addActionListener (this);
}
#Override
public void actionPerformed(ActionEvent event)
{
// TODO Auto-generated method stub
BlackJackWindow2 bl = new BlackJackWindow2();
if (event.getSource() == play)
{
bl.BlackJackWindow2();
}
else if(event.getSource() == exit){
System.exit(0);
}
}
second window....
import javax.swing.* ;
import java.awt.event.* ;
import java.awt.* ;
import java.util.* ;
public class BlackJackWindow2 extends JFrame implements ActionListener
{
private JButton hit ;
private JButton stay ;
private JButton back;
//private JLabel lbl;
public void BlackJackWindow2()
{
// TODO Auto-generated method stub
JPanel pane=new JPanel();
setTitle ("Black Jack!!!!!") ;
JFrame frame = new JFrame("");
setVisible(true);
setSize (380, 260) ;
setLocation (450, 200) ;
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE) ;
setLayout(new FlowLayout());
hit = new JButton("Hit");
stay = new JButton("stay");
back = new JButton("return to main menu");
// add (lbl) ;
add(hit, BorderLayout.CENTER);
hit.addActionListener (this) ;
add(stay,BorderLayout.CENTER);
stay.addActionListener (this) ;
add(back,BorderLayout.CENTER);
back.addActionListener (this) ;
}
#Override
public void actionPerformed(ActionEvent event)
{
// TODO Auto-generated method stub
BlackJackWindow1 bl = new BlackJackWindow1();
if (event.getSource() == hit)
{
//code for the game goes here i will complete later
}
else if(event.getSource() == stay){
//code for game goes here i will comeplete later.
}
else
{
//this is where i want the frame to close and go back to the original.
}
}
}
The second frame needs a reference to the first frame so that it can set the focus back to the first frame.
Also your classes extend JFrame but they are also creating other frames in their constructors.
A couple of suggestions:
You're adding components to a JPanel that uses FlowLayout but are using BorderLayout constants when doing this which you shouldn't do as it doesn't make sense:
add(play, BorderLayout.CENTER);
Rather, if using FlowLayout, just add the components without those constants.
Also, rather than swap JFrames, you might want to consider using a CardLayout and swapping veiws in a single JFrame. For instance:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class FooBarBazDriver {
private static final String INTRO = "intro";
private static final String GAME = "game";
private CardLayout cardlayout = new CardLayout();
private JPanel mainPanel = new JPanel(cardlayout);
private IntroPanel introPanel = new IntroPanel();
private GamePanel gamePanel = new GamePanel();
public FooBarBazDriver() {
mainPanel.add(introPanel.getMainComponent(), INTRO);
mainPanel.add(gamePanel.getMainComponent(), GAME);
introPanel.addBazBtnActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
cardlayout.show(mainPanel, GAME);
}
});
gamePanel.addBackBtnActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
cardlayout.show(mainPanel, INTRO);
}
});
}
private JComponent getMainComponent() {
return mainPanel;
}
private static void createAndShowUI() {
JFrame frame = new JFrame("Foo Bar Baz");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new FooBarBazDriver().getMainComponent());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}
class IntroPanel {
private JPanel mainPanel = new JPanel();
private JButton baz = new JButton("Baz");
private JButton exit = new JButton("Exit");
public IntroPanel() {
mainPanel.setLayout(new FlowLayout());
baz = new JButton("Start");
exit = new JButton("exit");
mainPanel.add(new JLabel("Hello World"));
mainPanel.add(baz);
mainPanel.add(exit);
exit.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Window win = SwingUtilities.getWindowAncestor(mainPanel);
win.dispose();
}
});
}
public void addBazBtnActionListener(ActionListener listener) {
baz.addActionListener(listener);
}
public JComponent getMainComponent() {
return mainPanel;
}
}
class GamePanel {
private static final Dimension MAIN_SIZE = new Dimension(400, 200);
private JPanel mainPanel = new JPanel();
private JButton foo;
private JButton bar;
private JButton back;
public GamePanel() {
foo = new JButton("Foo");
bar = new JButton("Bar");
back = new JButton("return to main menu");
mainPanel.add(foo);
mainPanel.add(bar);
mainPanel.add(back);
mainPanel.setPreferredSize(MAIN_SIZE);
}
public JComponent getMainComponent() {
return mainPanel;
}
public void addBackBtnActionListener(ActionListener listener) {
back.addActionListener(listener);
}
}
Since I had to test it myself if it is in fact so easy to implement, I built this simple example. It demonstrates a solution to your problem. Slightly inspired by #jzd's answer (+1 for that).
import java.awt.Color;
import java.awt.HeadlessException;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class FocusChangeTwoFrames
{
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
createGUI();
}
});
}
private static void createGUI() throws HeadlessException
{
final JFrame f2 = new JFrame();
f2.getContentPane().setBackground(Color.GREEN);
final JFrame f1 = new JFrame();
f1.getContentPane().setBackground(Color.RED);
f1.setSize(400, 300);
f1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f1.setVisible(true);
MouseListener ml = new MouseAdapter()
{
#Override
public void mousePressed(MouseEvent e)
{
if(f1.hasFocus())
f2.requestFocus();
else
f1.requestFocus();
}
};
f1.addMouseListener(ml);
f2.setSize(400, 300);
f2.setLocation(200, 150);
f2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f2.setVisible(true);
f2.addMouseListener(ml);
}
}
Enjoy, Boro.

Categories