wait for user input in swing - java

I have a few classes that use swing GUI and one JFrame that displays all of the GUI and all of GUI have an action listener for the Jbuttons and an ItemListener for the Jcheckboxes that cause various things to happen. Some of these buttons and checkboxes are other sub-classes that extend them.
when I do this
Public class SomeClass{
SomeClass(){
// some code here
methodCalled();
}
public void methodCalled(){
//more code here
new BazarGui();
new MapGui();
}
}
How do I actually get bazar GUI to wait for the user to click some buttons or checkboxes with out having the program go right to map GUI? they both work fine on their own but when one is called after the other only the second one shows. Would make the GUIs for the bazaar and map be JDialogs as opposed to JPanels and then adding them to the JFrame solve this problem?

Related

Open elements and struct of jFrame in another like a menu

i have 5 jFrames in my java project. And i want to make like a Main Menu.
I mean, i want that the program starts with a jFrame and when i click a button insteand of open the jFrame, all the elements like labels, buttons and tables are being shown in my principal jFrame.
And if i click other button the main frame will clean and charge other jframe.
It is possible? im programming with java jdk 8 and netbeans.
Thanks
Edit:
I think who marked duplicate didn't understand my question. I don't want to open or close the frame, or other frames, I want to load the structure and components of several in the same frame. Please read my question before you start complain that is duplicated
i have 5 jFrames in my java project.
And that's a problem.
And i want to make like a Main Menu. I mean, i want that the program starts with a jFrame and when i click a button insteand of open the jFrame, all the elements like labels, buttons and tables are being shown in my principal jFrame. And if i click other button the main frame will clean and charge other jframe.
Yes this can be solved by getting the contentPane (usually a JPanel) from the JFrame whose content you want to display within the currently displayed JFrame, and making it the contentPane of the displayed JFrame, for example:
// create the new JFrame, the one whose content you wish to display
NewJFrame newJFrame = new NewJFrame();
// get its contentPane
Container newContentPane = newJFrame.getContentPane();
// add this content pane into the displayed JFrame
displayedJFrame.setContentPane(newContentPane);
// revalidate and repaint the JFrame so that its new data is well displayed
displayedJFrame.revalidate();
displayedJFrame.repaint();
// displayedJFrame.pack(); // and you might need to do this if sizes are way off
But this extra gymnastics is bulky, prone to bugs and unnecessary. You are painting yourself in a corner by having your class extend JFrame, forcing you to create and display JFrames, when often more flexibility is called for. In fact, I would venture that most of the Swing GUI code that I've created and that I've seen does not extend JFrame, and in fact it is rare that you'll ever want to do this. More commonly your GUI classes will be geared towards creating JPanels, which can then be placed into JFrames or JDialogs, or JTabbedPanes, or swapped via CardLayouts, wherever needed. This will greatly increase the flexibility of your GUI coding.
For this situation what I recommend is that you do that, that your GUI classes create JPanels, and that you add the ones that you want to swap to a JPanel that uses a CardLayout. And then whenever you want to show a different "card", call show(...) on the CardLayout object, passing in the JPanel that uses it, as well as the String key that was used when adding the "card" JPanel to the CardLayout-using JPanel. This is all well-explained in the CardLayout Tutorials.
Other useful links:
For rationale on why to avoid manually swapping please see: What's so special about CardLayout vs manual adding/removal of JPanels?
For using a CardLayout to help control a "multi-page" application with multiple classes, please see: How to Integrate Multi-page Java Desktop Application from Multiple GUI Classes

How can I output my data to JPanel from my JFrame

I have a JFrame named MainGUI. Inside of MainGUI I have passed three LinkedList ll1, ll2, ll3.
These LinkedList are full of data and I'm trying to just print one of them on the screen into my JPanel. I'm use to just doing a for loop and using System.out.println to print things out onto the screen.
So right now I have MainGUI which hosts three buttons.
New Tasks In Progress Tasks Completed Tasks
Each button has a different LinkedList ll1, ll2, ll3 etc.
I want to be able to click the button and have the data elements listed below in the JPanelI created which rests under the buttons.
Any help is deeply appreciated.
Since you provided no code, I assume you are having trouble understanding how LinkedList can interact in programs that have a GUI.
First off, when using buttons you always need to instruct them to do something when they are clicked by adding an ActionListener, as explained in this answer.
Secondly, if you want to add the list data to the JPanel, there are a few ways you can do it. A JList, or if you'd like the user to be able to copy and paste the data (I find it to be very handy), a JTextArea, ... Just make sure to call setEditable(false) in order to stop the user from fiddling with the data you provide. Considering a JTextArea, here's what that would look like, if ll1 contained Strings:
Adding somewhere that our JPanel contains a JTextArea:
JTextArea txtArea = new JTextArea();
txtArea.setEditable(false);
panel.add(txtArea);
Now, we order the button to do something when clicked:
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
txtArea.setText(null); //clear out old text
for(String str: ll1) {
txtArea.append(str+"\n");
}
panel.revalidate(); //repaint JPanel
}
});
This way, you can click the button as many times as you want. Note that if you add more content to ll1 after it is displayed it won't get visually updated by itself, you will always need to click the button again or look further into Listeners.
You can try adding a JTextArea or whichever JComponent that suits what you want to display to the JPanel that you want to display the data from. Write the data from your linked list to that JComponent using its method e.g. append() if you're using JTextArea.

Switch between multiple JFrames

