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

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

Related

Java KeyBindings not reacting on JPanel

I have previously used Java's KeyListener, but as my programs are demanding more I have gotten the recommendation to switch over to KeyBinds.
First of all I have tried to add keybindings to JFrame which didn't work ( I don't understand what JComponent I need to use. ). Therefore I tried moving the program over to a JPanel and then adding it to a JFrame, however the Key bind do not react when the desired button is pressed (in this case it's the "1" button);
In the method call I have set the action to be Print "Hi". Here is the code:
public class Panel extends javax.swing.JPanel {
JPanel Panel = new JPanel();
/**
* Creates new form Panel
*/
public Panel() {
addKeyBinding(Panel, KeyEvent.VK_1, "1Button", (evt)->{
System.out.println("Hi");
});
initComponents();
}
.....
And here is the method
.....
public static void addKeyBinding(JComponent comp, int keyCode, String id, ActionListener actionListener){
InputMap im = comp.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
ActionMap ap = comp.getActionMap();
im.put(KeyStroke.getKeyStroke(keyCode, 0, false),
id);
ap.put(id, new AbstractAction(){
#Override
public void actionPerformed(ActionEvent e) {
actionListener.actionPerformed(e);
}
});
}
What am I doing wrong? Thanks!
The key bindings are for your form panel, right? I think you're misunderstanding a few concepts about classes and objects. Also it's hard to help without seeing the full code. But your error is very likely caused by this line:
addKeyBinding(Panel, KeyEvent.VK_1, "1Button", ...
which should be:
addKeyBinding(this, KeyEvent.VK_1, "1Button", ...
The variable Panel should be replaced with the keyword this thus referencing the actual form panel.
It also should be created wherever you're creating your window so this line can also be removed:
JPanel Panel = new JPanel();
There are many things wrong with your code. I can't imagine the code in the first snippet even compiles. You are trying to name a variable the same as your classname.
Your class has no reason to extend JPanel since it isn't a new type of JPanel. Simply remove your extends. Then change the first line to:
JPanel panel = new JPanel();
Then pass lower-case panel to the addKeyBinding method.
If for some strange reason you want to keep your class extending JPanel then pass this as the first parameter to addKeyBinding as /u/tiiv said and remove the JPanel Panel = new JPanel line since that isn't needed (as you have it written now your class is the JPanel).
As far as which component to use JFrame is a top-level container so that is usually your main application window. And then you put JPanel and other components in the JFrame. There are actually 4 top-level containers in swing (JFrame, JWindow, JDialog, and JApplet) but JFrame is generally the one you will use as your main app window.
I hope that helps.

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.

Change JPanel contents in JDialog

I'm trying to add components to a JDialog after it has been created and displayed. Nothing I try makes the changes actually update to the screen, and I've read and applied every question I could find related to this.
This example code creates a modal JDialog showing the word "test". I cannot get it to display "test2". Almost exactly the same code but with a JFrame instead of a JDialog behaves as I expect, so I don't understand. I'm new to Java and especially to swing.
import javax.swing.*;
public class DialogTester {
public static void main(String[] args) {
new DialogTester();
}
public DialogTester() {
JFrame jframe = new JFrame();
jframe.setVisible(true);
JDialog jdialog = new JDialog(jframe,true);
JPanel jpanel = new JPanel();
jpanel.add(new JLabel("test"));
jdialog.add(jpanel);
jdialog.setVisible(true);
jpanel.add(new JLabel("test2"));
jpanel.revalidate();
jdialog.getContentPane().validate();
jdialog.pack();
}
}
I also tried calling
jdialog.repaint();
which did nothing.
You created a modal dialog. So, as soon as you call setVisible(true), the following instructions wait for the dialog to be closed to be executed.
Put the code adding a label before the dialog is made visible, or put it in an event handler called after the dialog is shown, for example, when you click on a button in this dialog.

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)

Swing keyboard not responding

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.

Categories

Resources