Two Panels in one JFrame? - java

i have two Panels and want them to be shown in my JFrame, but when i try it like this, i can only see the second one. Can someone please help me? :(
import javax.swing.JFrame;
public class MainWindow {
CardLayout layout;
JFrame frame;
Player panel1;
Block panel2;
public MainWindow() {
frame = new JFrame("Rechteck");
panel1 = new Player();
panel2 = new Block();
panel1.addKeyListener(new KeyListen(panel1));
frame.add(panel1);
frame.add(panel2);
frame.setSize(500,500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}}

You have added both your panels to the BorderLayout.CENTER of your JFrame—only one can occupy that location,. This will be the last one added, panel2 in this case.
To allow the panels occupy the space evenly, you could use GridLayout:
frame.setLayout(new GridLayout(2, 1));
Aside: Better to use Key Bindings when registering key events for components in Swing.

Create a JPanel add that to the JFrame. Add panel1 and panel2 to the new panel. JFrame can only have one child, usually set by calling JFrame.setContentPane().

Related

How to position JPanel to upper right corner of JFrame

I have written a board game and have gotten to the point where I want to add a timer to the right corner of my JFrame. I was thinking it might be best solved through putting a JPanel in the upper right corner that I then will update with the count down time. However, I have run into the issue that I can't seem to figure out how to place the JPanel to a set location. Whatever I try to do it just seems to cover the entire screen, rather than the size and location I have put it to.
private final JFrame frame = new JFrame("myBoardGame");
private JPanel jp = new JPanel();
public ShowBoard(Board board){
frame.setResizable(false);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setContentPane(board);
frame.setLayout(new BorderLayout());
frame.pack();
frame.setVisible(true);
jp.setLayout(null);
jp.setLocation(300,300);
jp.setSize(100,100)
frame.add(jp);
this.board = board;
getKeyBindings(); }
Instead of it moving to the location 300x300 and setting it size to 100x100 it makes the entire screen go grey. What am I doing wrong? I simply want to be able to move the JPanel around the JFrame to where it fits best.
You can use a BorderLayout contentPane, as the frame's content pane. This pane would include:
In its BorderLayout.NORTH position, a JPanel (timerPane) with a FlowLayout (with orientation ComponentOrientation.RIGHT_TO_LEFT). You can use this panel to house your timer Component.
In its BorderLayout.CENTER position, your board.
Your code (modified to include this considerations) would look like this:
private final JFrame frame = new JFrame("myBoardGame");
private JPanel contentPane = new JPanel(new BorderLayout());
private JPanel timerPane = new JPanel(new FlowLayout());
public ShowBoard(Board board){
timerPane.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
contentPane.add(timerPane, BorderLayout.NORTH);
contentPane.add(board, BorderLayout.CENTER);
frame.setResizable(false);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setContentPane(contentPane);
frame.pack();
frame.setVisible(true);
this.board = board;
getKeyBindings();
}

Problems with BorderLayout() in Java

I've tried a lot of different ways, but I will explain two and what was happening (no error messages or anything, just not showing up like they should or just not showing up at all):
First, I created a JPanel called layout and set it as a BorderLayout. Here is a snippet of how I made it look:
JPanel layout = new JPanel();
layout.setLayout(new BorderLayout());
colorChoice = new JLabel("Choose your color: ");
layout.add(colorChoice, BorderLayout.NORTH);
colorBox = new JComboBox(fireworkColors);
colorBox.addActionListener(this);
layout.add(colorBox, BorderLayout.NORTH);
In this scenario what happens is they don't show up at all. It just continues on with whatever else I added.
So then I just tried setLayout(new BorderLayout()); Here is a snippet of that code:
setLayout(new BorderLayout());
colorChoice = new JLabel("Choose your color: ");
add(colorChoice, BorderLayout.NORTH);
colorBox = new JComboBox(fireworkColors);
colorBox.addActionListener(this);
add(colorBox, BorderLayout.NORTH);
In this scenario they are added, however, the width takes up the entire width of the frame and the textfield (not shown in the snippet) takes up basically everything else.
Here is what I have tried:
setPreferredSize() & setSize()
Is there something else that I am missing? Thank you.
I also should note that this is a separate class and there is no main in this class. I only say this because I've extended JPanel instead of JFrame. I've seen some people extend JFrame and use JFrame, but I haven't tried it yet.
You created a JPanel, but didn't add it to any container. It won't be visible until it is added to something (a JFrame, or another panel that is in a frame somewhere up the hierarhcy)
You added two components to the same position in the BorderLayout. The last one added is the one that will occupy that position.
Update:
You do not need to extend JFrame. I never do, instead I always extend JPanel. This makes my custom components more flexible: they can be added in another panel, or they can be added to a frame.
So, to demonstrate the problem I will make an entire, small, program:
public class BadGui
{
public static void main(String[] argv)
{
final JFrame frame = new JFrame("Hello World");
final JPanel panel = new JPanel();
panel.add(new JLabel("Hello"), BorderLayout.NORTH);
panel.add(new JLabel("World"), BorderLayout.SOUTH);
frame.setVisible(true);
}
}
In this program I created a panel, but did not add it to anything so it never becomes visible.
In the next program I will fix it by adding the panel to the frame.
public class FixedGui
{
public static void main(String[] argv)
{
final JFrame frame = new JFrame("Hello World");
final JPanel panel = new JPanel();
panel.add(new JLabel("Hello"), BorderLayout.NORTH);
panel.add(new JLabel("World"), BorderLayout.SOUTH);
frame.getContentPane().add(panel);
frame.setVisible(true);
}
}
Note that in both of these, when I added something to the panel, I chose different layout parameters (one label I put in 'North' and the other in 'South').
Here is an example of a JPanel with a BorderLayout that adds a JPanel with a button and label to the "North"
public class Frames extends JFrame
{
public Frames()
{
JPanel homePanel = new JPanel(new BorderLayout());
JPanel northContainerPanel = new JPanel(new FlowLayout());
JButton yourBtn = new JButton("I Do Nothing");
JLabel yourLabel = new JLabel("I Say Stuff");
homePanel.add(northContainerPanel, BorderLayout.NORTH);
northContainerPanel.add(yourBtn);
northContainerPanel.add(yourLabel);
add(homePanel);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setLocationRelativeTo(null);
setExtendedState(JFrame.MAXIMIZED_BOTH);
setTitle("Cool Stuff");
pack();
setVisible(true);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(Frames::new);
}
}
The below suggestion is assuming that your extending JFrame.
Testing
First of all, without seeing everything, theres always a numerous amount of things you can try.
First off, after you load everything, try adding this in (Again, assuming your extending JFrame:
revalidate();
repaint();
I add this into my own Swing projects all the time, as it refreshes and checks to see that everything is on the frame.
If that doesn't work, make sure that all your JComponent's are added to your JPanel, and ONLY your JPanel is on your JFrame. Your JFrame cannot sort everything out; the JPanel does that.
JPanel window = new JPanel();
JButton button = new JButton("Press me");
add(window);
window.add(button); // Notice how it's the JPanel that holds my components.
One thing though, you still add your JMenu's and what-not through your JFrame, not your JPanel.

JAVA JScrollPane not showing up

I have a JPanel with scrollbar and i want to add a lot of JLabels to it. But the scrollbar doesnt work . I can not use the scrollbar and even after the panel is full it doesn't scroll . Here is my code :
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Scroll {
public static void main(String[] args) {
JPanel panel = new JPanel(new GridLayout(0,1));
JPanel p = new JPanel(new BorderLayout());
JScrollPane scroll = new JScrollPane(panel);
scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
p.add(scroll, BorderLayout.NORTH);
JButton but = new JButton("OK");
p.add(but, BorderLayout.SOUTH);
but.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
panel.add(new JLabel("Some random text"));
scroll.revalidate();
p.repaint();p.revalidate();
}
});
JFrame frame = new JFrame();
frame.setSize(800,200);
frame.setVisible(true);
frame.add(p);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
}
}
Your problem seems to lie with your layout managers. I think BorderLayout behaves strangely when you don't use the BorderLayout.CENTER position. I changed the line
p.add(scroll, BorderLayout.NORTH);
to
p.add(scroll, BorderLayout.CENTER);
Then, to make the text appear from the top instead of centering, I changed the layout manager for the panel component to a BoxLayout. From:
JPanel panel = new JPanel(new GridLayout(0, 1));
to
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
This seems to have given me the functionality you want. Let me know if this fixes your issues or not!
As already suggested, you should probably use JList or JTable to implement your use case.
Regarding the issue, this is because all BorderLayout constraints except of CENTER will expand to as much space as their components occupy, even if that means that they will expand out of the screen bounds (in your case the NORTH section expands to the south after each button click).
To solve this, explicitly specify the preferred size for the components which can grow indefinitely if you add them to a non-central panel section with BorderLayout:
scroll.setPreferredSize(new Dimension(-1, 100));
I use -1 for the width here to indicate that it is not important (I could use any other value), since it will be ignored by the layout manager anyway (with BorderLayout.NORTH the component is stretched horizontally to take all the available horizontal space).