I'm relatively new to Java and I'm trying to make some kind of quiz. I created 3 JFrames, all in the same package. On my main frame, there are two buttons (one for the english version and the other one for the german version). I want to switch JFrames after pressing these buttons (so that I can, by pressing "English", see and interact with my english quiz frame). Looking it up didn't help me the slightest, because I'm not really experienced with it. Is it even possible to do it like this? If not, how could I do it?
The standard approach is to use the Card Layout, which allows you to use the same JFrame as you populate it with different things at different points in your application. So initially, your JFrame would show the loading screen, then the user presses a button and you load a new set of components without discarding the current JFrame you have. In some cases, you might also need to make some size adjustments.
It is difficult to say without seeing any code, but usually, what is done is that you do something like so:
new Frame(args);
this.dispose();
The code above assumes that the constructor of Frame takes care of launching and making the components visible. The this.dispose(); disposes of the current JFrame (assuming your class extends JFrame).
You have two buttons in your frame 1 right? So first, double click the button which says "English". Lets say the variable name for that button is jButton1. Inside that button type this.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
this.dispose();
EnglishFrame eng = new EnglishFrame();
eng.setVisible(true);
}
Then double click the other button which says "German" (jButton2). Inside that type this.
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
this.dispose();
GermanFrame german = new GermanFrame();
german.setVisible(true);
}
this.dispose() - This will cause the jFrame window to close
Then you create an object of the other two forms. (In your case the form for English and Germany)
.setVisible(true) - This will show you the form.
Create a single Jframe window. After that create JPanels with all the compenents such as buttons, textfields and labels you want. Make sure the panel is the same size as your Jframe. Panel's work about the same as JFrame's, code wise.
This code will stitch everything together for you:
panel.setSize(Jframe.getSize()) //That wont
panel.add(button); //Just remember you need to add more code to position the buttons correctly.
//If you using netbeans builder:
//You just have to use this one line in the constructor/intialiser method
frame.add(panel); //This will add the panel to the Jframe/Window
//No need to add extra code for positioning.
If you want to swap between the panels. In the button press method, use this
frame.setContentPane(panel); //panel = panel you want to change too.
frame.repaint(); //Ensures that the frame swaps to the next panel and doesn't get stuck.
frame.revalidate(); //Ensures that the frame swaps to the next panel and doesn't get stuck.
When you first start the java application you have to set the content pane or else it will appear as a blank window.
frame.setContentPane(panel); //Starting Panel
frame.setVisible(true); //Make the frame visible
Sorry if the explanation is bad, I don't have enough time to explain it fully.

Save State of Buttons (Whether Enabled Or Disabled), Textboxes, and JComboBox Selections in Netbeans Java?

I have 2 forms in Netbeans, 1 form will launch and the user will input information. Then if the user wants to, will open up the other jframe. The jframe that the user was working on will close. Now from the newly opened jframe, the user decides to go back to the previous frame. The problem is when the user does decide to go back to the previous frame, the text in the textboxes are gone, the buttons that were enabled are disabled, and the combobox selection resets. Does anyone know how I can save the state of all these elements? Thank you.
Would something like this help?
public class MyFrame extends JFrame{
private JCheckBox box1;
public MyFrame(){
box1 = new JCheckBox();
}
public void work(){
if(getbox().isSelected){
//work
}else{
//do else
}
}
public JCheckBox getbox1(){
return this.box1;
}
public JCheckBox setSelectedbox1(boolean set){
getbox1().setSelected(set);
}
If you want to keep that object alive you can use:
myFrame.setVisible(false)
myFrame.setVisible(true)
An application should generally only have a single JFrame.
You can probably use a Card Layout to swap different panels. Read the Swing tutorial on How to Use CardLayout for more information and example.
Other options or to use a JTappedPane or JInternalFrames. The tutorial also has section on these components.

Keyboard input stops working in Swing application (a calculator) after clicking on a JButton

I'm making a calculator using Swing. So far I have created a GUI that consists of a JFrame with BorderLayout, and in its center I put a JPanel that has a JLabel (representing the screen of the calculator) and some JButtons (representing the keys).
I want the calculator to be able to receive input directly from the keyboard, so I included the method addKeyListener in a class that extends JFrame and I put as an argument a reference to an object of a class that implements KeyListener.
When I run the application it accepts keyboard input until I click on one of the JButtons. After that using the keyboard doesn't work anymore.
I suspect the problem is about focus, but it is not a problem that I could fix by clicking anywhere on the application. I added the following code:
setFocusable(true);
to the JFrame but it did not help. I have read that using Key Bindings maybe a better option than using a KeyListener, but I am not really sure about this approach.
Swing components are lightweight and use KeyBindings, where KeyListeners are for AWT components which are heavyweight. and known to have focus issues when mixed with Swing components. Thus I suggest changing to KeyBindings (but I see you have heard of them). You would use them something like:
final JButton b=..;
//method to add keybindings to a JComponent ie JButton,JPanel,JTextField etc
private void addKeyBindings(JComponent jc) {
//not the getInputMap(..) call it could also be JComponent.WHEN_FOCUSED etc
jc.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("D"), "D pressed");
jc.getActionMap().put("D pressed", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent ae) {
//do something when d is pressed
b.doClick();
}
});
}
For general knowledge a very hacky solution would be calling requestFocusInWindow() on the component to which the listeners are attached whenever focus is lost (like after button click etc)
It's another hacky approach, but you could alter the properties of the JButton when you create it so that it can't take the focus in the first place i.e:
myJbutton.setFocusable(false);
This worked for me.

Categories

Resources