Add component in a JPanel subclass - java

I want to create a JPanel subclass thats holds some JLabels. I started to write my code but I immediatly find a big problem. Component added to the JPanel subclass are not visible (or they are not added to JPanel I don' t kano). This is the code of the JPanel Subclass:
public class ClientDetails extends JPanel
{
private JLabel nameAndSurname = new JLabel ("Name & Surname");
private JLabel company = new JLabel ("Company");
private JPanel topPanel = new JPanel ();
public ClientDetails ()
{
this.setBackground(Color.white);
this.setLayout(new BorderLayout());
topPanel.setLayout(new BoxLayout(topPanel, BoxLayout.Y_AXIS));
topPanel.add(nameAndSurname);
topPanel.add(company);
this.add(topPanel,BorderLayout.PAGE_START);
}
}

You need to
put the JPanel in a top level container (like a JFrame)
call pack() on it so the LayoutManager finds room for your stuff
.
public class Test extends JPanel {
private JLabel nameAndSurname = new JLabel ("Name & Surname");
private JLabel company = new JLabel ("Company");
private JPanel topPanel = new JPanel ();
JFrame frame;
public Test()
{
this.setBackground(Color.white);
this.setLayout(new BorderLayout());
topPanel.setLayout(new BoxLayout(topPanel, BoxLayout.Y_AXIS));
topPanel.add(nameAndSurname);
topPanel.add(company);
this.add(topPanel,BorderLayout.PAGE_START);
frame = new JFrame("test");
frame.add(this);
frame.pack();
frame.setVisible(true);
}
}

Related

Panel is not showing on frame in Java Swing

I've made a HallOfFame class which is subclass of JPanel and i want to add a label writing "Hall OF Fame" on this panel.In the MainWindow class (frame) i have added the HallOfFame (Panel) to the content pane but nothing shows up. The same happens with every component i am trying to add on the frame (MainWindow) except the top (placed North with the BorderLayout) panel with 3 buttons.
public class HallOfFame extends JPanel{
JLabel hofLabel;
public HallOfFame() {
this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
this.setBorder(new LineBorder(Color.GRAY, 1));
this.setAlignmentX(CENTER_ALIGNMENT);
hofLabel = new JLabel("Hall OF Fame");
add(hofLabel);
}
}
public class MainWindow extends JFrame{
/*Size of main window*/
public static final Dimension winSize = new Dimension(1200, 800);
public static final int TOP_HEIGHT = 80;
public static final int PLAYER_WIDTH = 300;
private GameBoard gameBoard;
private HallOfFame hallOfFame;
private BannerPanel bannerPanel;
private PlayerPanel playerPanel;
public MainWindow() {
//Initializing the frame.
Container c = this.getContentPane();
c.setPreferredSize(winSize);
this.setTitle("TucTacToe");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
/*Hall of fame*/
hallOfFame = new HallOfFame();
/*GameBoard*/
gameBoard = new GameBoard();
/*Banner Panel*/
bannerPanel = new BannerPanel();
/*PlayerPanel*/
playerPanel = new PlayerPanel();
/*Adding the components to the window*/
c.add(bannerPanel, BorderLayout.NORTH);
c.add(hallOfFame, BorderLayout.CENTER);
//add(gameBoard, BorderLayout.CENTER);
c.add(playerPanel);
this.pack();
this.setVisible(true);//setting visible the frame.
}
}
Here is the window of the project
c.add(hallOfFame, BorderLayout.CENTER);
c.add(playerPanel)
You are adding the "playerPanel" to the CENTER of the frame. When you don't specify the constraint it defaults to the CENTER when using BorderLayout.
Only the last component added will be visible. So it appears your playerPanel doesn't have any components added to it.
For a simple test just use:
c.add(hallOfFame, BorderLayout.CENTER);
//c.add(playerPanel)
Now you should see the hallOfFame panel.

How to make method return a panel?

I am making a Java application with tabbed pane, I want some panes to have the same panel layout and structure, I don't want to clutter my code by writing the same code over and over again, so I created a method that returns a JPanel with a structure I want the pane to have.
I am initialising new variables and taking them to the method . My problem is that after I create a panel I can not do anything else in it because it doesn't show up. I can not add labels etc, etc (although if I add the label in the method it does show).
My question is it possible to somehow change the code I've written to make it possible to change it after the panel is returned?
JPanel panel2 = panel2(); // this code bit is in the constructor
JPanel mainPanel = new JPanel(); //Variables needed to create a panel
JPanel LeftPanel = new JPanel();
JPanel RightPanel = new JPanel();
JSplitPane splitPaneH = new JSplitPane();
JPanel panelTop = new JPanel();
JPanel panelBottom = new JPanel();
private JPanel panel2() {
JPanel newPanel = new JPanel();
CreateAPanel(newPanel, LeftPanel,RightPanel,splitPaneH, panelTop,panelBottom);
JLabel label = new JLabel ("lalala");
LeftPanel.add(label,BorderLayout.CENTER);
return newPanel;
}
private JPanel CreateAPanel(JPanel mainPanel, JPanel LeftPanel,JPanel RightPanel, JSplitPane splitPaneH, JPanel panelTop, JPanel panelBottom){
mainPanel.setPreferredSize(new Dimension(1100, 630));
mainPanel.setLayout(new BorderLayout());
LeftPanel = new JPanel();
RightPanel = new JPanel();
splitPaneH = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
panelTop = new JPanel();
panelBottom = new JPanel();
splitPaneH.setTopComponent(panelTop);
splitPaneH.setBottomComponent(panelBottom);
splitPaneH.setDividerLocation(300);
splitPaneH.setPreferredSize(new Dimension(800,630));
mainPanel.add(LeftPanel, BorderLayout.WEST);
mainPanel.add(RightPanel,BorderLayout.EAST);
LeftPanel.setBackground(Color.RED);
LeftPanel.setPreferredSize(new Dimension (300,630));
RightPanel.add(splitPaneH);
return mainPanel;
}
you do not use your return value...
your method CreateAPanel(...) creates the desired panel but you just don't use it
you should adjust your method panel2() in like this:
private JPanel panel2()
{
//JPanel newPanel = new JPanel(); don't create a new panel!
//CreateAPanel(newPanel, LeftPanel,RightPanel,splitPaneH, panelTop,panelBottom);
//instead do this:
JPanel newPanel = CreateAPanel(newPanel, LeftPanel,RightPanel,splitPaneH, panelTop,panelBottom);
JLabel label = new JLabel ("lalala");
LeftPanel.add(label,BorderLayout.CENTER);
return newPanel;
}
It's totally possible to add components to the Panel object afterwards. The only mistake that you have made is that "inside the method body you create new JPanel instances to replace with original param references" so when the method returns there is no effect on the original objects. I suggest doing something different as this:
private JPanel[] CreateAPanel(JPanel mainPanel)
{
mainPanel.setPreferredSize(new Dimension(1100, 630));
mainPanel.setLayout(new BorderLayout());
JPanel leftPanel = new JPanel();
JPanel rightPanel = new JPanel();
JSplitPane splitPaneH = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
JPanel panelTop = new JPanel();
JPanel panelBottom = new JPanel();
splitPaneH.setTopComponent(panelTop);
splitPaneH.setBottomComponent(panelBottom);
splitPaneH.setDividerLocation(300);
splitPaneH.setPreferredSize(new Dimension(800,630));
mainPanel.add(leftPanel, BorderLayout.WEST);
mainPanel.add(rightPanel,BorderLayout.EAST);
leftPanel.setBackground(Color.RED);
leftPanel.setPreferredSize(new Dimension (300,630));
rightPanel.add(splitPaneH);
return new JPanel[]{mainPanel, leftPanel, rightPanel, panelTop, panelBottom};
}
If you want to change or add some more components inside result JPanel you get you can set names to all your components when you create them:
JPanel newPanel = new JPanel();
newPanel .setName("leftPanel");
resultPanel.add(newPanel, BorderLayout.WEST);
Then when you get resultPanel you can get it's components:
Component[] componentList = resultPanel.getContentPane().getComponents();
JPanel leftPanel = null;
for (Component component: componentList) {
if (Objects.equals(component.getName(), "leftPanel")) {
leftPanel = (JPanel) component;
}
}
if (leftPanel != null) {
// do something
}

Java Button Placement using BorderLayout

This code displays nothing, I have exhausted many avenues but it does not display anything on the GUI (I have a main class that calls this as well already). Please help. I am trying to put the two JButtons horizontally at the bottom of the page and the JTextField and JLabel at the center of the screen.
package test;
import javax.swing.*;
import java.awt.*;
public class Gui extends JFrame {
private JLabel label;
private JButton clear;
private JButton copy;
private JTextField textfield;
public Gui(){
super("test");
clear = new JButton("Clear");
copy = new JButton("Copy");
label = new JLabel("");
textfield = new JTextField("enter text here");
JPanel bottom = new JPanel(new BorderLayout());
JPanel subBottom = new JPanel();
subBottom.add(copy);
subBottom.add(clear);
JPanel centre = new JPanel (new BorderLayout());
JPanel subCentre = new JPanel();
subCentre.add(label);
subCentre.add(textfield);
bottom.add(subBottom, BorderLayout.PAGE_END);
centre.add(subCentre, BorderLayout.CENTER);
}
}
Your code is a bit over-complicated. You only need two panels, centre, and buttons. There are two reasons your UI is not showing up:
You never added the panels to the frame
You never set visible to true(Achieve this by using setVisible(true)), unless you did this in the class you ran it in.
One simple way to achieve your desired UI is like so(I added a main method to show the window):
import javax.swing.*;
import java.awt.*;
public class test extends JFrame {
public Test() {
super("test");
JPanel buttons = new JPanel();
JPanel centre = new JPanel();
add(buttons, BorderLayout.SOUTH); //these lines add the
add(centre, BorderLayout.CENTER); //panels to the frame
JButton clear = new JButton("Clear"); // No need
JButton copy = new JButton("Copy"); // to declare
JLabel label = new JLabel("Label"); // these
JTextField textfield = new JTextField("enter text here"); // privately
buttons.add(copy);
buttons.add(clear);
centre.add(label);
centre.add(textfield);
pack();
setLocationRelativeTo(null);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
} //end constructor
//added main method to run the UI
public static void main(String[] args) {
new Experiments();
} //end main
} //end class
And it shows the window:
I got closer but its not pretty code, the JFrame is 500x500 so this works based on that... any better suggestions than what I have?
package lab6;
import javax.swing.*;
import java.awt.*;
public class Gui extends JFrame {
private JLabel label;
private JButton clear;
private JButton copy;
private JTextField textfield;
public Gui(){
super("test");
clear = new JButton("Clear");
copy = new JButton("Copy");
label = new JLabel("label");
textfield = new JTextField("enter text here");
JPanel masterPanel = new JPanel(new BorderLayout());
JPanel top = new JPanel();
top.setPreferredSize(new Dimension(100, 200));
JPanel bottom = new JPanel();
JPanel subBottom = new JPanel();
subBottom.add(copy);
subBottom.add(clear);
JPanel centre = new JPanel ();
JPanel subCentre = new JPanel();
subCentre.add(label);
subCentre.add(textfield);
bottom.add(subBottom);
centre.add(subCentre);
masterPanel.add(bottom, BorderLayout.PAGE_END);
masterPanel.add(top, BorderLayout.PAGE_START);
masterPanel.add(centre, BorderLayout.CENTER);
add(masterPanel);
}
}

How do I align components in Java Swing?

I'm building a simple beginner app in Java and I need your help with aligning components. What I'm trying to do is to align component(JLabel "name") to the left side of the panel. I've already tried with "new FlowLayout(FlowLayout.LEFT)" but it didn't work so I'm asking you to help me. Here is the picture of the frame and source code below it.
public class firstClass extends JFrame implements ActionListener {
private JFrame frame1;
private JFrame frame2;
private JPanel mainPanelFirst;
private JPanel secondPanel;
private JButton newWindowButton;
private int mulitplyPanels;
private JLabel leftLabel;
private JLabel rightLabel;
private JComboBox leftCB;
private JComboBox rightCB;
First Window:
public JFrame createMainUI(){
frame1 = new JFrame("Main frame");
frame1.setSize(600,600);
frame1.setResizable(false);
frame1.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame1.setVisible(true);
mainPanelFirst = new JPanel();
mainPanelFirst.setLayout(new FlowLayout());
frame1.add(mainPanelFirst);
newWindowButton = new JButton("Open new window");
newWindowButton.addActionListener(this);
mainPanelFirst.add(newWindowButton);
return frame1;
}
Second Window(include the label I want to align):
public JFrame createSecondUI() {
frame2 = new JFrame("Second frame");
frame2.setSize(600, 600);
frame2.setResizable(false);
frame2.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame2.setVisible(true);
secondPanel = new JPanel();
secondPanel.setLayout(new FlowLayout());
secondPanel.setBackground(Color.gray);
frame2.add(secondPanel);
JPanel topPanel = new JPanel();
topPanel.setLayout(new FlowLayout(70,400,20));
topPanel.setBackground(Color.WHITE);
secondPanel.add(topPanel);
leftLabel = new JLabel("Name:");
topPanel.add(leftLabel);
return frame2;
}
#Override
public void actionPerformed(ActionEvent e) {
createSecondUI();
}
}
Thank you for your help :)
Warning read this as well: Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?
Since that the JFrame is non-resizable, give the topPanel a defined size:
JPanel topPanel = new JPanel();
topPanel.setPreferredSize(new Dimension(600,100));
topPanel.setLayout(new FlowLayout(FlowLayout.LEFT,400,20));
I would suggest using a Layout Manager for your app. The one you're looking for is most likely BorderLayout, unless you want specific abilities to control where and how your objects are laid out.
Hope this helps
Layout Managers
How to use BorderLayout

