Why Does the First Panel Added to a Frame Disappear

Why does the first panel added to a frame disappear?

  • The default layout of a JFrame (or more specifically in this case, the content pane of the frame) is a BorderLayout.
  • When adding a component to a BordeLayout with no constraint, the Swing API will put the component in the CENTER.
  • A BorderLayout can contain exactly one component in each of the 5 layout constraints.
  • When a second component is added to the same (in this case CENTER) constraint of a BorderLayout, this implementation of Java will display the last component added.

As to what would be a better approach depends on the specific needs of the user interface.

Why do my components disappear when added to a panel?

if "this" is the JFrame, this.add(...) won't work. You should add your components to the contentPane of the JFrame.

GUI objects disappearing when adding center panel to my content pane

I have tested your code and it is working with no problems.
Most likely you are adding components some where else to the container, and by default any added components goes to center, which cause the old center panel to be removed , and the the swing frame to draw dirty area.Sample Image

EDIT:

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.GridLayout;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class Test2 extends JFrame {
public Test2() {
begin();
}
public void begin() {
// creates the GUI Objects for the northPanel
JPanel northPanel = new JPanel();
northPanel.setLayout(new GridLayout(1, 4));

JTextField searchBox = new JTextField();
JLabel searchBoxLabel = new JLabel("Search ID #:");
JButton search = new JButton("Search");

northPanel.add(searchBoxLabel);
northPanel.add(searchBox);
northPanel.add(search);

// creates the GUI OBjects for the southPanel
JPanel southDivider = new JPanel();
southDivider.setLayout(new GridLayout(2, 1));

JPanel southPanel = new JPanel();
southPanel.setLayout(new GridLayout(1, 3));

JButton enter = new JButton("Enter");
JButton incrementInfo = new JButton("Increment ID");
JButton setCurrentTimeDate = new JButton("Current Time/Date");
JButton findRate = new JButton("Find Yield Rate");

southPanel.add(findRate);
southPanel.add(setCurrentTimeDate);
southPanel.add(incrementInfo);
southPanel.add(enter);

JLabel messageLabel = new JLabel("Welcome to the Stringer Application");

southDivider.add(southPanel);
southDivider.add(messageLabel);

// create the GUI objects on the eastPanel
JPanel eastPanel = new JPanel();
eastPanel.setLayout(new GridLayout(5, 2));

JComboBox cellType = new JComboBox();
cellType.addItem("Rect");
cellType.addItem("Cham");
JLabel cellTypeLabel = new JLabel("Cell Type:");

JComboBox ecaCode = new JComboBox();
ecaCode.addItem("A");
ecaCode.addItem("B");
JLabel ecaCodeLabel = new JLabel("ECA Code:");

JTextField ecaSyringeNum = new JTextField();
JLabel ecaSyringeNumLabel = new JLabel("Eca Syringe #:");

JComboBox passFail = new JComboBox();
passFail.addItem("Pass");
passFail.addItem("Fail");
JLabel passFailLabel = new JLabel("Pass/Fail:");

JTextField operator = new JTextField();
JLabel operatorLabel = new JLabel("Operator:");

eastPanel.add(operatorLabel);
eastPanel.add(operator);
eastPanel.add(cellTypeLabel);
eastPanel.add(cellType);
eastPanel.add(ecaCodeLabel);
eastPanel.add(ecaCode);
eastPanel.add(ecaSyringeNumLabel);
eastPanel.add(ecaSyringeNum);
eastPanel.add(passFailLabel);
eastPanel.add(passFail);

// create the GUI objects on the westPanel
JPanel westPanel = new JPanel();
westPanel.setLayout(new GridLayout(6, 2));

JLabel yieldLabel = new JLabel("Current Yield:");
JLabel yieldValueLabel = new JLabel("Select Date/Times");
JTextField yieldAfterDate = new JTextField();
JTextField yieldAfterTime = new JTextField();
JTextField yieldBeforeDate = new JTextField();
JTextField yieldBeforeTime = new JTextField();
JLabel yieldAfterDateLabel = new JLabel("After Date:");
JLabel yieldAfterTimeLabel = new JLabel("After Time:");
JLabel yieldBeforeDateLabel = new JLabel("Before Date:");
JLabel yieldBeforeTimeLabel = new JLabel("Before Time:");
JLabel setBeforeToCurrentLabel = new JLabel("<html>'Set to Current' for <br> Current Date/Time</html>");
JButton fillBeforeWithCurrent = new JButton("Set to Current");

westPanel.add(yieldLabel);
westPanel.add(yieldValueLabel);
westPanel.add(yieldAfterDateLabel);
westPanel.add(yieldAfterDate);
westPanel.add(yieldAfterTimeLabel);
westPanel.add(yieldAfterTime);
westPanel.add(yieldBeforeDateLabel);
westPanel.add(yieldBeforeDate);
westPanel.add(yieldBeforeTimeLabel);
westPanel.add(yieldBeforeTime);
westPanel.add(setBeforeToCurrentLabel);
westPanel.add(fillBeforeWithCurrent);

// create the GUI objects for the centerPanel
JPanel centerPanel = new JPanel();
centerPanel.setLayout(new GridLayout(3, 4));

JTextField date = new JTextField();
JLabel dateLabel = new JLabel("Date:");
JTextField time = new JTextField();
JLabel timeLabel = new JLabel("Time:");
JTextField stringID = new JTextField();
JLabel stringIDLabel = new JLabel("String ID:");
JTextField cellLot = new JTextField();
JLabel cellLotLabel = new JLabel("Cell Lot #:");
JTextField cellEff = new JTextField();
JLabel cellEffLabel = new JLabel("Cell Eff:");
JTextField comments = new JTextField();
JLabel commentsLabel = new JLabel("Comments:");

centerPanel.add(dateLabel);
centerPanel.add(date);
centerPanel.add(timeLabel);
centerPanel.add(time);
centerPanel.add(stringIDLabel);
centerPanel.add(stringID);
centerPanel.add(cellLotLabel);
centerPanel.add(cellLot);
centerPanel.add(cellEffLabel);
centerPanel.add(cellEff);
centerPanel.add(commentsLabel);
centerPanel.add(comments);

// add the panel's to the contentPane
Container contentPane = getContentPane();
contentPane.setLayout(new BorderLayout());

contentPane.add(centerPanel, BorderLayout.CENTER);
contentPane.add(northPanel, BorderLayout.NORTH);
contentPane.add(southDivider, BorderLayout.SOUTH);
contentPane.add(eastPanel, BorderLayout.EAST);
contentPane.add(westPanel, BorderLayout.WEST);

// contentPane.validate();
setSize(812, 514);

}

public static void main(String[] args) {
Test2 t=new Test2();

// t.begin();
t.setVisible(true);
}
}

