Swing keyboard not responding - java

I'm using a KeyListener on a JFrame object which I set as FullScreenWindow, something like this code:
class Game{
private GraphicsDevice device;
...
public void run(){
JFrame frame = new JFrame();
frame.addKeyListener(new MarioKeyListener());
device.setFullScreenWindow(frame);
}
...
}
And it works fine if I just create a Game object in my main method and call run().
However I want to do this inside the mousePressed() function of a MouseAdapter which I added to another JFrame-s MenuItem. The result is that the program runs as normal but doesn't accept any keyboard input.
JMenu gamemenu = new JMenu("Game");
JMenuItem newGame = new JMenuItem("New Game");
newGame.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e){
Game g = new Game();
g.run();
}
});
gamemenu.add(newGame);
I think My frame object is not in focus, but calling setFocusable(true) and requestfocusinwindow() did not help.
If anyone knows whats wrong or how to fix this, help would be greatly appreciated...
Tomi

requestFocusInWindow()..
Requests that this Component get the input focus, if this Component's top-level ancestor is already the focused Window.
Are you checking the return value? I suspect it is failing because the new window is not the focused component at the moment the method is called.
If that is the case, the answer might be found in similar fashion to the dialog focus strategy of adding a RequestFocusListener to the mix.

Related

Java - How to close a window on open of a dialog

i created a dialog class that opens when a JLabel is clicked but i want the main window to close when the label is clicked and a more bigger issue is that the label is in a class that extends a JPanel now if the label is clicked the panel goes as in setVisible(false), do you get what i mean, but when i tried to use polymorphism in the panel class to obtain both the main window class and the dialog it proved successful but when the label is clicked an new similar main
wnidow pops up and immediately disappears. ie it duplicates the main window, i know that this problem might look like a chalenge because there are no codes, the file is too complicated but i kmow there is a pro out there who can get a picture of what this code is and help me, thank you
"an new similar main wnidow pops up and immediately disappears. ie it duplicates the main window, " -
Seeing how your JPanel is a separate class, it seems to me like you have a referencing issue. I bet what you did was create a new MainWindow so that you could reference it. Like
mousePressed(MouseEvent e) {
MainWindow window = new MainWindow();
window.dispose();
}
That would definitely explain the the issue. There are a few ways to deal with this. I'm going to give you the rookie way, since you still seem like a rook :D You'll probably learn more proper ways as your learning gets deeper. So you can do something like below, where you pass the reference of the MainWindow to the JPanel class, instead of creating a new MainWindow
public class MyPanel extends JPanel {
private MainWindow window;
public MyPanel(final MainWindow window) {
this.window = window;
JLabel label = new Label();
label.addMouseListener(new MouseAdapter(){
public void mousePressed(MouseEvent e) {
window.setVisible(false); // or dispose
}
});
}
}
When you instantiate the MyPanel, pass the reference of the MainWindow to the MyPanel, like MyPanel panel = new MyPanel(MainWindow.this);

Cannot use JFrame method from mouselistener

