Open JPanel on JFrame from Button on another panel - java

I'm trying to close a JPanel that's on top of my JFrame.
Now I want to close this panel by clicking a button that's on top of this panel and open another panel on the same frame.
All my panels and my frame is in a separated class.
Here is my idea:
JFrame Class
public MainFrame() throws IOException {
InitializeStartScreen();
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setExtendedState(JFrame.MAXIMIZED_BOTH);
this.setLocationRelativeTo(null);
this.setIconImage(FrameTopIcon.getImage());
this.setTitle("test");
this.setVisible(true);
}
private void InitializeStartScreen() {
StartPanel startPNL = new StartPanel();
this.add(startPNL);
// pack();
}
public static void main(String args[]) throws IOException {
try {
new MainFrame();
}
catch (IOException e) {
throw e;
}
}
JPanel Class
import javax.swing.*;
import java.awt.*;
public class StartPanel extends JPanel {
private LabelButtonCategory Button1 = new LabelButtonCategory("test");
public StartPanel() {
this.setLayout(new GridBagLayout());
InitializeLabelButtons();
this.setBackground(backgroundColor);
this.add(gridPanel);
this.setVisible(true);
}
private void InitializeLabelButtons() {
button1Panel.setBackground(backgroundColor);
ImageIcon iconBtn1 = new ImageIcon("./src/images/CreateBill.png");
Button1.setIcon(iconBtn1);
Button1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
Button1MouseClicked(evt);
}
public void mouseEntered(java.awt.event.MouseEvent evt) {
Button1MouseEntered(evt);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
Button1MouseExited(evt);
}
});
button1Panel.add(Button1);
gridPanel.add(button1Panel);
private void Button1MouseClicked(java.awt.event.MouseEvent evt) {
// CLOSE THIS PANEL AND OPEN ANOTHER PANEL ON FRAME
}

Related

java communication between 2 JFrames

I'm getting an AWT-EventQueue-0 Null Pointer Exception in the below code and I can't get to fix it.
I want to have a main frame, from which by pressing a button
I open a second frame, where I have the option to create new players,
which would show up in the main frame.
I passed the references to the constructors, but I still keep getting the error.
I would be very happy for some help, thanks!
public class Main {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new App();
}
});
}
}
public class App extends JFrame {
private MainPanel mainPanel;
private SecondPanel secondPanel;
public App() {
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(800, 600);
secondPanel = new SecondPanel(mainPanel);
mainPanel = new MainPanel(secondPanel);
add(mainPanel);
}
}
public class MainPanel extends JPanel {
private JTextArea textArea;
private JScrollPane scrollPane;
private JButton options;
public MainPanel(SecondPanel secondPanel) {
textArea = new JTextArea();
textArea.setColumns(20);
textArea.setRows(5);
textArea.setSize(300, 300);
textArea.setVisible(true);
textArea.setEditable(false);
scrollPane = new JScrollPane(textArea);
scrollPane.setSize(new Dimension(400, 400));
options = new JButton("Options");
options.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
secondPanel.setVisible(true);
}
});
add(scrollPane);
add(options);
}
public JTextArea getTextArea() {
return textArea;
}
public void setTextArea(JTextArea textArea) {
this.textArea = textArea;
}
}
public class SecondPanel extends JFrame {
private JButton create, remove;
private JPanel panel;
public SecondPanel(MainPanel mainPanel) {
setVisible(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
panel = new JPanel();
panel.setLayout(new BorderLayout());
create = new JButton("create");
create.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
mainPanel.getTextArea().append("New Player Created");
}
});
remove = new JButton("remove");
remove.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
mp.getTextArea().setText("Player removed");
}
});
add(panel);
panel.add(create, BorderLayout.EAST);
panel.add(remove, BorderLayout.WEST);
}
}
Well, it has to be "null", because you don't initialise your MainPanel before you hand it over to the secondPanel.
Instead, make an own method for setting the MainPanel on the secondPanel and to set the secondPanel on the MainPanel.
I see that you need the secondPanel for instance in your constructor to set an ActionListener. Do that in your "setSecondPanel(SecondPanel sPanel)"-Method which, as I mentioned before, you should create.