setLayout() to BoxLayout causes JPanels to disappear

Multiple issue:

panel1.setLayout(new BoxLayout(panel1, BoxLayout.Y_AXIS));

JPanel panel2 = new JPanel();
panel2.setLayout(new BoxLayout(panel2, BoxLayout.Y_AXIS));

The Box layout doesn't appear to like that you have set the layout of the child panels and have not entered any components.

So the preferred size of each child panel is (0, 0). So it can't grow.

Delete the above two setLayout(...) statements.

Instead of being split into 67/33, the split is rather 85/15.

Well you have a typo. One panel has a width of 50, the other 300.

The BoxLayout will first allocate the preferred space. Since you hardcoded the size of your frame to 750, you will have roughly 400 pixels of space left over. The BoxLayout will then allocation 200 pixels to each panel to fill the available space.

openingPage.setSize(750, 600);
openingPage.setVisible(true);
openingPage.setLocationRelativeTo(null);
openingPage.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
openingPage.setResizable(false);

The above code should be executed AFTER all components have been added to the frame and the order is important. It should be more like:

openingPage.setResizable(false);
//openingPage.setSize(750, 600);
openingPage.pack();
openingPage.setVisible(true);
openingPage.setLocationRelativeTo(null);
openingPage.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

Normally you should use pack() instead of setSize(...) this layout manager will display the components at their preferred size. You want to set the resizable property before packing the frame since this will affect the border size of the frame. The pack method needs that information.

