Been having a hard time adding JPanels to JFrame. Am pretty much new on java, always used C++
I need to do 4 Panels inside one Frame.
Here is my Code, just started today..
package project2;
import javax.swing.JOptionPane;
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.BorderLayout;
import javax.swing.*;
import java.awt.Container;
import java.awt.Dimension;
public class GUI extends JFrame
{
private JPanel Checks; //Panel to Hold Checks
private JPanel Transactions;
private JPanel History;
private JPanel Graphics;
private JLabel CLabel;
public GUI()
{
super ( "UTB Check-In");
JPanel Checks = new JPanel(); //set up panel
CLabel = new JLabel("Label with text");
Checks.setBackground(Color.red);
Checks.setLayout( new BoxLayout(Checks,BoxLayout.LINE_AXIS));
add(Checks);
// JPanel Transactions = new JPanel();
// Transactions.setToolTipText("Electronic Transactions");
//Transactions.setBackground(Color.blue);
// add(Transactions);
}
}
I was trying to put Transaction and Checks one side from the other with different colors,in this case blue and red it doesnt stay in the middle it those one or the other.
One of my Colleagues told me that the BoxLayout(or any layout) needed to be implemented with the size..something to that extend. am not really sure I been reading
http://docs.oracle.com/javase/tutorial/uiswing/layout/box.html
But I still do not get it completely. If somebody can help me out
thanks!
Your code fail cause you are adding directly to the JFrame which have by default BorderLayout. You are setting BoxLayout to the wrong panel.
You have to setLayout() to the top component(jframe) that you are adding or as i prefer adding to a jpanel rather than directly to the jframe to acomplish what you want to do.
Example:
public GUI()
{
super ( "UTB Check-In");
JPanel parent = new JPanel();
parent.setLayout(new BoxLayout(parent,BoxLayout.LINE_AXIS));
add(parent);
JPanel Checks = new JPanel(); //set up panel
CLabel = new JLabel("Label with text");
Checks.setBackground(Color.red);
parent.add(Checks);
JPanel Transactions = new JPanel();
Transactions.setToolTipText("Electronic Transactions");
Transactions.setBackground(Color.blue);
parent.add(Transactions);
}
By the way, in Java variables starts with lowerCase as a code convention.
Related
since some hours I am trying to create a JFrame whit following behavior:
I have a Title (with maybe an Image included) -This is centered at the top. -> Check
The rest of this JFrame should be filled with JPanel.
The first JPanel should be placed in the center on top. The second JPanel should be placed under the first and so on. When the first JPanel runs out of the screen, a second row needs to be created.
I dont care if they are reordered or not. Here is a drawing i prepared to show what I want:
Example - I need one of that behaviors
I have tried out so many combination of different Layouts.. But still can't find the right solution.
Here is my code, which is working fine besides the fact, that my panels are ordered from left to right instead of from top to down.. :(
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
#SuppressWarnings("serial")
public class myFrameClass extends JFrame {
myFrameClass() {
super();
setLayout(new BorderLayout());
GraphicsDevice[] gs = GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices();
GraphicsConfiguration[] gc = gs[0].getConfigurations();
setUndecorated(true);
setBackground(Color.WHITE);
setLocation(gc[0].getBounds().x, gc[0].getBounds().y);
setExtendedState(JFrame.MAXIMIZED_BOTH);
add(getHeader(), BorderLayout.NORTH);
add(getPanels());
setVisible(true);
}
private JPanel getPanels() {
JPanel p = new JPanel();
p.setLayout(new FlowLayout());
int cnt = 6;
for (int i = 0; i < cnt; i++) {
p.add(getPanel());
}
return p;
}
private JPanel getPanel() {
JPanel p = new JPanel();
p.setBackground(Color.RED);
p.setPreferredSize(new Dimension(200, 200));
return p;
}
private JPanel getHeader() {
JPanel p = new JPanel();
p.add(new JLabel("Titel"));
return p;
}
public static void main(String args[]) {
new myFrameClass();
}
}
I also found Oracle VerticalFlowLayout but was not able to access it. Might it help me? In case - how to use it?
Otherwise.. How to use JFrame to archive that behavior?
Thank you
Hello StackExchange community,
I'm at my wits end about this JSplitPane I'm trying to put into my frame, it is sitting on the right side of my frame instead of filling it up or atleast sitting on the left.
If anyone could help me with this issue I'd be very thankful.
See below an image of my problem and the code
The problem area is the pane with "tab1" and "tab2", the divider and the pane on the right side of that divider:
I've tried setting setAlignmentX(Component.LEFT_ALIGNMENT) on all the individual parts of the JSplitPane. I've also tried making a JPanel to hold it and aligning that. All to no avail.
Furthermore, existing information I've been able to find hasn't been relevant, mostly people discussing how to align the contents of the JSplitPane.
The code below is all that is needed to make this frame, if any of you need it to help me out feel free.
package test;
import java.awt.Color;
import java.awt.Component;
import java.util.ArrayList;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
public class FrameMaker {
public int x = 0;
private ArrayList<String> mpLabels;
private JFrame theFrame;
public void MakeFrame() {
theFrame = new JFrame("title");
theFrame.getContentPane().setLayout(new BoxLayout(theFrame.getContentPane(), BoxLayout.Y_AXIS));
mpLabels = new ArrayList<String>();
//label1
JPanel bgSwitches = new JPanel();
JLabel calcsLabel = new JLabel("top label, broadened with lines to exaggerate problem-------------------------------------------");
bgSwitches.add(calcsLabel);
//label2
JPanel topLevel = new JPanel();
JLabel textinfo = new JLabel("label below that");
topLevel.add(textinfo);
//splitpane tabs
mpLabels.add("tab1");
mpLabels.add("tab2");
String[] mpLabelsAr = new String[mpLabels.size()];
JList<String> posL = new JList<String>(mpLabels.toArray(mpLabels.toArray(mpLabelsAr)));
posL.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
//panel inside the right splitpane pane, this is needed for something later.
JPanel RPanel = new JPanel();
RPanel.setLayout(new BoxLayout(RPanel, BoxLayout.Y_AXIS));
JScrollPane scrollPos = new JScrollPane(posL);
JScrollPane scrollROI = new JScrollPane(RPanel);
JSplitPane posPanel = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,scrollPos,scrollROI);
posPanel.setOneTouchExpandable(false);
posPanel.setDividerLocation(75);
//label and textfield
JLabel msLabel = new JLabel("another label");
JTextField msField = new JTextField("textfield");
JPanel buttonPanel = new JPanel();
buttonPanel.add(msLabel);
buttonPanel.add(msField);
bgSwitches.setBackground(new Color(0,0,255));
theFrame.add(bgSwitches);
topLevel.setBackground(new Color(0,255,0));
theFrame.add(topLevel);
posPanel.setAlignmentX(Component.LEFT_ALIGNMENT);
posPanel.setBackground(new Color(0,255,255));
theFrame.add(posPanel);
buttonPanel.setBackground(new Color(255,0,0));
theFrame.add(buttonPanel);
theFrame.pack();
theFrame.setVisible(true);
}
}
You need to align all of your other elements to the left as well.
bgSwitches.setAlignmentX(Component.LEFT_ALIGNMENT);
topLevel.setAlignmentX(Component.LEFT_ALIGNMENT);
buttonPanel.setAlignmentX(Component.LEFT_ALIGNMENT);
You can also add posPanel.setResizeWeight(VALUE BETWEEN 0 AND 1); to specify what percent of the space the JSplitPane should occupy and it will resize with your window.
I'm having a very hard time with borders, I've looked through tutorials and examples and each seems to use a different style, I'm just trying to organise the content into separated borders. The content for the bottom panal isn't finished yet but I'm just trying to get it to work as is before adding more.
The compiler says there are problems on two lines java.lang.NullPointerException:
package question2;
import java.awt.Color;
import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.TitledBorder;
/**
* #author Matt Headley
This frame shows a data set and its statistics.
*/
public class ComputerStoreGUI extends JFrame
{
private JCheckBox item1;
private JCheckBox item2;
private JCheckBox item3;
private JCheckBox item4;
private JCheckBox item5;
private TitledBorder border;
private TitledBorder border2;
private static JPanel content;
private static JPanel top;
private static JPanel bottom;
private JTextField parts;
public ComputerStoreGUI()
{
JCheckBox item1 = new JCheckBox("Install Hard Drive - $25.00");
JCheckBox item2 = new JCheckBox("Install RAM - $15.00");
JCheckBox item3 = new JCheckBox("Remove Virus - $50.00");
JCheckBox item4 = new JCheckBox("Format Hard Drive - $80.00");
JCheckBox item5 = new JCheckBox("Quote Hourly Labour - $10.00");
item1.setHorizontalAlignment(JCheckBox.LEFT);
item2.setHorizontalAlignment(JCheckBox.LEFT);
item3.setHorizontalAlignment(JCheckBox.LEFT);
item4.setHorizontalAlignment(JCheckBox.LEFT);
item5.setHorizontalAlignment(JCheckBox.LEFT);
JTextField cost = new JTextField(10);
top = new JPanel(new FlowLayout(FlowLayout.LEFT));
top.add(item1);
top.add(item2);
top.add(item3);
top.add(item4);
top.add(item5);
bottom.add(cost); //here ????????
cost.setHorizontalAlignment(JTextField.CENTER);
}
public static void main(String[] args)
{
JFrame frame = new ComputerStoreGUI(); // and here ???????
content = new JPanel();
content.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
top = new JPanel();
top.setBorder(BorderFactory.createTitledBorder("Standard Services"));
bottom = new JPanel();
bottom.setBorder(BorderFactory.createTitledBorder("Hourly Service"));
frame.setSize(250, 400);
frame.setTitle("LU Computer Store");
frame.setContentPane(content);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
content.add(top);
content.add(bottom);
frame.setVisible(true);
}
}
the end goal is to look something like this:
First, I dont see a reson to extend JFrame in your example. So without inheritance you can use composition like:
JFrmae frame = new JFrame();
Read more: Why do we need to extend JFrame in a swing application?
The compiler says there are problems on two lines
java.lang.NullPointerException:
Reason is, you have declared the JPanel bottom but without initializing you are trying to use it, from this line: bottom.add(cost);
Do something like:
bottom = new JPanel(new FlowLayout(FlowLayout.LEFT));
bottom.add(cost);
EDIT:
comment: It runs now, but the panels are tiny
Because you need to set layout for the parent JPanel, you can use BoxLayout, to add child panels one below another, like below:
content = new JPanel();
content.setLayout(new BoxLayout(content, BoxLayout.PAGE_AXIS));
In case if you want to add space between those two child panels, use as below:
content.add(top);
content.add(Box.createRigidArea(new Dimension(0,10)));
content.add(bottom);
I have tried setLocation(x,y) and setLocationRelativeTo(null) by setting Layout of JFrame as null but that didn't work out.While searching I found this questions being already asked by two or three people but they have done through setLocation() and setLocationRelativeTo(null).
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import java.awt.FlowLayout;
public class StartMenu{
JPanel startPanel;
JLabel title;
JButton startTest;
JButton exit;
JFrame menuFrame;
public StartMenu(){
menuFrame = new JFrame("Start Menu");
menuFrame.setLayout(null);
startPanel = new JPanel();
title = new JLabel("Adaptive Test",JLabel.CENTER);
title.setLocation(20,20);
startPanel.add(title);
startTest = new JButton("Start");
startTest.setLocation(40,40);
startPanel.add(startTest);
exit = new JButton("Exit");
exit.setLocation(100,100);
startPanel.add(exit);
menuFrame.setContentPane(startPanel);
menuFrame.setVisible(true);
menuFrame.setSize(500, 500);
menuFrame.setResizable(false);
menuFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Your JFrame's layout is set to null, but the startPanel's one is not. So first of all, use:
startPanel.setLayout(null);
Now, instead of component.setLocation(x, y), use component.setBounds(x, y, width, height), so you also set a size for them.
But as has been said in the comments, it would be preferable to use layout managers instead of null layout.
First you set to null the JFrame istead of the JPanel, so you have to use
startPanel.setLayout(null);
then you should use setBounds istead of setLocation becouse if you just set the location with a null layout manager you'll probably will see nothing on your panel, becouse all dimensions are initialized to 0 by default.
so, you can rewrite your software like this:
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class StartMenu{
JPanel startPanel;
JLabel title;
JButton startTest;
JButton exit;
JFrame menuFrame;
public StartMenu(){
menuFrame = new JFrame("Start Menu");
menuFrame.setLayout(null);
startPanel = new JPanel();
startPanel.setLayout(null);
title = new JLabel("Adaptive Test",JLabel.CENTER);
title.setBounds(20,20, 100, 30);
startPanel.add(title);
startTest = new JButton("Start");
startTest.setBounds(50,50, 100, 30);
startPanel.add(startTest);
exit = new JButton("Exit");
exit.setBounds(100,100, 100 ,30);
startPanel.add(exit);
menuFrame.setContentPane(startPanel);
menuFrame.setVisible(true);
menuFrame.setSize(500, 500);
menuFrame.setResizable(false);
menuFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Like this you get something working but it isn't a very good programming practice to set by hand all the location and sizes in your software becouse it will not work good on different systems (thus it will not be portable) and you will also find yourself in a debugging nightmare when your software will start growing with tens if not hundreds of graphics elements.
My suggestion is to use the gridBagLayout, it me seem obscure at first, but trust me, it's not so!
I made a quick research to solve this problem but until now I found nothing regarding to this. I have one image into one TabbedPane object but when I try to align this image on the center of the label inside the TabbedPane it "Doesn't" work. The center alignment in this case works only for horizontal view but I want to be in the center of both vertical and horizontal. Check out the sample below:
import java.awt.BorderLayout;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import com.sh.st.gui.MainScreen;
public class test {
JTabbedPane tabbedPane = new JTabbedPane();
JFrame mainFrame = new JFrame();
public static void main (String[] args){
test t = new test();
}
public test(){
JPanel entrance = new JPanel();
JLabel lbImage1;
JMenuBar bar;
JMenu file, registerQuery;
ImageIcon Logo= new ImageIcon("rsc/img/imagem.jpg");
lbImage1= new JLabel(Logo, JLabel.CENTER);
entrance.add(lbImage1);
tabbedPane.addTab("Entrance", null, entrance);
mainFrame.getContentPane().add( tabbedPane, BorderLayout.CENTER);
bar= new JMenuBar();
file= new JMenu("File");
registerQuery= new JMenu("Request");
mainFrame.setVisible(true);
}
}
I guess its not so hard to do what I want but until now as I said, I found nothing, anyone could help please? thanks in advance
The JLabel alignment will only center horizontally due to the potitioning characteristics of its parent container. In this case it is the default layout for JPanel which is FlowLayout. This layout manager does not facilitate easy vertical alignment.
Provided that the JLabel lbImage1 will be the only component on the JPanel entrance, then GridLayout can be used to center the JLabel both horizontally and vertically:
entrance.setLayout(new GridLayout());