So I have been coding Java for a few months now, and I have been using JOptionPane to display text and variables in my games. I want to upgrade to a single window like a normal game, but I want to only focus on simple buttons and text on the screen. I have tried learning JFrame and ActionListsner, but I failed to completley figure it out. JFrame really confused me.
My question is this: Is there an easier way beside JFrame to just have a window that I can have simple text, buttons and TextFields without the hassle of opening a bunch of windows with JOptionPane, making crap loads of ActionListeners with JFrame or having to get into GUI? If not, where can I find help on how to make games with JFrame?
You should be using a JFrame. Trust me, they aren't that hard to use. Using a JFrame, you could create multiple panels and switch between them using CardLayout.
Since you said you aren't sure about how JFrame works, I gave a short introduction to them at the end of this post. But first, lets first talk about how to solve your problem.
Switching Panels via CardLayout
When you want to switch whats being viewed in the window completely, you're gonna want an entirely different panel for that specific purpose (for example, one for Main Menu, and one for the game). CardLayout was created for this.
You specify a "deck" panel. This panel will hold all the other panels you wanna switch between (cards):
CardLayout layout = new CardLayout();
JPanel deck = new JPanel();
deck.setLayout(layout);
You'll need to maintain a reference to the layout (via a variable) so you can switch between panels.
Now that we have a "deck" panel, we need to add some cards. We do this by creating more JPanels, and specifying a name when we add it to the frame (constraints):
JPanel firstCard = new JPanel();
JPanel secondCard = new JPanel();
deck.add(firstCard, "first");
deck.add(secondCard, "second");
The first card added to the deck will always be the first one to show.
Once you have all your cards added, you can switch between them by calling layout.show(deck, "second");. This is how you use CardLayout to manage multiple panels within your container.
Creating listeners
There's no easier way to manage it. It only gets harder from there (bindings - I highly suggest you look into them). For listeners, there are 2 steps:
Create the listener
Add it to the component
Could be 1 if you created the listener "on the fly" using a lambda:
JButton button = new JButton();
//Java 8+
button.addActionListener(event -> {
//whenever you click the button, code in here triggers
});
For those who don't use Java 8, you will need to use an anonymous class:
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//whenever you click the button, code in here triggers
}
});
Only some components support ActionListener. Anything that extends AbstractButton, like JMenuItem, JButton, JRadioButton, and more will support ActionListeners. JTextField also supports it, even though it's not an AbstractButton. Every component supports KeyListener, though, which can also be used to listen for input events from the user.
If you have any questions about this, let me know and I'll be glad to answer them.
Using Swing Components
JFrame
You initialize a JFrame:
JFrame frame = new JFrame();
You then want to set the defaultCloseOperation, to determine what happens when the window closes:
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
There are different options, but EXIT_ON_CLOSE will terminate your program after closing the window. If you do not set the defaultCloseOperation, then your window will close, but your program will still be running. BIG NO NO. If you don't want the entire program to exit when you close the frame, use DISPOSE_ON_CLOSE.
After you have the close operation, you might be tempted to set the size. This is bad practice. Your frame should size depending on what's inside of it. To do this, you add your components to your frame, then call pack():
JButton button = new JButton("Button");
frame.add(button);
//add other components
frame.pack();
This will ensure your frame sizes to fit what's inside of it. You should always design GUI from the inside out, to ensure you always have enough room for what you need.
Containers
JFrame is a Container. Containers are just components that hold other components. All containers should have a LayoutManager to manage how components are laid out and, if needed, sized. JFrame isn't the only container though. JPanel is actually a container that's meant to be added to another container (or window). You can add things to a JPanel, then add that panel to another container. This is how you keep things neatly organized. Containers are pretty straight forward, so there's not much to talk about.
Content Pane
When you create a JFrame, it comes along with something called the contentPane. It is a JPanel nested within the JFrame. When you do frame.add(button), you'll notice that add actually refers to the contentPane:
//in Container class
public Component add(Component comp) {
addImpl(comp, null, -1); //where it's added
return comp;
}
//In JFrame class (overriding)
protected void addImpl(Component comp, Object constraints, int index) {
if(isRootPaneCheckingEnabled()) {
getContentPane().add(comp, constraints, index); //adds to content pane instead
} else {
super.addImpl(comp, constraints, index); //if root panes were not supported, which they currently are
}
}
You too can grab the contentPane from the frame using
Container pane = frame.getContentPane();
The reason why the contentPane is in Container form is to ensure a strong API (if JPanels were no longer going to be used for this, we wouldn't need to worry about changing the method type of getContentPane). Although, since it IS a JPanel, you can cast it back to it's original form:
JPanel pane = (JPanel) frame.getContentPane();
Although it's usually not needed. Using it as a Container tends to work just fine.
Layouts
JFrame, by default, uses BorderLayout, but you can change this by calling the setLayout method of the container:
FlowLayout layout = new FlowLayout();
frame.setLayout(layout);
Before jumping into layouts, I want to mention that JPanels use FlowLayout as default, except for the frame's default contentPane, which you can also change by doing frame.setContentPane(...). The contentPane uses BorderLayout as default.
Now, lets talk about a couple, starting with the JFrame default: BorderLayout.
Some layouts require what are called constraints, which tell the layout how to handle that specific component that's being added. You specify these constraints when you add the component to the container:
frame.add(button, BorderLayout.SOUTH);
BorderLayout is pretty simple. You have 5 options: NORTH, SOUTH, EAST, WEST, or CENTER. (there are other values such as PAGE_START, which are interchangeable. It's best to just use the easier form)
All constraints for BorderLayout are static field variables that you call similar to how I did. BorderLayout is actually an easy layout to use, seeing how there's not much to it. Even though it's simplicity limits what you can do (you can only put it in a certain position like NORTH), you'd usually combine layouts to get the result you want. This layout can be very powerful when combined with other layouts.
FlowLayout is pretty straight forward, as well as other layouts out there. One of the less straight-forward ones would be GridBagLayout, which can be a really flexible layout. It can also be pretty complex, though, as the documentation even states.
When using GridBagLayout, you need to create a constraints object: GridBagConstraints. To work with GridBagLayout, you set the constraints using the constraints object, then add both the component and the constraints to the container:
frame.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
JButton button = new JButton("yoyoyo");
frame.add(button, gbc);
Even if we don't adjust the constraints, we MUST still specify it when adding a component to the container.
Lets say we had 4 buttons, and we wanted to put them side by side. You would adjust the constraint's gridx and gridy values:
JButton button = new JButton("1");
JButton button2 = new JButton("2");
JButton button3 = new JButton("3");
JButton button4 = new JButton("4");
frame.add(button, gbc);
gbc.gridx = 1; //or gridx += 1, or gridx = 1. gridx starts at 0
frame.add(button2, gbc);
gbc.gridx = 0; //must reset the value back to normal
gbc.gridy = 1;
frame.add(button3, gbc);
gbc.gridx = 1;
//since gridy already == 1, no need to change it
frame.add(button4, gbc);
We can use the same constraints object, as long as we reset values when needed.
GridBagLayout starts centered, and works from the center out, unless you specify otherwise. You cannot skip grid spaces either. Also, as you'll notice, all your buttons will be touching. If you wanted a little space between each component, you can set the insets of the constraints:
int top = 5, left = 5, bottom = 1, right = 1;
gbc.insets.set(top, left, bottom, right);
There is a LOT more to this layout, and sadly I just don't feel this is the best place to give the explanation to it all, seeing how it's already documented (I even added the link).
There are many other layouts out there. Get familiar with as many as you possibly can, then find the ones that'll help suit your needs. Positioning should ALWAYS rely on the LayoutManager that's being used. As for sizing, that kinda depends on the layout you're using.
I would highly recommend using JavaFX. It's a very nice fairly easy to use GUI system with nice looking and customizable controls. JavaFX events (basically ActionListeners) are pretty straightforward as well.
This should get you started: http://docs.oracle.com/javase/8/javafx/get-started-tutorial/get_start_apps.htm#JFXST804
I believe CardLayout is what you're looking for. With it, the programmer can choose which JPanels should be visible in the JFrame. Upon user interaction you can switch the contents of the JFrame without new JFrames or JOptionPanes popping up.
Is there an easier way than using Swing for simple games? Swing has a learning curve, but with the right resources and practice you can learn to build simple GUI applications pretty quickly.
I am learning to use swing so please bear with me. Have a look at the attached screenshot:
These are JLabels within a JLabel within a JFrame. I would like to move these inner JLabel (which are randomly generated in size and color at runtime) to the very bottom as though they were books on a shelf. I know about Layout managers, though I can't quite seem to find the proper one to do what I want. This screenshot shows the result of specifying none, thus it should default to FlowLayout.
The inner JLabels are just .add()ed without any placement done. SetLocation appears to do nothing whatsoever.
Can you help me out?
If I were you I'd add put those JLabels inside of a JPanel with a boxlayout then align that with a border layout. Here is some code to help you out:
JLabel outer = new JLabel();
outer.setLayout(new BorderLayout(0,0));
/** Add inner JLabels here. The other you add them is the order they will appear from to right**/
JPanel bookshelf = new JPanel();
bookshelf.setLayout(new BoxLayout(toolbar, BoxLayout.X_AXIS));
//Add your jlabels to the bookshelf
outer.add(bookshelf, BorderLayout.SOUTH);
Here is a great tutorial on layout managers.
Also here is a UI I designed which is similar to what I think you want.
Hope this helps you out.
I am trying to create a JScrollPane within one of the tabs to my JTabbedPane. I tried what I though would work which was this:
pane.add("Main", mainGame);// These are my other tabs
pane.add("Upgrades", upgradeScreen); //the JTabbedPane
pane.add("Credits", creditsTab);
upgradeScreen.setLayout(null); //The null layout
lblMoney2.setBounds(10, 11, 277, 22);
upgradeScreen.add(lblMoney2); // A simple JLabel
scrollPane.add(upgradeScreen); //my JScrollPane
Where pane is my JTabbedPane and scrollPane is my JScrollPane. This simply got rid of my upgradesScreen tab. I kind of expected this but I did not know what else to do. If more code is needed for you to figure it out, tell me and i'll put it in, otherwise, thanks for the help!
Don't us JScrollPane#add, instead you want to use JScrollPane#setViewportView
Check out How to use ScrollPane more details.
Advise- Don't use null layouts, they limit the ability for your application to run on multiple platforms. Instead take the time to learn how layout managers work
This simply got rid of my upgradesScreen tab.'
yes, because no component can have two parents at once. You added upgradeScreen to JTabbedPane first and then again added it to a JScrollPane. The Component's add(component) function will eventually call the addImpl(component) function: which will remove the component from it's old parent and add it to the new parent.
However:
You need to add the JScrollPane to the JTabbedPane instance.
The component which you wish to scroll set it as a view to JScrollPane using the setViewportView(component) function. for your context it is the upgradeScreen
I have made a simple GUI using a GridLayout(5,3) , it is action performed and it implements action listener as well. The are some calculation and algorithms that working according to what inputs or buttons the user provides. Everything works just fine up to this point.
At some point in my code, the user gets a pop up massage that he is correctly logged in to the system using this common method JOptionPane.showMessageDialog(....) . All i want is, after he press the OK button, is to create an additional form that pop ups, and looks similar to the one above i made with GridLayout(5,3) so that my user can store additional info about him.
I really cant get it to work, and i have no idea how to start this.
Any ideas are very welcomed! Cheers and thanks in advance :)
if add this:
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container pane = getContentPane();
GridLayout grid=new GridLayout(10,1);
pane.setLayout(grid);
it only adds more lines to my gridlayout. And all above buttons and labels remains. How can i get rid of the previous labels and buttons?
You state:
if add this:
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container pane = getContentPane();
GridLayout grid=new GridLayout(10,1);
pane.setLayout(grid);
it only adds more lines to my gridlayout. And all above buttons and labels remains. How can i get rid of the previous labels and buttons?
You have at least three options if you want to swap "views" on the JFrame.
If you want to use the same GUI with the same JTextComponents but have the components empty of text, then you'll need to go through your text components and call setText("") on all of them. If you want to keep the same JButtons and labels but change their text, then similarly you will need to go through all of them calling setText("something else").
If you want totally new components to replace the old ones, the most straight forward way I believe is to use a CardLayout to hold your JPanel that has all your components. When you want to swap the JPanel for another, make sure that the new JPanel has been added to the CardLayout-using JPanel and then call next() on the CardLayout object.
Another way is to manually swap out JPanels held by the JFrame's contentPane by calling removeAll() on the contentPane, then add(nextJPanel) on it, then revalidate(), then repaint().
I have Java application which adds JTextFields # runtime to JPanel. Basically user clicks a button and new JTextField is added, clicks again added again...
Each new JTextField is directly below the previous one. Obviously I run out of space pretty soon so I'm trying to use JScrollPane and thats where the hell begins, because it just doesnt work no matter what I try.
Right click on JPanel and Enclose in Scroll Pane. Didnt work.
After reading some examples I realized I must have JPanel as an argument for JScrollPane constructor. Which I did via right clicking on ScrollPane and CustomizeCode. Because apparently auto-generated code is protected in NetBeans and I cannot just change all those declarations, etc. manually. Still doesnt work.
I did try to set PreferedSize to null for JPanel and/or JScrollPane, didnt help.
JScrollPane is a child of lets call it TabJPanel (which in turn is a tab of TabbedPane). I tried to mess with their relationships, basically trying every possible way of parentship between JFrame, JPanel(holding textfields), TabJPanel and JScrollPane, but nothing worked.
I also made VerticalScrollBar "always visible" just in a case. So I see the scrollbar, it's just that populating that JPanel with JTextFields does not affect it.
When there are too many JTextFields I they go "below" the bottom border of JPanel and I cannot see them anymore.
Code for adding new JTextFields is like this, in a case it's relevant.
JTextField newField = new JTextField( columns );
Rectangle coordinates = previousTextField.getBounds();
newField.setBounds(coordinates.x , coordinates.y + 50, coordinates.width, coordinates.height);
JPanel.add(newField);
JPanel.revalidate();
JPanel.repaint();
Sorry for a long post I'm just trying to provide as much info as possible, because being newbie I dont know whats exactly relevant and whats not. Thanks in advance :)
As there is another answer now, I'm adding my suggestion too.
This sounds exactly like a problem to use a JTable with a single column. JList is not yet editable (and might never be).
JTable would handle the layout problems for you, and you can easily access the values via the table.
Use your own TableModel (a simple Vector should be sufficient in your case), and add values to it.
An option you have is to utilize a LayoutManager, instead of setting the bounds directly on the components. To test this, a simple single column GridLayout with the alignment set to vertical should prove the concept.
panel.setLayout(new GridLayout(0,1));
zero in the rows param allows for rows to be added to the layout as needed.
I do this way to add a scrollpane, create a panel and fill it with few components, then create a scrollpane in the component you want to add it, cut and paste the panel in which all your details will fall in and resize the scrollpane.Because the components take a larger space than the one visible right click on the scrollpane and select design this container, there you can increase the size of the scrollpane and add as many components as you have.