how to add Panel from different class on pressing button

i want to add panel from "newWork" class on pressing of "drop" button in "menuPan" class.
i cant add panel.
simply how to add Panel from different class on pressing button.
here are the three different classes .
MainClass :-
public class userFrame extends JFrame{
public void Frame()
{
setTitle("TEST CASE");
setSize(900,670);
add(new MenuPan(),BorderLayout.NORTH);
add(new WorkPan(),BorderLayout.CENTER);
setLocationRelativeTo(this);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String [] args){
userFrame u =new userFrame();
u.Frame();
}
}
MenuPan
public class MenuPan extends JPanel implements ActionListener{
WorkPan work=new WorkPan();
JButton view;
public menuPan() {
setBackground(Color.white);
setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY));
setLayout(new FlowLayout(1, 15, 10));
view=new JButton(" Registered Courses ");
view.addActionListener(this);
add(view);
}
#Override
public void actionPerformed(ActionEvent e) {
work.TaskPannel();
}
}
WorkPAN class :-
class WorkPan extends JPanel{
JPanel work=new JPanel();
public WorkPan() {
setBackground(Color.LIGHT_GRAY);
setLayout(new BorderLayout(40, 50));
}
void TaskPannel() {
System.out.println("here");
add(new NewWork(),BorderLayout.CENTER);// adds NewWork panel
}
}
NewWork Class
class NewWork extends JPanel{
public NewWork(){
setBackground(Color.red);
}
}
One issue -- you create one workPan (which should be renamed WorkPan), change its state in your ActionListener, but never add it to your GUI. So you appear to be changing the state of a non-displayed GUI component, and so it would make sense that nothing will show in the GUI.
Suggestions:
Be sure to create only one WorkPan reference,
Be sure to display this single reference in the GUI
Be sure that your ActionListener calls the appropriate method on the same reference.
Side recommendation:
Learn and follow Java naming conventions so you others can more easily understand and follow your code.
To swap JPanels within a GUI, I strongly advise you to use a CardLayout rather than adding and removing components manually as you're currently doing. Please check out the CardLayout Tutorial.
And my solution does work, but you also must call revalidate and repaint to get the GUI to layout the new component and repaint it. Note additions and changes as marked by the \\ !! comment
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class FooWork {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
userFrame.main(args);
});
}
}
class NewWork extends JPanel {
public NewWork() {
setBackground(Color.red);
}
}
class WorkPan extends JPanel {
JPanel work = new JPanel();
public WorkPan() {
setBackground(Color.LIGHT_GRAY);
setLayout(new BorderLayout(40, 50));
}
void TaskPannel() {
System.out.println("here");
add(new NewWork(), BorderLayout.CENTER);// adds NewWork panel
// !!
revalidate();
repaint();
// !!
}
}
class MenuPan extends JPanel implements ActionListener {
// !! WorkPan work = new WorkPan();
WorkPan work; // !!
JButton view; // !!
// !!
public MenuPan(WorkPan workPan) { // references are key
// !!
this.work = workPan; // set the reference!
// !!
setBackground(Color.white);
setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY));
setLayout(new FlowLayout(1, 15, 10));
view = new JButton(" Registered Courses ");
view.addActionListener(this);
add(view);
}
#Override
public void actionPerformed(ActionEvent e) {
work.TaskPannel();
}
}
class userFrame extends JFrame {
public void Frame() {
setTitle("TEST CASE");
setSize(900, 670);
// !!
WorkPan workPan = new WorkPan();
MenuPan menuPan = new MenuPan(workPan);
// !!
// !!
// add(new MenuPan(), BorderLayout.NORTH);
// add(new WorkPan(), BorderLayout.CENTER);
add(menuPan, BorderLayout.NORTH);
add(workPan, BorderLayout.CENTER);
// !!
setLocationRelativeTo(this);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
userFrame u = new userFrame();
u.Frame();
}
}
But again, cleaner is to use a CardLayout to help with the swapping:
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.*;
public class SwapStuff {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
private static void createAndShowGui() {
SwapMainPanel mainPanel = new SwapMainPanel();
JFrame frame = new JFrame("SwapStuff");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
}
class SwapMainPanel extends JPanel {
private CardLayout cardLayout = new CardLayout();
private JPanel cardPanel = new JPanel(cardLayout);
private ButtonPanel buttonPanel = new ButtonPanel(this); // pass the reference
private WorkPanel workPanel = new WorkPanel();
private ViewPanel viewPanel = new ViewPanel();
public SwapMainPanel() {
cardPanel.add(workPanel, workPanel.getClass().getName());
cardPanel.add(viewPanel, viewPanel.getClass().getName());
setLayout(new BorderLayout());
add(buttonPanel, BorderLayout.PAGE_START);
add(cardPanel, BorderLayout.CENTER);
}
// one possible way to swap "cards"
public void nextCard() {
cardLayout.next(cardPanel);
}
}
class ButtonPanel extends JPanel {
private SwapMainPanel mainPanel;
public ButtonPanel(SwapMainPanel mainPanel) {
this.mainPanel = mainPanel; // set the reference!
add(new JButton(new SwapAction("Swap Panels", KeyEvent.VK_S)));
}
private class SwapAction extends AbstractAction {
public SwapAction(String name, int mnemonic) {
super(name);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
mainPanel.nextCard();
}
}
}
class WorkPanel extends JPanel {
public WorkPanel() {
setBorder(BorderFactory.createTitledBorder("Work Panel"));
}
#Override
public Dimension getPreferredSize() {
return new Dimension(500, 400);
}
}
class ViewPanel extends JPanel {
public ViewPanel() {
setBorder(BorderFactory.createTitledBorder("View Panel"));
setBackground(Color.RED);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(500, 400);
}
}

How to Dispose an opened Jframe from Other

Hi i was wondering how to Dispose a jFrame from another one, cause i want to create a new instance of that class with new values in its textfields, so the First jFrame is this:
public class Frame1 extends javax.swing.JFrame implements ActionListener {
Frame2 f;
public Frame1() {
initComponents();
this.setLocationRelativeTo(null);
}
private void rbtnShowFrame2ActionPerformed(java.awt.event.ActionEvent evt) {
f = new Frame2();
f.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
this.dispose(); //I TRIED TO DISPOSING IT HERE BUT DOESN'T WORK
}
}
So i want in the other jFrame Dispose the jFrame1 only if i trigger the event action performed of a botton, if this doesn't happen i do't want to dispose it, i don't know if i can do it with ActionListener, this is the Second jFrame:
public class Frame2 extends javax.swing.JFrame {
public Frame2() {
initComponents();
this.setLocationRelativeTo(null);
Frame1 f1 = new Frame1();
this.cmdOk.addActionListener(cGUI);
}
private void cmdOkActionPerformed(java.awt.event.ActionEvent evt) {
//Here is where i want to dispose() the other jFrame1
//to create a new instance and pass the value using public static jTextFields
f1.labelNumeroCotizacion.setText(this.labelNumCotizacionEnviar.getText());
f1.setVisible(true);
}
}
Sorry for my Code, i am newbie using OOP! thanks for all guys....
Here is an example of how to dispose a JFrame from another JFrame:
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class Demo
{
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
FrameA one = new FrameA();
FrameB two = new FrameB(one);
one.setVisible(true);
two.setVisible(true);
}
});
}
}
class FrameA extends JFrame
{
private static final long serialVersionUID = 1812279930292019387L;
public FrameA()
{
super("Frame A");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
setLocationRelativeTo(null);
setResizable(false);
}
}
class FrameB extends JFrame
{
private static final long serialVersionUID = 5126089271972476434L;
public FrameB(final JFrame otherFrame)
{
super("Frame B");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
setLayout(new GridBagLayout());
setLocationRelativeTo(otherFrame);
JButton button = new JButton("Dispose Other");
button.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
otherFrame.dispose();
}
});
add(button);
setResizable(false);
}
}

