Temporarly Cover JFrame with JPanel [duplicate] - java

How to make an added JPanel visible inside a parent JPanel?
I am using Netbeans for designing my UI.
I have a MainFrame.java, which contains two panels; namely headerPanel and bodyPanel.
In headerPanel I have put three buttons,let it be button1, button2 and button3.
Also I have created three separate files extending JPanel, name it panel1, panel2 and panel3.
Then I added all my three panels inside bodypanel in MainFrame.java in constructor.
bodyPanel.add(panel1);
bodyPanel.add(panel2);
bodyPanel.add(panel3);
I want that on clicking the respective buttons only respective panels should appear in the bodypanel in mainframe, i.e. if I click button1 then panel1 should be displayed.
I have already tried the following code in button1 mouse listener method:
bodyPanel.validate();
bodyPanel.getComponent(0).setVisible(true);
But panel1 does not appear. I did it cause added components in a panel are allotted index. So first I tried to get the components and then make it visible. It did not work.

Use a CardLayout, as shown here.

your requirement truely full filled by CARD LAYOUT
see this example link
and below example Link
the perfect code for your problem case is
package panels.examples;
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class MainFrame extends JFrame implements ActionListener
{
JPanel headerPanel;
JPanel bodyPanel;
JPanel panel1,panel2,panel3;
JButton button1,button2,button3;
Container con;
CardLayout clayout;
public MainFrame()
{
//con=getContentPane();
clayout=new CardLayout();
headerPanel=new JPanel();
bodyPanel=new JPanel(clayout);
button1=new JButton("button1");
button2=new JButton("button2");
button3=new JButton("button3");
//add three buttons to headerPanel
headerPanel.add(button1);
headerPanel.add(button2);
headerPanel.add(button3);
button1.addActionListener(this);
button2.addActionListener(this);
button3.addActionListener(this);
panel1=new JPanel();
panel1.add(new JLabel("Panel1"));
panel1.setBackground(Color.pink);
panel2=new JPanel();
panel2.add(new JLabel("Panel2"));
panel2.setBackground(Color.gray);
panel3=new JPanel();
panel3.add(new JLabel("Panel3"));
//add above three panels to bodyPanel
bodyPanel.add(panel1,"one");
bodyPanel.add(panel2,"two");
bodyPanel.add(panel3,"three");
setLayout(new BorderLayout());
setSize(600,450);
add(headerPanel,BorderLayout.NORTH);
add(bodyPanel,BorderLayout.CENTER);
// headerPanel.setBounds(0,0,600,100);
bodyPanel.setBounds(0,100, 600, 500);
setVisible(true);
}
public static void main(String args[])
{
new MainFrame();
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==button1)
{
clayout.show(bodyPanel, "one");
}
else if(e.getSource()==button2)
{
clayout.show(bodyPanel, "two");
}
else if(e.getSource()==button3)
{
clayout.show(bodyPanel, "three");
}
}
}
out put

Use the CardLayout. Below is a Helper class that I have written. Hope it helps.
import java.awt.CardLayout;
import javax.swing.JPanel;
/**
*
* #author Dchan(Dulitha Wijewantha)
*
* This class is used to switch Cards in a CardLayout
*
* #version $Revision: 1.0 $
*/
public class CardLayoutHelper {
private JPanel panel;
private CardLayout layout;
/**
*
* #param panel JPanel
*/
public CardLayoutHelper(JPanel panel) {
this.panel = panel;
this.layout = (CardLayout) this.panel.getLayout();
}
public CardLayoutHelper(JPanel panel, JPanel... panels){
this(panel);
for (int i = 0; i < panels.length; i++) {
JPanel jPanel = panels[i];
panel.add(jPanel.getName(), jPanel);
}
}
/**
*
* #param currentPanel
* - The panel that will be switched into the view
*/
public void switchPanel(JPanel currentPanel) {
panel.removeAll();
panel.add(currentPanel, currentPanel.getName());
layout.show(panel, currentPanel.getName());
panel.revalidate();
panel.repaint();
}
public void switchPanel(String name){
layout.show(panel, name);
panel.revalidate();
panel.repaint();
}
}