I am currently trying developing simple game, but having some trouble with making game menu. I use JPanel for each states in game menu such as instruction or option and have method in parent JFrame to shuffle them according to what item user click on the menu.
My code is like this (without some simple method like setSize() or setVisible() ).
public class Game extends JFrame{
private JPanel mainPanel = new MainPanel();
private JPanel helpPanel; = new HelpPanel();
private JPanel optionPanel = new OptionPanel();
private JPanel currentPanel = new JPanel();
public Game(){
add(currentPanel);
}
public void changePanel(int destination){
remove(currentPanel);
if(destination==MAIN_PANEL)
currentPanel = mainPanel;
else if(destination==HELP_PANEL)
currentPanel = helpPanel;
else if(destination==OPTION_PANEL)
currentPanel = optionPanel;
add(currentPanel);
}
Everything work perfectly except when I try to use changePanel method in mouselistener, it wasn't responded anything. Then I try some simple method like this.
....
public void mouseClicked(MouseEvent e) {
removeAll();
JOptionPane.showConfirmDialog(null, "Pop when click anywhere.");
}
....
I expected my JFrame would be cleared and the dialog poped. The dialog does pop but for JFrame. My question is how can I use those simple method from mouselistener.
Sorry for my terrible English. I am now learning both Java and English.
Don't use a MouseListener.
I can't tell exactly what you are doing but you should probably be using either a JMenuBar with menus or JButtons. In any case I suggest you start by reading the Swing tutorial to learn the basics of Swing. There are sections on:
How to Use Menus
How to Use Buttons
to get your started.
Also you should check out the section on Using a Card Layout. This is generally the better approach when you want to remove/add panels from a frame.

Refreshing a JFrame while in an Action Listener

The code snippet below sets text in a JLabel, which is added to a JPanel, which is attached to a JFrame. No matter what I do though (such as repaint(), revalidate(), etc) I cannot get the UI to update the text until the Action Listener is done.
I have never had this problem before, possible because I have never had to have several things happen in a single firing of Action Listener. What am I missing?
TL;DR Why does the following not update the text on the screen until it has finished firing the Action Listener, even if I put in repaint() after each listPanel.add()?
final JFrame guiFrame = new JFrame();
final JPanel listPanel = new JPanel();
listPanel.setVisible(true);
final JLabel listLbl = new JLabel("Welcome");
listPanel.add(listLbl);
startStopButton.addActionListener(new ActionListener(){#Override public void actionPerformed(ActionEvent event){
if(startStopButton.getText()=="Start"){
startStopButton.setVisible(false);
listPanel.remove(0);
JLabel listLbl2 = new JLabel("Could not contact”);
listPanel.add(listLbl2);
JLabel listLbl2 = new JLabel("Success”);
listPanel.add(listLbl2);
}
}
guiFrame.setResizable(false);
guiFrame.add(listPanel, BorderLayout.LINE_START);
guiFrame.add(startStopButton, BorderLayout.PAGE_END);
//make sure the JFrame is visible
guiFrame.setVisible(true);
EDIT:
I attempted to implement SwingWorker, but still the interface is not updating until the action interface finishes firing. Here is my SwingWorker code:
#Override
protected Integer doInBackground() throws Exception{
//Downloads and unzips the first video.
if(cameraBoolean==true)
panel.add(this.downloadRecording(camera, recording));
else
panel.add(new JLabel("Could not contact camera "+camera.getName()));
panel.repaint();
jframe.repaint();
return 1;
}
private JLabel downloadRecording(Camera camera, Recording recording){
//does a bunch of calculations and returns a jLabel, and works correctly
}
protected void done(){
try{
Date currentTime = new Timestamp(Calendar.getInstance().getTime().getTime());
JOptionPane.showMessageDialog(jframe, "Camera "+camera.getName()+" finished downloading at "+currentTime.getTime());
}catch (Exception e){
e.printStackTrace();
}
}
Basically, SwingWorker (as I implemented it) is not properly updating the JPanel and JFrame. If I try to do the repaint in the "done()", they are not updated either. What am I missing?
Additionally, as soon as the JOptionPane displays itself, no more panels can be added to my jframe. I am unsure what is causing that either.
The action listener is being executed on the Event Dispatch Thread. For tasks like that, consider using a SwingWorker.
This would allow you to process your logic without blocking the updates (and thus the repaints) of the JFrame.
At a high level, this is what I mean:
startStopButton.addActionListener(new ActionListener(){#Override public void actionPerformed(ActionEvent event){
if(startStopButton.getText()=="Start"){
// Start SwingWorker to perform whatever is supposed to happen here.
}
You can find some information on how to use SwingWorker here, should you need it.

Accessing a Button from another Object

I am busy doing a school project and hoped some awesome people out there could help me.
I currently have a Main, a Log in GUI and a Search frame (designed with Netbeans Gui dev).
I have an actionPerformed(ActionEvent e) method, where I am struggling is to access the Log in button that is on my Log in GUI. Currently I am doing this.
In my constructor: Declare the Frame. LogInFrame x = new LogInFrame();
In
public actionPerformed(ActionEvent eve)
{
if(eve.getSource()==x.LogInBtn())
{
x.setVisible(false);
}
}
At the moment the button isn't responding, so I was wondering if I was doing anything wrong.
The current Frame is just a standard frame. Really simple
public static void main (String[] args)
{
JFrame LogInFrame = new JFrame ("Log in");
LogInFrame.setSize (300, 300);
JButton close = new JButton ("Hid frame");
LogInFrame.getContentPane ().add (close);
}
}
Thats about everything that is needed. The problem does not lie with the GUI itself as I can run the GUI in netbeans fine. I can use the auto generated actionPerformed method of the button by double clicking on it. But i want to be able to access my GUI's compenents in my main.(tell the button what to do from my main). I have made sure that the button is public and can be accessed. I dont get any physical "coding" errors, the code just doesnt seem to be working (the button isnt responding if I add events from my main)

Problem with setVisible(boolean)

I have a JFrame with some component on it. I want that the frame disappears when i click on a special button for example exit button.
I wrote this code in exit button
this.setvisible(false);
but it only hides the component on it and frame doesn't disappear.
What can I do that when I click on exit button the frame disappears?
Here's an example of a button that hides the frame:
final JFrame frame = new JFrame();
frame.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
final JButton hideButton = new JButton("hide frame");
frame.add(hideButton);
hideButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.setVisible(false);
}
});
frame.setVisible(true);
frame.pack();
In your call this.setVisible(false), this probably refers to the button and not the frame.
You need to call setVisible() on the Frame not the Button.
Also make sure you are calling dispose() on the frame to clean up all resources.
Additionally you should also use
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
during creation of the frame, to make sure the windows is properly closed and disposed when the user clicks the "standard" close button in the upper right corner (on Windows).
This tutorial might also help you understand what's going on better:
http://download.oracle.com/javase/tutorial/uiswing/components/frame.html
call it on JFrame object.
example:
// when exit is pressed
fr.setVisible(false); // fr is a reference to object of type JFrame `

Categories

Resources