I am creating a very simple graphical interface for an artificial sales system, and I am trying to show two screens ("Sales" and "Home") with buttons for switching to another jpanel, and with "Quit" on both to close the application.
I use the following code, I thought that I can use the same code for other buttons as for the Exit button, however, the Exit appears only on the Sale page, and not on the main page.
import java.awt.Font;
import java.awt.event.*;
import javax.swing.*;
public class PHPSRSFrame implements ActionListener
{
public static final int WIDTH = 800;
public static final int HEIGHT = 600;
public static final int BUTTON_WIDTH = 115;
public static final int BUTTON_HEIGHT = 30;
public static final int HEADING_WIDTH = 350;
public static final int HEADING_HEIGHT = 35;
private JFrame frame;
private JPanel homePanel, salesPanel;
private JButton salesButton, homeButton, quitButton;
public PHPSRSFrame()
{
frame = new JFrame("PHP Sales Reporting System");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
homePanel = new JPanel();
homePanel.setLayout(null);
salesPanel = new JPanel();
salesPanel.setLayout(null);
JLabel lblPhpSalesReporting = new JLabel("Welcome");
lblPhpSalesReporting.setFont(new Font("Arial Black", Font.BOLD, 24));
lblPhpSalesReporting.setBounds(WIDTH/2-HEADING_WIDTH/2, 50, HEADING_WIDTH, HEADING_HEIGHT);
JLabel lblSales = new JLabel("Sales");
lblSales.setFont(new Font("Arial Black", Font.BOLD, 24));
lblSales.setBounds(WIDTH/2-100/2, 50, 100, HEADING_HEIGHT);
salesButton = new JButton("Sales");
salesButton.setBounds(WIDTH/2-BUTTON_WIDTH/2, 150, BUTTON_WIDTH, BUTTON_HEIGHT);
salesButton.addActionListener(this);
homeButton = new JButton("Home");
homeButton.setBounds(20, 20, BUTTON_WIDTH, BUTTON_HEIGHT);
homeButton.addActionListener(this);
quitButton = new JButton("Quit");
quitButton.setBounds(650, 500, BUTTON_WIDTH, BUTTON_HEIGHT);
quitButton.addActionListener(this);
homePanel.add(lblPhpSalesReporting);
homePanel.add(salesButton);
homePanel.add(quitButton);
salesPanel.add(homeButton);
salesPanel.add(lblSales);
salesPanel.add(quitButton);
frame.setContentPane(homePanel);
frame.setSize(WIDTH, HEIGHT);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent ae)
{
JButton button = (JButton) ae.getSource();
if (button == salesButton)
{
frame.remove(homePanel);
frame.setContentPane(salesPanel);
}
else if (button == homeButton)
{
frame.remove(salesPanel);
frame.setContentPane(homePanel);
}
else if (button == quitButton) {
System.exit(0);
}
frame.revalidate();
frame.repaint();
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
@Override
public void run()
{
new PHPSRSFrame();
}
});
}
}
Can someone please tell me what I am missing / did wrong, which leads to the fact that the "home" button ONLY appears on the sales page?
Thankyou.