Adding a button anywhere in a JPanel - java

Without using the Swing GUI on Eclipse, I've been struggling with adding a button to a JFrame anywhere in the frame (so no BorderLayout.CENTER). I can't get past:
JPanel panel = new JPanel();
JButton OKButton = new JButton("OK");
OKButton.addActionListener(new MyAction());
panel.add(OKButton,BorderLayout.CENTER);
So would something like this be completely redesigned or is there something I'm missing?
EDIT: By Anywhere (as I'm planning to add more than one button/label to a frame), I meant perhaps a coordinate on the frame. So other than dead center, (example) 75% from the left and 25% down.

You can use different Panels with different LayoutMangers to arrange the GUI as you like.
Have a look here for some common LayoutManagers:
http://docs.oracle.com/javase/tutorial/uiswing/layout/using.html
Otherwise you could use the null Layout (panel.setLayout(null)) and place all components by setting the position. But I would recommend you the LayoutMangers

Related

JPanel button is not at the correct place

i made a custom JFrame for the desktop application and i added a JPanel on the very top of the app to serve as a subtitute of the title box. the problem is when i added a button it located right in the middle of the JPanel instead of the usual left top. AND it would not move even if i set it at a different location.
here is the code:
JFrame f = new JFrame("Hello");
f.setResizable(true);
JPanel pa = new JPanel();
JButton btn = new JButton("Exit");
btn.setBackground(Color.white);
btn.setText("Button");
btn.setSize(300, 80);
btn.setLocation(50, 0);
pa.setBackground(Color.red);
pa.setPreferredSize(new Dimension(width,60));
pa.add(btn);
f.setBackground(Color.white);
f.setUndecorated(true);
f.getContentPane().add(pa, BorderLayout.NORTH);
f.setSize(new Dimension(width,height));
f.setLocation(200, 200);
f.setVisible(true);
You use a BorderLayout in the frame. You can do the same thing in the panel.
pa.setLayout(new BorderLayout());
pa.add(btn, BorderLayout.WEST);
In general, setLocation tends to fight against the layout manager, so you usually don't want to use it unless you're going to position everything by hand.
that is one way to do it, but BorderLayout way is not very good way because i also want to add another button next to it.
Then what this might need is a FlowLayout using FlowLayout.LEADING as the alignment.
But as general tips:
Provide ASCII art or a simple drawing of the intended layout of the GUI (showing all components) at minimum size, and if resizable, with more width and height - to show how the extra space should be used.
For better help sooner, post a
Minimal, Complete, and Verifiable example or Short, Self Contained, Correct Example of your attempt.

Java: Upgrading to a single window

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.

Overlap JPanels with WindowBuilder for eclipse

I am using WindowBuilder Pro for eclipse, and I would like to have two Jpanels that perfectly overlap each other. I would then be able to toggle their visibilty based on the selection of a combox box. When I try and acheive this in the gui builder, the first panel gets displaced by the second panel. And advice please?
It is possible using groupLayout, according to the tutorial .
What you must do is add the components to a mother JPanel , and set that panel to use GroupLayout.
Then add the components to the layout as a ParallelGroup in both the horizontal and vertical spacing. This means they will occupy the same X and Y space. Then disable/enable as needed, hiding the JPanels as well.
I believe the way it would work is so:
JPanel panel1, panel2, panel3;
//initialize panel3, etc
panel1=new JPanel();
panel2 = new JPanel();
panel1.add(new JTextField("Panel1"));
panel2.add(new JTextField("PANEL2"));
groupLayout = new GroupLayout(panel3);
panel3.setLayout(groupLayout);
groupLayout.setHorizontalGroup(
groupLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(panel1)
.addComponent(panel2)
);
groupLayout.setVerticalGroup(
groupLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(panel1)
.addComponent(panel2)
);
panel1.setEnabled(false);
panel1.setVisible(false);
then add a jCheckBox with an ActionPerformed method containing:
if(panel1.isEnabled()) {
panel1.setEnabled(false);
panel1.setVisible(false);
panel2.setEnabled(true);
panel2.setVisible(true);
}else
if(panel2.isEnabled()) {
panel2.setEnabled(false);
panel2.setVisible(false);
panel1.setEnabled(true);
panel1.setVisible(true);
}
That produced the desired behaviour for me. You should be able to switch the JComboBox for the JCheckBox fairly easily.
EDIT: Removed the necessity of having "Jpanel of their own". That should not be the case, and the above method allows you to get the benefits of both GroupLayout and CardLayout.
I would like to have two Jpanels that perfectly overlap each other. I would then be able to toggle their visibilty based on the selection of a combox box
See: How to Use Card Layout for an example that does exactly this.
I would like to have two Jpanels that perfectly overlap each other.
I believe the CardLayout is there exactly for that reason.
Basically, you can nest different panels or 'Cards' using the CardLayout and set the appropriate card to be displayed programmatically (on some event).

Difference between a JPanel and a LayerManager

Ok I gather that every JComponent can set its location...bet it JPanel, JButton, JLabel..whatever. It can set its location use .setLocation(x,y).
I have come to suspect that actually when I do
JButton btn = new JButton("Click me!") ;
btn.setLocation(10,200);
I am actually changing the location of a button in a panel, and not in the frame. And if I do
JPanel jPanel = new JPanel();
jPanel.setLocation(10,100);
I am changing the location of jPanel not in the JFrame but in the default JPanel provided by default. So JComponents can change their locations, why not just dump everything directly into a bloody jFrame object? :S
I haven't tried but I believe I can arrange stuff just by using the setLocation(x,y) method..and I guess that'd be a big pain the butt.
This leads to my question..if we can set components location by using the method, what is the LayoutManager for?
Can you please provide example to show the difference?
Can you please provide example to show the difference?
Here is an example of using layouts, as well as a challenge.
The challenge is to make a resizable, PLAF changable version of that UI using setLocation()/setBounds().
If you (or anyone) can manage it (in code that is small enough to post to the thread), I'll contribute 500 bounty points to the answer.

Can you set a permanent size for a JPanel inside of a JFrame?

My current problem is that I have a JFrame with a 2x2 GridLayout. And inside one of the squares, I have a JPanel that is to display a grid. I am having a field day with the java swing library... take a look
Image
Java is automatically expanding each JLabel to fit the screen. I want it to just be those blue squares (water) and the black border and not that gray space. Is there a way I can just set the size of that JPanel permanently so that I don't have to go through changing the size of the JFrame a million times before I get the exact dimension so that the gray space disappears?
I also would like to set the size of those buttons so they are not so huge (BorderLayout is being used for the buttons and TextField)
GridBagLayout is what you really want to use. The GridLayout will force the same size for each component in the layout no matter what size constraints you put on them. GridBagLayout is a lot more powerful and a lot more complicated. Study up on the API page for it. Using GridBagLayout, the components won't fill the whole grid space if you don't want them to and can even stay the size that you ask it to be. To keep a component's size from changing, I would set all three available size constraints:
water.setPreferredSize(new Dimension(20, 20));
water.setMinimumSize(new Dimension(20, 20));
water.setMaximumSize(new Dimension(20, 20));
For your buttons, I would definitely use an inner panel as Bryan mentions. You could use either a GridLayout like he suggests or a FlowLayout if you don't want all the buttons to be the same size. Add all your buttons to that inner panel instead of the main one.
If you want the two checkerboards to stay the same size, then you'll need to have them each contained in their own JPanel. Set each of those parent JPanel's to have a layout type of GridBagLayout. Set the preferedSize for each checkerboard component and then add them to their respective containers. GridBagLayout should by default lay each board out in the center of the parent JPanel. So as the window is resized, the JPanel parent area will get larger or smaller, but the checkerboard components inside will remain the same size.
Alternatively, you could have your blue squares scale to the right size as the window is resized by having each checkboard square be a JPanel with a BorderLayout layout manager and adding the JLabel (with a blue background color) to its BorderLayout.CENTER location.
As for your buttons, try something like this:
JPanel theButtonPanel = new JPanel(new BorderLayout());
JButton button1 = new JButton("Fire");
JButton button2 = new JButton("Pass");
JButton button3 = new JButton("Forfiet");
JPanel innerButtonContainer = new JPanel(new Grid(1, 3, 8, 8));
innerButtonContainer.add(button1);
innerButtonContainer.add(button2);
innerButtonContainer.add(button3);
theButtonPanel.add(innterButtonContainer);
Lastly, consider using a design tool for your Swing user interface. Netbeans has an excellent UI designer built into it. Download Netbeans here.
If you can setResizeable( false ) on the top level frame you can then set your layout manager to null and hard code each location and size via setBounds. This is how I would do it (contingent on resizing of course).
I have had success solving problems like these using TableLayout which is a third party layout manager. You will need to download it and read the tutorial but the key would be to set the justification to CENTER when adding the JButtons to their positions in the layout.

Categories