Events on a JPanel which has a Border Layout

When I add a MouseListener/FocusListener to a JPanel which has a BorderLayout and JComponents in it, I can't catch mouse or focus events. Is there any way to catch a JPanel's mouse and focus events which has a BorderLayout?
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Application extends JFrame{
public Application(){
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel jPanel = new JPanel(new BorderLayout());
jPanel.add(new JButton("Button"));
jPanel.addMouseListener(new MouseAdapter() {
#Override
public void mouseExited(MouseEvent e) {
System.out.println("mouseExited");
}
});
// if border is set then listener works if not does not
// jPanel.setBorder(new LineBorder(Color.black, 1));
setLayout(new FlowLayout());
add(jPanel);
setSize(400, 400);
setVisible(true);
}
public static void main(String[]args){
new Application().setVisible(true);
}
}
As said, just a simple mistake. Because JFrame is given a FlowLayout, the JPanel occupies the area required for JButton only. You can test that by adding a Border to the JPanel.
Now it works,
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Application extends JFrame {
private static final long serialVersionUID = 1L;
public Application() {
JPanel jPanel = new JPanel();
jPanel.setLayout(new FlowLayout());
jPanel.add(new JButton("Button"));
jPanel.addMouseListener(new MouseAdapter() {
#Override
public void mouseExited(MouseEvent e) {
System.out.println("mouseExited");
}
});
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
add(jPanel);
setSize(400, 400);
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Application().setVisible(true);
}
});
}
}
The following Code prints the corresponding Events to StdOut.
JFrame frame = new JFrame();
JPanel panel = new JPanel(new BorderLayout());
JPanel innerPanel = new JPanel();
innerPanel.setSize(200,200);
panel.add(innerPanel);
panel.addMouseListener(new MouseListener() {
public void mouseReleased(MouseEvent e) {
System.out.println("MouseReleased");
}
public void mousePressed(MouseEvent e) {
System.out.println("MousePressed");
}
public void mouseExited(MouseEvent e) {
System.out.println("MouseExited");
}
public void mouseEntered(MouseEvent e) {
System.out.println("MouseEntered");
}
public void mouseClicked(MouseEvent e) {
System.out.println("MouseClicked");
}
});
frame.setContentPane(panel);
frame.setVisible(true);`

Adding JApplet into JFrame

I am trying to view a JApplet within a JFrame.
Class: Paint
public void paint(Graphics g) {
g.drawString("hi", 50, 50);
}
public static void main(String args[]) {
JFrame frame = new JFrame("test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setJMenuBar(methodThatReturnsJMenuBar());
JPanel panel = new JPanel(new BorderLayout());
frame.add(panel);
JApplet applet = new Paint();
panel.add(applet, BorderLayout.CENTER);
applet.init();
frame.pack();
frame.setVisible(true);
}
The applet shows up in the Window, but there is no background (it's transparent), and when I click on the Menu, the list is covered. How do I make it so that the Menu list isn't covered, and there is a background?
Edit: When I draw a white rectangle, it fixes the background problem, but the Menu list is still covered.
I would gear my GUI creation towards making a JPanel and then use the JPanel as I desire, either in an JApplet or a JFrame. For e.g.,
import java.awt.*;
import javax.swing.*;
public class MyPanel extends JPanel {
private static final Dimension PREF_SIZE = new Dimension(400, 300);
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawString("hi", 50, 50);
}
#Override
public Dimension getPreferredSize() {
return PREF_SIZE;
}
public JMenuBar methodThatReturnsJMenuBar() {
JMenu menu = new JMenu("Menu");
JMenuBar menuBar = new JMenuBar();
menuBar.add(menu);
return menuBar;
}
}
Then to use in an applet:
import javax.swing.JApplet;
public class MyApplet extends JApplet {
public void init() {
try {
javax.swing.SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
createGUI();
}
});
} catch (Exception e) {
System.err.println("createGUI didn't successfully complete");
}
}
private void createGUI() {
getContentPane().add(new MyPanel());
}
}
Or in a JFrame:
import javax.swing.JFrame;
public class MyStandAlone {
private static void createAndShowUI() {
MyPanel myPanel = new MyPanel();
JFrame frame = new JFrame("MyPanel");
frame.getContentPane().add(myPanel);
frame.setJMenuBar(myPanel.methodThatReturnsJMenuBar());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}

Categories

Resources