Remove Jframe panels

JFrame frame1 = new JFrame("frame");
frame1.setVisible(true);
frame1.setPreferredSize(new Dimension(800, 600));
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel Panel1 = new JPanel();
JPanel Panel2 = new JPanel();
frame1.add(Panel1,BorderLayout.SOUTH);
frame1.add(Panel2,BorderLayout.North);
How do i do something like this that if something happens the frame is blank
if(SOMETHINGHAPPENS)
{
//remove all panels from frame 1 so i have a blank frame
//now i want to add some new panels
}
Simple answer, don't.
Instead, use a CardLayout on the JFrame
This will allow you to setup a series of "views" which you can switch between as needed
Try this. Jframe.remove(JPanel). Then call JFrame.pack()
, and possibly JFrame.repaint() in order to refresh the graphics if necessary.
JPanel extends JComponent, so it should work just fine. Remember to substitute JFrame and JPanel in the code above with the names of the frames/panels you are using the methods on.

Best layout for frame

What kind of layout should I use to create a page Like this:
It should be resizable
It has two main panels Right and Left?
Extra space will be given to the 'Main Text' text area, and extra height will be given to the button panel while centering them.
import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class EndOfLineButtonLayout {
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
// the GUI as seen by the user (without frame)
JPanel gui = new JPanel(new BorderLayout());
gui.setBorder(new EmptyBorder(2, 3, 2, 3));
JPanel textPanel = new JPanel(new BorderLayout(5,5));
textPanel.add(new JScrollPane(new JTextArea("Top Text",3,20)),
BorderLayout.PAGE_START);
textPanel.add(new JScrollPane(new JTextArea("Main Text",10,10)));
gui.add(textPanel, BorderLayout.CENTER);
JPanel buttonCenter = new JPanel(new GridBagLayout());
buttonCenter.setBorder(new EmptyBorder(5,5,5,5));
JPanel buttonPanel = new JPanel(new GridLayout(0,1,5,5));
for (int ii=1; ii<6; ii++) {
buttonPanel.add(new JButton("Button " + ii));
}
// a component added to a GBL with no constraint will be centered
buttonCenter.add(buttonPanel);
gui.add(buttonCenter, BorderLayout.LINE_END);
JFrame f = new JFrame("Demo");
f.add(gui);
// Ensures JVM closes after frame(s) closed and
// all non-daemon threads are finished
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
// See http://stackoverflow.com/a/7143398/418556 for demo.
f.setLocationByPlatform(true);
// ensures the frame is the minimum size it needs to be
// in order display the components within it
f.pack();
// should be done last, to avoid flickering, moving,
// resizing artifacts.
f.setVisible(true);
}
};
// Swing GUIs should be created and updated on the EDT
// http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html
SwingUtilities.invokeLater(r);
}
}
You can use gridbag layout, try using netbeans, I have tried it and found really usefull.
Once you create it with netbeans you can use the same and build infact any kind of layout.
best of luck with other solutions.
p.s. border layout is perfect for your requirement, but I mentioned this just in case you would like to do lot more .
I would use BorderLayout.
Create Three JPanels and add them to a JFrame as follows:
public class YourClass extends JFrame{
//code here
this.setLayout(new BorderLayout());
this.add(TopPanel, BorderLayout.NORTH);
this.add(RightPanel, BorderLayout.EAST);
this.add(MainPanel, BorderLayout.CENTER);
this.pack();
this.setVisible(true);
The two main panels would be placed inside a main JPanel using a BorderLayout. The left panel would be placed using BorderLayout.CENTER, and the right panel would be placed using BorderLayout.LINE_END.
The left panel would use a BoxLayout, Y axis to separate the two JPanels within the left panel.
The right buttons panel would use a GridBagLayout. This sizes the buttons the same and allows you to use Insets to add some spacing to the buttons.
The buttons would be spaced from the top to the bottom of the right buttons panel. If you want all the buttons towards the top of the right buttons panel, you would put the right buttons panel inside of another JPanel using a FlowLayout.

Categories