Related

Prevent JPanel within JScrollPane from growing horizontally

I have a JPanel with FlowLayout that I'm dynamically filling with identical components (JButtons in the MWE). The JPanel is inside a JScrollPane. As I add components, I'd like them to fill left to right, kicking down to the next row once the top row would become wider than the JScrollPane.
My problem is that FlowLayout is instead widening the JPanel ad nauseum, to which the JScrollPane responds by adding a horizontal scroll. How do I prevent this?
Edit: I've seen WrapLayout; I was hoping for a solution within standard Java since I'm using NetBeans GUI Builder for my application.
MWE based on this answer:
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JPanel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.*;
import javax.swing.JScrollPane;
public class MWE extends JFrame implements ActionListener {
JPanel panel;
JScrollPane pane;
public MWE() {
super("Add component on JFrame at runtime");
setLayout(new BorderLayout());
this.panel = new JPanel();
this.pane = new JScrollPane();
this.panel.setLayout(new FlowLayout(FlowLayout.LEFT));
this.pane.setViewportView(this.panel);
add(pane, BorderLayout.CENTER);
JButton button = new JButton("CLICK HERE");
add(button, BorderLayout.SOUTH);
button.addActionListener(this);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(500, 500);
setVisible(true);
}
public void actionPerformed(ActionEvent evt) {
this.panel.add(new JButton("Button"));
this.panel.revalidate();
validate();
}
public static void main(String[] args) {
MWE mwe = new MWE();
}
}
Try setting a preferred size for the panel :
this.panel.setPreferredSize(new Dimension(500, 500));

Access and change size of Components placed on a JDialog

I created a modal JDialog (to be correct, a children of JDialog) and set it visible when the user clicks on a JButton on a JFrame. To make sure the content on the JDialog is vertically centered I've overridden the setVisible() method and do some operations before calling super.setVisible(true). The problem here is that no component, that's placed on the dialog, does have an other size than 0 before calling setVisible(true) if the dialog is set to be modal. Also setVisible() does block the execution.
Any suggestions/tips how to bypass/fix this issue?
Sample code:
public class SampleDialog extends JDialog {
protected JPanel contentPane;
public SampleDialog() {
super();
setLayout(new BorderLayout());
setDefaultCloseOperation(HIDE_ON_CLOSE);
setModal(true);
JPanel headerPane = new JPanel();
headerPane.setBackground(Color.GREEN);
add(headerPane, BorderLayout.NORTH);
contentPane = new JPanel();
contentPane.setBackground(Color.WHITE);
add(contentPane, BorderLayout.CENTER);
JPanel footerPane = new JPanel();
footerPane.setBackground(Color.YELLOW);
add(footerPane, BorderLayout.SOUTH);
contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS));
contentPane.add(new JLabel("Code"));
contentPane.add(new JTextField());
contentPane.add(new JLabel("Password"));
contentPane.add(new JPasswordField());
contentPane.add(new JButton("Login"));
}
#Override
public void setVisible(boolean b) {
/*
* Get total height of all components added to 'contentPane'
* Place Box.createVerticalStrut() before and after the 'contentPane' components,
* so the input fields look like they are centered vertically
* !!! Cannot determine size of any component because it is not rendered
*/
super.setVisible(b);
}
}
to make sure the content on the JDialog is vertically centered i've overriden the setVisible()
You should NOT be overriding setVisible() for this.
To center the component use an appropriate layout manager.
For example to center components vertically and horizontally you can just use a GridBagLayout:
JDialog dialog = new JDialog();
dialog.setLayout( new GrigBagLayout() );
JPanel panel = new JPanel(...);
panel.add(...);
dialog.add(panel, new GridBagConstraints());
You can use MigLayout manager to easily create your intended layout:
package com.zetcode;
import java.awt.event.ActionEvent;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import net.miginfocom.swing.MigLayout;
/*
* Centering components on screen.
* Author Jan Bodnar
* Website zetcode.com
*/
class MyDialog extends JDialog {
public MyDialog() {
initDialog();
}
private void initDialog() {
JLabel lbl1 = new JLabel("Code");
JTextField field1 = new JTextField(15);
JLabel lbl2 = new JLabel("Password");
JPasswordField field2 = new JPasswordField(15);
JButton btn = new JButton("Login");
createLayout(lbl1, field1, lbl2, field2, btn);
setTitle("Login");
setLocationRelativeTo(null);
setDefaultCloseOperation(HIDE_ON_CLOSE);
setModal(true);
}
private void createLayout(JComponent... arg) {
setLayout(new MigLayout("wrap, align 50% 50%", "[center]"));
add(arg[0]);
add(arg[1]);
add(arg[2]);
add(arg[3]);
add(arg[4]);
pack();
}
}
public class MigLayoutCenterEx extends JFrame {
public MigLayoutCenterEx() {
initUI();
}
private void initUI() {
JPanel pnl = new JPanel();
JButton btn = new JButton("Show dialog");
btn.addActionListener((ActionEvent e) -> {
JDialog dialog = new MyDialog();
dialog.setVisible(true);
});
pnl.add(btn);
add(pnl);
setSize(400, 300);
setTitle("MigLayout example");
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
MigLayoutCenterEx ex = new MigLayoutCenterEx();
ex.setVisible(true);
});
}
}
Screenshot:

Set JTextFields and JButtons position in CardLayout

This is a java template i found about Card Layout
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Main {
private static final String CARD_JBUTTON = "Card JButton";
private static final String CARD_JTEXTFIELD = "Card JTextField";
private static final String CARD_JRADIOBUTTON = "Card JRadioButton";
private static void createAndShowGUI()
{
JFrame frame = new JFrame("Card Layout Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
// This JPanel is the base for CardLayout for other JPanels.
final JPanel contentPane = new JPanel();
contentPane.setLayout(new CardLayout(200, 200));
/* Here we be making objects of the Window Series classes
* so that, each one of them can be added to the JPanel
* having CardLayout.
*/
Window1 win1 = new Window1();
contentPane.add(win1, CARD_JBUTTON);
Window2 win2 = new Window2();
contentPane.add(win2, CARD_JTEXTFIELD);
Window3 win3 = new Window3();
contentPane.add(win3, CARD_JRADIOBUTTON);
/* We need two JButtons to go to the next Card
* or come back to the previous Card, as and when
* desired by the User.
*/
JPanel buttonPanel = new JPanel();
final JButton previousButton = new JButton("PREVIOUS");
previousButton.setBackground(Color.BLACK);
previousButton.setForeground(Color.WHITE);
final JButton nextButton = new JButton("NEXT");
nextButton.setBackground(Color.RED);
nextButton.setForeground(Color.WHITE);
buttonPanel.add(previousButton);
buttonPanel.add(nextButton);
/* Adding the ActionListeners to the JButton,
* so that the user can see the next Card or
* come back to the previous Card, as desired.
*/
previousButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
CardLayout cardLayout = (CardLayout) contentPane.getLayout();
cardLayout.previous(contentPane);
}
});
nextButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
CardLayout cardLayout = (CardLayout) contentPane.getLayout();
cardLayout.next(contentPane);
}
});
// Adding the contentPane (JPanel) and buttonPanel to JFrame.
frame.add(contentPane, BorderLayout.CENTER);
frame.add(buttonPanel, BorderLayout.PAGE_END);
frame.pack();
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
}
And this is my Window1.java
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
class Window1 extends JPanel
{
/*
* Here this is our first Card of CardLayout, which will
* be added to the contentPane object of JPanel, which
* has the LayoutManager set to CardLayout.
* This card consists of Two JButtons.
*/
private ActionListener action;
public Window1()
{
init();
}
private void init()
{
final JButton clickButton = new JButton("Click ME");
final JButton dontClickButton = new JButton("DON\'T CLICK ME");
final JTextField title = new JTextField(12);
action = new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
if (ae.getSource() == clickButton)
{
String myString = title.getText();
System.out.println(myString);
}
else if (ae.getSource() == dontClickButton)
{
JOptionPane.showMessageDialog(null, "I told you not to click me!"
, "Wrong Button", JOptionPane.PLAIN_MESSAGE);
}
}
};
clickButton.addActionListener(action);
dontClickButton.addActionListener(action);
add(clickButton);
add(dontClickButton);
add(title);
}
}
Now my problem is that how do i set the position of the textfields and buttons in Window1?
With this code they are set in the center of the view aligned horizontally.
I tried to use title.setLocation(5,5); but it's not working. Any suggestions?
Now my problem is that how do i set the position of the textfields and buttons in Window1?
Rows like Jlabel - JTextField then new row ,and in the end of the page the button
The thing is you're not using any layout managers. The default layout manager for JPanel is FlowLayout, which will do exactly what you're experiencing (horizontal layout of the components).
Getting vertical alignment could be achieved by using different layout managers. You could use a GridBagLayout for all the component, or a GridLayout, or you could nest JPanel with different layout managers. The possibilities are endless. It just comes down to the exact look you want.
See Laying out Components Within a Container to learn how to use different layout managers. I'll give you an example, but don't let it stop you from looking at the tutorials. You need to learn them.
Also besides just positioning of the components layout managers use dynamic sizing either by respecting the preferred of components are not respecting them. You can see a picture in this answer of some of the layout managers that do and don't respect preferred sizes.
import java.awt.FlowLayout;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class LayoutManagers extends JPanel{
public LayoutManagers() {
JLabel label = new JLabel("Text Field");
JTextField textField = new JTextField(20);
JRadioButton rb1 = new JRadioButton("Radio 1");
JRadioButton rb2 = new JRadioButton("Radio 2");
JButton button = new JButton("Button");
JPanel panel1 = new JPanel();
panel1.add(label);
panel1.add(textField);
JPanel panel2 = new JPanel();
panel2.add(rb1);
panel2.add(rb2);
JPanel panel3 = new JPanel(new FlowLayout(FlowLayout.TRAILING));
panel3.add(button);
JPanel panel4 = new JPanel(new GridLayout(3, 1));
panel4.add(panel1);
panel4.add(panel2);
panel4.add(panel3);
setLayout(new GridBagLayout());
add(panel4);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
JFrame frame = new JFrame();
frame.add(new LayoutManagers());
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
});
}
}