I suggest you look at the demo code from the Swing tutorial on Layout Manager. The code will show you how to better structure your classes so the GUI is create on the Event Dispatch Thread (EDT).

JPanel disappears when added to more than one other JPanel

I added homeButtonPanel to JPanel gameRoom, and then to JPanel gamePlay.

A component can only have a single parent, so no you can't add the same component to more than one panel.

So you need to create two instances of "homeButtonPanel" and then add an instance to each panel.

Another option is to have your main panel use a BorderLayout. Then you add the panel using the CardLayout to the CENTER of the BorderLayout. Then the "homeButtonPane" can be added to the PAGE_END of this panel, so now it will appear that the homeButtonPanel belongs to both panels in your CardLayout even when you swap panels.

Why is the graphics disappearing from CardLayout?

Below is an example of what you might want to refactor your code to look like (I have omitted non-essential code that you had in your example) in order to get it working. Most notably you will see I use a JPanel and override paintComponent of the panel , call super.paintComponent and then do all the drawing work inside there. Also I override getPreferredSize in order to size the JPanel correctly instead of setSize.

Update:

As per your comment:

first I wanted the panel to appear with just the buttons and then when I hit the drawButton then I want the drawing to appear.:

Simply create a boolean canDraw that is initially set to false, in paintComponent before drawing check the canDraw booleans value and return if it is false. Then in the draw buttons ActionListener do canDraw = true;, and then call welcomPanel.repaint(); which will cause paintComponent to be called and thus because the canDraw is true it should draw the graphics as opposed to returning.

Some other points to keep in mind are:

  1. Don't use a null/AbsoluteLayout rather use an appropriate LayoutManager
  2. Don't call setBounds() or setSize() on components, if you use a correct layout manager this will be handled for you
  3. All Swing components should be called on the EDT via SwingUtilities.invokeLater (perhaps you do this, but I put it here to be safe)
  4. Call JFrame#pack() before setting the frame to visible

Sample Image

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class WelcomePage {

boolean canDraw = false;
private JPanel welcomePanel;

public WelcomePage() {
createAndShowGui();
}

public static void main(String[] args) {
SwingUtilities.invokeLater(WelcomePage::new);
}

private void createAndShowGui() {
JFrame frame = new JFrame("WelcomePage");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// lets use a panel to hold our buttons which has a FlowLayoout and thus we dont need setSize or setBounds
JPanel buttonsPanel = new JPanel();
JButton backButton = new JButton("Back");
JButton drawButton = new JButton("DRAW");
drawButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
canDraw = true;
// repaint will call jpanels paintComponent
welcomePanel.repaint();
}
});
buttonsPanel.add(backButton);
buttonsPanel.add(drawButton);

welcomePanel = new JPanel() {
// override paintComponent of jpanel
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);

// only draw when this is true
if (!canDraw) {
return;
}

g.drawString("CHASE", 200, 90);
g.setColor(Color.yellow);
for (int row = 0; row < 8; row++) {
for (int col = 0; col < 8; col++) {
if (row % 2 == col % 2) {
g.setColor(Color.GRAY);
} else {
g.setColor(Color.RED);
}
g.fillRect(100 + col * 40, 100 + row * 40, 40, 40);
}

}
}

// override getPreferredSize of jpanel to provide the correct size based on the drawing in paintComponent
@Override
public Dimension getPreferredSize() {
return new Dimension(600, 600);
}
};

frame.add(buttonsPanel, BorderLayout.NORTH);
frame.add(welcomePanel, BorderLayout.CENTER);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}


Related Topics



Leave a reply



Submit