problem in nested Jpanel over Jframe

I have a JFrame and a Jpanel over that in which various buttons are placed.so on click of a button I have called a new class which is also having containers placed in a Jpanel.so I want to show that new class panel over the main Jframe panel.How can I do that?
And if we use card layout in it then how can i use that as on click button i have called an object of a new class.
as
Card layout consider each component in a container as card and i want whole Jpanel as a card so is it possible to do that???
Can We do nesting of Jpanels in it?
Please suggest me a right way to do that?
here is SSCCE:
// this is the main class on which i want to use panel of other class
public class mymain
{
JFrame jframe = new JFrame();
JPanel panel = new JPanel();
BorderLayout borderlayout = new BorderLayout();
public mymain()
{
jframe.setLayout(borderlayout);
JMenuBar menubar = new JMenuBar();
jframe.setJMenuBar(menubar);
JButton home_button = new JButton("HOME");
menubar.add(home_button);
jframe.getContentPane().add(panel,BorderLayout.CENTER);
panel.setLayout(new GridBagLayout());
//here used containers over that frame
and call it from main()
}
here is another class to manage category is
public class manageCategory
{
JPanel panel = new JPanel();
GridBagLayout gridbglayout = new GridBagLayout();
GridBagConstraints gridbgconstraint = new GridBagConstraints();
public manageCategory()
{
panel.setLayout(new BorderLayout());
// i have again here used containers placed with grid bag layout
}
}
So now i want that as i click on home button used in mymain class then the panel that is used in manageCategory() should be displayed on the same panel.and when i again click on home button then the mymain panel get displayed.how can i do that???
I would advise you to use a CardLayout for this task.
Updated example with JPanel and "classes":
static class MainPanel extends JPanel {
public MainPanel(final Container frame) {
add(new JButton(new AbstractAction("Click to view next") {
#Override
public void actionPerformed(ActionEvent e) {
frame.add(new NextPanel(), "NextPanel");
((CardLayout) frame.getLayout()).show(frame, "NextPanel");
}
}));
}
}
static class NextPanel extends JPanel {
public NextPanel() {
add(new JLabel("Next page in the card layout"));
}
}
public static void main(String[] args) throws Exception {
JFrame frame = new JFrame("Test");
frame.setLayout(new CardLayout());
frame.add(new MainPanel(frame.getContentPane()), "MainPanel");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 300);
frame.setVisible(true);
}
CardLayout is one of possible ways, but there are another options valid or required by most completed GUI
1) BorderLayout, because there only one JComponent can occupate decision area
someContainer.add(myPanel, BorderLayout.CENTER)
revalidate();
repaint();
2) GridBagLayout
before anything you have to get declared GridBagConstraints from myOldComponent layed by GridBagLayout
myContainer.setVisible(myOldComponent);
//or
myContainer.remove(myOldComponent);
myContainer.add(myNewComponent, gbc);
revalidate();
repaint();
You can
JFrame myFrame = new JFrame();
JPanel panel1 = new JPanel();
Panel1.setVisible(true);
myFrame.add(panel1);
JPanel panel2 = new JPanel();
Panel2.setVisible(false);
myFrame.add(panel2);
//Here you setup your panels and your actionlisteners etc and when
//you wish for your second panel to show up just run the code below.
panel1.setVisible(false);
panel2.setVisible(true);
Obviously you first have to add both panels to your Jframe. Panel1 will be at first visible, as it is the one shown by default. Panel2 must be set to be invisible in the beginning.

Categories