How can I replace one of two JPanels with another JPanel in Java?

I designed an interface for the welcome screen with one JFrame included two JPanels (JPanel1 on right and JPanel2 on left). The buttons on the left is to switch the Panels in JPanel1. I want to press on a button to replace JPanel1 content with another JPanel but I don`t know how. Please help.
Here is a very simple example of something that should approximate your description. On the left, we have a hug button to toggle the content of the right panel. On the right, you have a panel with a given border and a label. When you press the button, the content on the right is swapped with the other panel.
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Dimension;
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.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class TestCardLayout2 {
protected void initUI() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel leftPanel = new JPanel(new BorderLayout());
JLabel label = new JLabel("Left panel");
leftPanel.add(label, BorderLayout.NORTH);
JButton button = new JButton("Toggle right panel");
leftPanel.add(button);
frame.add(leftPanel, BorderLayout.WEST);
final CardLayout cardLayout = new CardLayout();
final JPanel rightPanel = new JPanel(cardLayout);
rightPanel.setPreferredSize(new Dimension(200, 500));
JPanel rightPanel1 = new JPanel(new FlowLayout(FlowLayout.LEFT));
rightPanel1.setBorder(BorderFactory.createLineBorder(Color.RED));
JPanel rightPanel2 = new JPanel(new FlowLayout(FlowLayout.RIGHT));
rightPanel2.setBorder(BorderFactory.createLineBorder(Color.BLUE));
JLabel label1 = new JLabel("Right panel 1 with a red border");
JLabel label2 = new JLabel("Right panel 2 with a blue borer");
rightPanel1.add(label1);
rightPanel2.add(label2);
rightPanel.add(rightPanel1, "panel1");
rightPanel.add(rightPanel2, "panel2");
frame.add(rightPanel, BorderLayout.EAST);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
cardLayout.next(rightPanel);
}
});
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new TestCardLayout2().initUI();
}
});
}
}
An alternative to CardLayout would be JRootPane and its JRootPane.setContentPane() method. Here's an example:
final JPanel panel1 = ...;
final JPanel panel2 = ...;
boolean showingPanel1 = true;
final JRootPane rootPane = new JRootPane();
rootPane.setContentPane(panel1);
JButton switchButton = new JButton("Switch");
switchButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if (showingPanel1) {
rootPane.setContentPane(panel2);
} else {
rootPane.setContentPane(panel1);
}
showingPanel = !showingPanel;
}
});
Add the rootPane and switchButton components to your window, and then clicking switchButton will switch out the panels.
Here's a tutorial. You should mostly be concerned with JRootPane.setContentPane, the other stuff in the tutorial isn't relevant.
The best answer I found is that I will create one JFrame only and gonna make one big JPanel include two JPanels (JPanelLeft include the buttons and JPanelRight include what the button do) then I will copy the main JPanel for each JButton.
When I press on any button I will do (JFrame.getContentPane.removeAll) to remove the old JPanel then (JFrame.getContentPane.Add(NewJPanel).
This works for me and keep my design as I Want. Thanks for every body.

JPanel layout in applet

I have a JPanel that is not part of a JFrame. For various reasons I have to call the panel's paint method through my own "update" method.
This is my code:
public void onLoad ()
{
panel = new JPanel ();
panel.setBounds (0,0,Main.WIDTH,Main.HEIGHT);
panel.setLayout (new BoxLayout (panel, BoxLayout.Y_AXIS));
addButton ("button1", panel);
addButton ("button2", panel);
}
private void addButton (String text, Container container)
{
JButton button = new JButton (text);
button.setPreferredSize (new Dimension (100,20));
button.setAlignmentX (Component.CENTER_ALIGNMENT);
container.add (button);
}
public void onRender (Graphics2D g)
{
panel.paint (g);
}
This only paints the panel's background color. If I add button.setBounds(...) in the addButton method then it does paint the buttons but not affected by the BoxLayout.
So I want the buttons to be affected by the BoxLayout obviously. I'm not that savvy on how exactly Swing works so I'm not sure how to do this. JFrame has a pack() method which I think is what I need but some equivalent for JPanels since JPanels doesn't have that method.
I don't know what you're looking for, but for me this works well.
import java.awt.Component;
import java.awt.Dimension;
import javax.swing.BoxLayout;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class TestApplet extends JApplet{
public static void main(String[] args){
new TestApplet();
}
public TestApplet(){
this.setSize(400,400);
this.add(getCustPanel());
this.setVisible(true);
}
private JPanel getCustPanel() {
JPanel panel = new JPanel ();
panel.setLayout (new BoxLayout(panel, BoxLayout.Y_AXIS));
addButton ("button1", panel);
addButton ("button2", panel);
return panel;
}
private void addButton (String text, JPanel container)
{
JButton button = new JButton (text);
button.setPreferredSize (new Dimension(100,20));
button.setAlignmentX (Component.CENTER_ALIGNMENT);
container.add (button);
}
}

Categories