Trying to add 3 panels i created to a frame in Java with the JSplitPane. Have tried this with 2 panels, and that worked great, but with 3 it still does not do what i want.
Have read something about making 2 JSplitPanes and put the one in the other, but that does not actually work what i would like it to do.
My code shows that there are 3 panels, but the size are all wrong.. it should be filled out.
My code:
frame = new JFrame(); // Create a new frame
frame.setVisible(true); // Makes it visible
frame.setSize(900, 500); // Sets size
frame.setTitle(""); // Sets title
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null); // Sets the window on the center of the screen
temp_panel = new JPanel(); // Creates new JPanel
water_panel = new JPanel(); // Creates new JPanel
power_panel = new JPanel(); // Creates new JPanel
temp_panel.setBackground(Color.decode("#2ecc71")); // Sets color
water_panel.setBackground(Color.decode("#3498db")); // Sets color
power_panel.setBackground(Color.decode("#f1c40f")); // Sets color
temp_label = new JLabel("This is Temperature");
water_label = new JLabel("This is Water consumption");
power_label = new JLabel("This is Power consumption");
// Add labels on panel
temp_panel.add(temp_label);
water_panel.add(water_label);
power_panel.add(power_label);
JSplitPane splitPaneLeft = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
JSplitPane splitPaneRight = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
splitPaneLeft.setLeftComponent( temp_panel );
splitPaneLeft.setRightComponent( water_panel );
splitPaneRight.setLeftComponent( splitPaneLeft );
splitPaneRight.setRightComponent( power_panel );
splitPaneLeft.setEnabled(false);
splitPaneLeft.setDividerSize(0);
splitPaneRight.setEnabled(false);
splitPaneRight.setDividerSize(0);
// put splitPaneRight onto a single panel
JPanel panelSplit = new JPanel();
panelSplit.add( splitPaneRight );
frame.add(panelSplit, BorderLayout.CENTER);
It should look like this, but just with 3 panels with 3 different colors instead of 2!
Hope someone can help
If you don't need to change the relative sizes of the components during runtime, don't use a JSplitPane. Instead create a container JPanel that uses GridLayout, say new GridLayout(1, 0) for 1 row and variable number of columns, add your three colored JPanels to the GridLayout-using JPanel, and add this then to the JFrame.
you could make one of the panels another JSplitPane, unfortunately there is no other solution for this.
Related
I'm having a problem when i use .updateUI() in my JPanels, The bounds i set return to default.
//Set my Frame
frame = new JFrame();
frame.setSize(1600,900);
frame.setLayout(null);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
//Set Panel
JPanel menuInput = new JPanel();
menuInput.setBounds(100,100,500,500);
//Set Button
JButton buttonSolve = new JButton();
buttonSolve.setBounds(30,30,400,200);
menuInput .add(buttonSolve);
frame.add(menuInput);
//If i updateUI, the bound returns to default.
menuInput.updateUI();
However if i place my menuInput.updateUI before frame.add(menuInput) it will not affect the bounds, but i need to refresh my Panel every time new data comes in.
I use MigLayout, and i have no problem with setting the positions of each object now.
I'm trying practice my GUI and I am having troubles putting gap between component and the frame.
The picture above is what I have so far. But I really want to put a gap between the left side of the frame and "label1".
private void initialize() {
frame = new JFrame();
frame.setTitle("WINDOW");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 300);
panel = new JPanel();
panel.setLayout(new BorderLayout());
bottomPanel = new JPanel();
bottomPanel.setLayout(new GridLayout(1, 5));
l1 = new JLabel("Label1");
l2 = new JLabel("Label2");
l3 = new JLabel("Label3");
l4 = new JLabel("Label4");
l5 = new JLabel("Label5");
bottomPanel.add(l1);
bottomPanel.add(l2);
bottomPanel.add(l3);
bottomPanel.add(l4);
bottomPanel.add(l5);
panel.add(bottomPanel, BorderLayout.SOUTH);
frame.add(panel);
}
Above is part my code. I tried doing:
bottomPanel.setLayout(new GridLayout(1, 5, -20, 0));
to put some horizontal gap but that only added gap between the components. That didn't move "label1" away from the frame at all. Is there any other way of doing this? I am very new to Java so I don't really know much of the other tricks. I would appreciate any help! Thank you!
The other answers are fudges that won't achieve the desired effect when the GUI is resized. Instead use:
JLabel.setHorizontalAlignment(SwingConstants.CENTER);
By centering the text within the JLabel, combined with GridLayout stretching the components to the full width of the cell, each label will have as much space either side as the GUI can allow. E.G. here is the effect when the GUI is at minimum size.
And when stretched wider:
(The red border is added to show the bounds of each label.)
Add a Border to the panel:
bottomPanel = new JPanel();
bottomPanel.setBorder( new EmptyBorder(0, 10, 0, 0) );
Read the section from the Swing tutorial on How to Use Borders for more information about the different borders you can create.
Try the following:
bottomPanel.add(javax.swing.Box.createHorizontalStrut(10));
I have an assignment which requires me to create the layout that you see in the image as part of the development of a game. I've never worked with Java for desktop applications before so i'm a complete noob when it comes to using the Swing & AWT libraries. The image suggests that we use a JLayeredPane as our root container and then add the rest on top of it. My issue is that i've tried starting with the background image and the gridLayout but i can't seem to make anything other than the background show up. The grid doesn't show up at all (no border line, no background of the cells) and any other component i've added to it has failed. Can somebody point me in the right direction here? I've read the docs & saw some example of various layouts,containers and components but i can't seem to make all of them work together.
Here's my code so far:
public class BoardView extends JFrame{
// Constructor
public BoardView() {
JFrame window = new JFrame("Sorry Game"); // create a new Jwindow instance
ImageIcon appIcon = new ImageIcon(getClass().getClassLoader().getResource("res/icon.png")); // create the icon for the app
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // when the 'X' button is clicked, the app stops
window.setSize(new Dimension(1000, 700)); // setting the size of the window
window.setResizable(false); // Window won't be resizable
window.setIconImage(appIcon.getImage()); // set the icon for the app
window.setLayout(new BorderLayout());
JLayeredPane layeredPane = new JLayeredPane();
JLabel background = new JLabel();
background.setSize(1000,700);
background.setIcon(new ImageIcon(getClass().getClassLoader().getResource("res/background.png"))); for the JLabel
layeredPane.add(background,0);
JPanel gridPanel = new JPanel(new GridLayout(16,16));
gridPanel.setSize(650,700);
layeredPane.add(gridPanel);
for(int i = 0; i < 256; i++) {
JLabel tile = new JLabel();
tile.setBackground(Color.red);
tile.setBorder(new LineBorder(Color.black));
gridPanel.add(tile);
}
JLabel logo = new JLabel();
logo.setIcon(new ImageIcon(getClass().getClassLoader().getResource("res/sorryImage.png")));
layeredPane.add(logo);
window.add(layeredPane);
window.setLocationRelativeTo(null); // centers the window to the screen
window.setVisible(true); // make the window visible
}
}
My thought process was that i could set the JFrame's layout to a BorderLayout so that i can brake the final layout down into two parts, the West one and the East one. The West one would contain the Grid and the various JLabels and Buttons and the East one would contain the rest of the components. I've tried using the BorderLayout.WEST & EAST parameters when adding components to the JFrame but none has worked or changed a single thing. I've also tried using an index for the depth when adding components to the JLayeredPane as per the docs but again nothing changes.
P.S. Please note that i'm not looking for someone to create the layout for me. I want someone to help me understand what i'm doing wrong and what the best way of creating such layouts is.
In order to initialize the cells of the grid that i want to have images in, don't i need to add them manually in those positions?
If you use a GridLayout every cell must have a component and the components must be added in sequential order. That is as components are added they will wrap automatically to the next row as required.
So even if you don't want an image in a cell you would need to add a dummy component, lets say a JLabel with no text/icon.
An easier approach might be to use a GridBagLayout. The GridBagLayout can be configured to "reserve" space for cells that don't have components. So you can add a component to a specific cell.
import java.awt.*;
import java.util.*;
import javax.swing.*;
import javax.swing.border.*;
public class GridBagLayoutSparse extends JPanel
{
public GridBagLayoutSparse()
{
setBorder( new LineBorder(Color.RED) );
GridBagLayout gbl = new GridBagLayout();
setLayout( gbl );
/*
// Set up a grid with 5 rows and columns.
// The minimimum width of a column is 50 pixels
// and the minimum height of a row is 20 pixels.
int[] columns = new int[5];
Arrays.fill(columns, 50);
gbl.columnWidths = columns;
int[] rows = new int[5];
Arrays.fill(rows, 20);
gbl.rowHeights = rows;
*/
// Add components to the grid at top/left and bottom/right
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.BOTH;
gbc.gridx = 0;
gbc.gridy = 0;
addLabel("Cell 0:0", gbc);
gbc.gridx = 3;
gbc.gridy = 4;
addLabel("Cell 3:4", gbc);
}
private void addLabel(String text, GridBagConstraints gbc)
{
JLabel label = new JLabel(text);
label.setBorder( new LineBorder(Color.BLUE) );
add(label, gbc);
}
private static void createAndShowGUI()
{
JFrame frame = new JFrame("GridBagLayoutSparse");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout( new GridBagLayout() );
frame.add(new GridBagLayoutSparse());
frame.setSize(300, 300);
frame.setLocationByPlatform( true );
frame.setVisible( true );
}
public static void main(String[] args) throws Exception
{
java.awt.EventQueue.invokeLater( () -> createAndShowGUI() );
}
}
Run the code as is and the components will be grouped together in the center.
Uncomment the block comment and run again. The components will be positioned in the appropriate cell.
I am trying to make a 2x2 grid layout that has a JLabel on the top left, and three buttons on the other three spaces. When I do this, I get the unexpected result of one big button (filling up the entire JDialog) that says "Do you want to push me". I don't know why this result shows up, please help, Thanks!
public void sinceyoupressedthecoolbutton() {
JDialog replacementwindow = new JDialog(); //Like a window
JButton best = new JButton("best");
JButton first = new JButton("FIRST");
JButton second = new JButton("Second");
replacementwindow.setLayout(new GridLayout(2,3,0,0)); //Row, column, distance horizontally, distance vertical
JPanel panel = new JPanel();
replacementwindow.add(panel); //adding the JPanel itself
replacementwindow.add(first);
replacementwindow.add(second);
replacementwindow.add(best);
replacementwindow.setSize(500, 500);
replacementwindow.setTitle("NEW WINDOW!");
replacementwindow.setVisible(true);
}
It's because you set the layout of your JButton, and not of your JDialog
Change
label.setLayout(new GridLayout(2,2,0,0));
to
YES.setLayout(new GridLayout(2,2,0,0));
Also, your variable called label is a JButton, you probably want to change that.
Don't add components to a button. You add components to a panel.
So the basic code should be:
JDialog dialog = new JDialog(...);
JPanel panel = new JPanel( new GridLayout(...) );
panel.add(label);
panel.add(button1);
...
dialog.add(panel);
Also, variable names should NOT start with an upper case character! "Yes" does not follow Java standards. The other variables do. Be consistent!
In a part of my software I have a layout on bottom that holds couple of JButtons and a JLabel. I want to keep buttons one the right side of the panel, and label on the left side. I could manage to put buttons on the right, but do not know how to keep the JLabel on the left side.
Here is the code:
bottomPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
ftpBack = new JButton("Back");
ftpNext = new JButton("Next");
label = new JLabel("Text);
bottomPanel.add(label);
bottomPanel.add(ftpBack);
bottomPanel.add(ftpNext);
mainPanel.add(bottomPanel, BorderLayout.SOUTH);
This is what I am trying to achieve:
Any idea how to make it ?
You can't do this with a FlowLayout.
You can use a horizontal BoxLayout:
Box box = Box.createHorizontalBox();
box.add(label);
box.add(Box.createHorizontalGlue());
box.add(backButton);
box.add(Box.createHorizontalStrut(5));
box.add(nextButton);
Read the section from the Swing tutorial on How to Use BoxLayout for more information and examples.
Or another approach is to nest layout managers:
JPanel main = new JPanel( new BorderLayout() );
main.add(label, BorderLayout.WEST);
JPanel buttonPanel= new JPanel();
buttonPanel.add(back);
buttonPanel.add(next);
main.add(buttonPanel, BorderLayout.EAST);