Days ago i asked for help to put a JPanel on top of the other CardLayout panels, with the help of one of the users i achieved it using GlassPane, so thanks to him, but now i wanna close it whenever i click outside it(in other windows of the applications or components) because its stuck there until i click settings button, how can i achieve that? I have tried with focus lost and gained but that doesn't work with the panel so what am i supposed to do, here is my piece of code..
JPanel settingsPanel = new JPanel();
settingsPanel.setLayout(null);
settingsPanel.setPreferredSize(
new Dimension(180, 260));
JLabel lblSettingsTitle = new JLabel("Settings");
lblSettingsTitle.setFont(new Font("SansSerif", Font.BOLD |
Font.ITALIC, 18));
lblSettingsTitle.setBounds(5, 8, 200, 35);
settingsPanel.add(lblSettingsTitle);
JSeparator settingsSep = new JSeparator();
settingsSep.setForeground(Color.DARK_GRAY);
settingsSep.setBounds(0, 48, 160, 2);
settingsPanel.add(settingsSep);
JPanel panelLanguage = new JPanel();
panelLanguage.setBounds(0, 61, 200, 30);
settingsPanel.add(panelLanguage);
panelLanguage.setLayout(null);
JPanel pnlLanguage = new JPanel();
pnlLanguage.setBounds(0, 0, 200, 30);
panelLanguage.add(pnlLanguage);
pnlLanguage.setLayout(null);
JLabel lblLanguageIcon = new JLabel("");
lblLanguageIcon.setIcon(new
ImageIcon(frmMain.class.getResource("/image/Language_20px.png")));
lblLanguageIcon.setBounds(5, 5, 20, 20);
pnlLanguage.add(lblLanguageIcon);
JLabel lblLanguage = new JLabel("Choose Language");
lblLanguage.setFont(new Font("SansSerif", Font.ITALIC, 15));
lblLanguage.setBounds(30, 0, 170, 30);
pnlLanguage.add(lblLanguage);
JPanel pnlAlbanian = new JPanel();
pnlAlbanian.setBounds(0, 30, 200, 30);
panelLanguage.add(pnlAlbanian);
pnlAlbanian.setLayout(null);
JLabel lblAlbIcon = new JLabel("");
lblAlbIcon.setIcon(new
ImageIcon(frmMain.class.getResource("/image/albanian.png")));
lblAlbIcon.setBounds(20, 0, 30, 30);
pnlAlbanian.add(lblAlbIcon);
JLabel lblAlbanian = new JLabel("Albanian");
lblAlbanian.setBounds(50, 0, 150, 30);
pnlAlbanian.add(lblAlbanian);
JPanel pnlEnglish = new JPanel();
pnlEnglish.setBounds(0, 60, 200, 30);
panelLanguage.add(pnlEnglish);
pnlEnglish.setLayout(null);
JLabel lblEngIcon = new JLabel("");
lblEngIcon.setIcon(new
ImageIcon(frmMain.class.getResource("/image/britain.png")));
lblEngIcon.setBounds(20, 0, 30, 30);
pnlEnglish.add(lblEngIcon);
JLabel lblEnglish = new JLabel("English");
lblEnglish.setBounds(50, 0, 150, 30);
pnlEnglish.add(lblEnglish);
JPanel pnlAboutUs = new JPanel();
pnlAboutUs.setBounds(0, 120, 200, 30);
settingsPanel.add(pnlAboutUs);
pnlAboutUs.setLayout(null);
JLabel lblAboutIcon = new JLabel("");
lblAboutIcon.setIcon(new
ImageIcon(frmMain.class.getResource("/image/About_20px.png")));
lblAboutIcon.setBounds(5, 5, 20, 20);
pnlAboutUs.add(lblAboutIcon);
JLabel lblAboutUs = new JLabel("About Us");
lblAboutUs.setFont(new Font("SansSerif", Font.ITALIC, 15));
lblAboutUs.setBounds(35, 0, 165, 30);
pnlAboutUs.add(lblAboutUs);
JPanel pnlHelp = new JPanel();
pnlHelp.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
Help obj=new Help();
getGlassPane().setVisible(false);
obj.setVisible(true);
obj.setLocationRelativeTo(null);
}
});
pnlHelp.setLayout(null);
pnlHelp.setBounds(0, 91, 200, 30);
settingsPanel.add(pnlHelp);
JLabel lblHelpIcon = new JLabel("");
lblHelpIcon.setIcon(new
ImageIcon(frmMain.class.getResource("/image/Help_20px.png")));
lblHelpIcon.setBounds(5, 5, 20, 20);
pnlHelp.add(lblHelpIcon);
JLabel lblHelp = new JLabel("Help");
lblHelp.setFont(new Font("SansSerif", Font.ITALIC, 15));
lblHelp.setBounds(35, 0, 165, 30);
pnlHelp.add(lblHelp);
((JComponent) getGlassPane()).setLayout(new
FlowLayout(FlowLayout.LEFT, 260, 390));
((JComponent) getGlassPane()).add(settingsPanel, BorderLayout.EAST);
JLabel lblSettings = new JLabel("");
lblSettings.setHorizontalAlignment(SwingConstants.CENTER);
lblSettings.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
getGlassPane().setVisible(!getGlassPane().isVisible());
}
});
lblSettings.setToolTipText("Settings");
lblSettings.setIcon(new
ImageIcon(frmMain.class.getResource("/image/Settings_24px.png")));
lblSettings.setBounds(210, 600, 50, 50);
menuPanel.add(lblSettings);
I've slightly modified my previous example, so the settings panel goes closed on the click outside it.
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
public class RightSidePanel implements Runnable {
#Override
public void run() {
JFrame frm = new JFrame("Right side panel");
frm.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
// next two lines are not required
JPanel contentPanel = new JPanel(new BorderLayout());
frm.setContentPane(contentPanel);
JPanel mainPanel = new JPanel(new CardLayout());
mainPanel.add(new JLabel("It's the first card panel"), "first");
mainPanel.add(new JLabel("It's the second card panel"), "second");
// add some components to provide some width and height for the panel.
mainPanel.add(Box.createHorizontalStrut(600));
mainPanel.add(Box.createVerticalStrut(300));
mainPanel.setBackground(Color.CYAN);
JPanel settingsPanel = new JPanel(new GridLayout(1, 1));
settingsPanel.add(new JLabel("Here is the settings panel!"));
settingsPanel.setPreferredSize(new Dimension(settingsPanel.getPreferredSize().width, 300));
JButton settingsButton = new JButton("Show settings"); // move this line up
((JComponent) frm.getGlassPane()).setLayout(new FlowLayout(FlowLayout.RIGHT, 0, 0));
((JComponent) frm.getGlassPane()).add(settingsPanel);
// added code here
frm.getGlassPane().addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
// check whether the click on the glass pane.
Component c = SwingUtilities.getDeepestComponentAt(frm.getGlassPane(), e.getX(), e.getY());
if (e.getComponent().equals(c)) {
updateButton(frm, settingsButton);
}
}
});
// end of the added code
JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 10, 10));
settingsButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// move the method content to a separate method
updateButton(frm, settingsButton);
}
});
JButton switchButton = new JButton("Show second");
switchButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
CardLayout cl = (CardLayout) mainPanel.getLayout();
if (mainPanel.getComponent(0).isVisible()) {
cl.show(mainPanel, "second");
switchButton.setText("Show first");
} else {
cl.show(mainPanel, "first");
switchButton.setText("Show second");
}
}
});
buttonPanel.add(switchButton);
buttonPanel.add(settingsButton);
frm.add(mainPanel, BorderLayout.CENTER);
frm.add(buttonPanel, BorderLayout.SOUTH);
frm.pack();
frm.setLocationRelativeTo(null);
frm.setVisible(true);
}
private void updateButton(JFrame frm, JButton settingsButton) {
frm.getGlassPane().setVisible(!frm.getGlassPane().isVisible());
if (frm.getGlassPane().isVisible()) {
settingsButton.setText("Hide settings");
} else {
settingsButton.setText("Show settings");
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new RightSidePanel());
}
}
Related
I'm doing this as a challenge for myself. My problem is that when I click on the button, the content pane appears plain even if the JPanel has components in it.
I've tried adding the components on the frame but I get an error: >Cannot read field "parent" because "comp" is null.
I've tried other layout on JFrame and JPanel and still it didn't show.
Here's the full code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DecimalFormat;
public class test implements ActionListener{
public static void main(String [] args) {
new test();
}
static JPanel mainPanel, cubePanel;
static JFrame frame;
static Container container = new Container();
static JLabel calculatorFor;
static JButton sphereButton, rightCylinderButton, rightConeButton, rectangularPrismButton, triangularPrismButton,
cubeButton, squarePyramidButton, rectangularPyramidButton, ellipsoidButton, tetrahedronButton ,backToPreviousFrameButton;
static Font font = new Font(null, Font.PLAIN, 30);
static JLabel enterValueForEdge;
static JTextField edgeTextField;
static JTextArea surfaceAreaTextArea, surfaceAreaFormulaTextArea, surfaceAreaSolutionTextArea;
static JButton calculateButton;
static double edge;
static DecimalFormat surfaceAreaDecimal;
public test(){
frame = new JFrame("Calculating for Surface Area");
calculatorFor = new JLabel("Calculator for the Surface Area of:");
calculatorFor.setSize(600, 40);
calculatorFor.setLocation(100, 50);
calculatorFor.setFont(font);
calculatorFor.setFocusable(false);
sphereButton = new JButton("Sphere ");
sphereButton.setSize(400, 40);
sphereButton.setLocation(100, 100);
sphereButton.setFont(font);
sphereButton.addActionListener(this);
sphereButton.setFocusable(false);
rightCylinderButton = new JButton("Right Cylinder");
rightCylinderButton.setSize(400, 40);
rightCylinderButton.setLocation(100, 150);
rightCylinderButton.setFont(font);
rightCylinderButton.addActionListener(this);
rightCylinderButton.setFocusable(false);
rightConeButton = new JButton("Right Cone");
rightConeButton.setSize(400, 40);
rightConeButton.setLocation(100, 200);
rightConeButton.setFont(font);
rightConeButton.addActionListener(this);
rightConeButton.setFocusable(false);
rectangularPrismButton = new JButton("Rectangular Prism");
rectangularPrismButton.setSize(400, 40);
rectangularPrismButton.setLocation(100, 250);
rectangularPrismButton.setFont(font);
rectangularPrismButton.addActionListener(this);
rectangularPrismButton.setFocusable(false);
triangularPrismButton = new JButton("Triangular Prism");
triangularPrismButton.setSize(400, 40);
triangularPrismButton.setLocation(100, 300);
triangularPrismButton.setFont(font);
triangularPrismButton.addActionListener(this);
triangularPrismButton.setFocusable(false);
cubeButton = new JButton("Cube");
cubeButton.setSize(400, 40);
cubeButton.setLocation(100, 350);
cubeButton.setFont(font);
cubeButton.addActionListener(this);
cubeButton.setFocusable(false);
squarePyramidButton = new JButton("Square Pyramid");
squarePyramidButton.setSize(400, 40);
squarePyramidButton.setLocation(100, 400);
squarePyramidButton.setFont(font);
squarePyramidButton.addActionListener(this);
squarePyramidButton.setFocusable(false);
rectangularPyramidButton = new JButton("Rectangular Pyramid");
rectangularPyramidButton.setSize(400, 40);
rectangularPyramidButton.setLocation(100, 450);
rectangularPyramidButton.setFont(font);
rectangularPyramidButton.addActionListener(this);
rectangularPyramidButton.setFocusable(false);
ellipsoidButton = new JButton("Ellipsoid");
ellipsoidButton.setSize(400, 40);
ellipsoidButton.setLocation(100, 500);
ellipsoidButton.setFont(font);
ellipsoidButton.addActionListener(this);
ellipsoidButton.setFocusable(false);
tetrahedronButton = new JButton("Tetrahedron");
tetrahedronButton.setSize(400, 40);
tetrahedronButton.setLocation(100, 550);
tetrahedronButton.setFont(font);
tetrahedronButton.addActionListener(this);
tetrahedronButton.setFocusable(false);
backToPreviousFrameButton = new JButton("Back");
backToPreviousFrameButton.setSize(100, 40);
backToPreviousFrameButton.setLocation(900, 600);
backToPreviousFrameButton.setFont(font);
backToPreviousFrameButton.addActionListener(this);
backToPreviousFrameButton.setFocusable(false);
mainPanel = new JPanel();
mainPanel.setBounds(0, 0, 1080, 720);
mainPanel.setLayout(null);
mainPanel.setBackground(Color.decode("#FAF7FC"));
mainPanel.add(calculatorFor);
mainPanel.add(sphereButton);
mainPanel.add(rightCylinderButton);
mainPanel.add(rightConeButton);
mainPanel.add(rectangularPrismButton);
mainPanel.add(triangularPrismButton);
mainPanel.add(cubeButton);
mainPanel.add(squarePyramidButton);
mainPanel.add(rectangularPyramidButton);
mainPanel.add(ellipsoidButton);
mainPanel.add(tetrahedronButton);
mainPanel.add(backToPreviousFrameButton);
frame.getContentPane().add(mainPanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setBackground(Color.decode("#FAF7FC"));
frame.setLayout(new BorderLayout());
frame.setSize(1080,720);
frame.setResizable(false);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
}
public void cubePanel(){
enterValueForEdge = new JLabel("Enter Edge:");
enterValueForEdge.setSize(200, 40);
enterValueForEdge.setLocation(100, 50);
enterValueForEdge.setFont(font);
enterValueForEdge.setFocusable(false);
edgeTextField = new JTextField();
edgeTextField.setSize(400, 40);
edgeTextField.setLocation(300, 50);
edgeTextField.setFont(font);
calculateButton = new JButton("Calculate");
calculateButton.setSize(200, 40);
calculateButton.setLocation(100, 100);
calculateButton.setFont(font);
calculateButton.addActionListener(this);
calculateButton.setFocusable(false);
surfaceAreaFormulaTextArea = new JTextArea("SA = 6a²");
surfaceAreaFormulaTextArea.setSize(400, 40);
surfaceAreaFormulaTextArea.setLocation(100, 150);
surfaceAreaFormulaTextArea.setFont(font);
surfaceAreaFormulaTextArea.setEditable(false);
surfaceAreaTextArea = new JTextArea("SA: ");
surfaceAreaTextArea.setSize(500, 40);
surfaceAreaTextArea.setLocation(100, 200);
surfaceAreaTextArea.setFont(font);
surfaceAreaTextArea.setEditable(false);
surfaceAreaSolutionTextArea = new JTextArea();
surfaceAreaSolutionTextArea.setSize(900, 80);
surfaceAreaSolutionTextArea.setLocation(100, 250);
surfaceAreaSolutionTextArea.setFont(font);
surfaceAreaSolutionTextArea.setEditable(false);
surfaceAreaSolutionTextArea.setLineWrap(true);
backToPreviousFrameButton = new JButton("Back");
backToPreviousFrameButton.setSize(100, 40);
backToPreviousFrameButton.setLocation(900, 600);
backToPreviousFrameButton.setFont(font);
backToPreviousFrameButton.addActionListener(this);
backToPreviousFrameButton.setFocusable(false);
cubePanel = new JPanel();
cubePanel.setBounds(0, 0, 1080, 720);
cubePanel.setLayout(null);
cubePanel.setBackground(Color.decode("#FAF7FC"));
container = new Container();
cubePanel.add(enterValueForEdge);
cubePanel.add(edgeTextField);
cubePanel.add(calculateButton);
cubePanel.add(surfaceAreaFormulaTextArea);
cubePanel.add(surfaceAreaTextArea);
cubePanel.add(surfaceAreaSolutionTextArea);
cubePanel.add(backToPreviousFrameButton);
container.add(cubePanel);
container.setLayout(null);
container.setBackground(Color.decode("#FAF7FH"));
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == sphereButton){
new sphereFrame();
frame.dispose();
}
if(e.getSource() == rightCylinderButton){
new rightCylinderFrame();
frame.dispose();
}
if(e.getSource() == rightConeButton){
new rightConeFrame();
frame.dispose();
}
if(e.getSource() == rectangularPrismButton){
new rectangularPrismFrame();
frame.dispose();
}
if(e.getSource() == triangularPrismButton){
new triangularPrismFrame();
frame.dispose();
}
if(e.getSource() == cubeButton){
frame.getContentPane().removeAll();
frame.add(cubePanel);
frame.repaint();
frame.revalidate();
System.out.println("Remove");
frame.getContentPane().add(container);
}
}
Oracle has a helpful tutorial, Creating a GUI With Swing. Skip the Learning Swing with the NetBeans IDE section. Pay particular attention to the Laying Out Components Within a Container section.
Here's the GUI I created.
Press the "Cube" button to bring up the page for the cube calculation.
All Swing applications must start with a call to the SwingUtilities invokeLater method. This method ensures that the Swing components are created and executed on the Event Dispatch Thread.
The JFrame has a default BorderLayout and holds the main JPanel. The main JPanel uses a CardLayout to display the various calculation JPanels. Using a CardLayout is much easier than managing multiple JFrames and provides a nicer user experience.
I used Swing layout managers to position the Swing components on the various JPanels.
The start JPanel consists of two subordinate JPanels. The title JPanel uses a FlowLayout to display the title. The button JPanel uses a GridLayout to display the various calculation JButtons. You can create complex JPanels by nesting multiple simple JPanels.
The cube calculation JPanel was the only one you had in your code, so it was the only one I created. I made it a method, but you can create a separate class for each of the calculations. The cube calculation JPanel uses a GridBagLayout to create a form-like JPanel. I used lambda expressions to create the ActionListener for each of the JButtons, since they were so simple.
I made the start JPanel button ActionListener a separate class just to get the code away from the for loop that creates the JButtons.
Here's the complete runnable code.
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
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.JTextField;
import javax.swing.SwingUtilities;
public class CardLayoutGUI implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new CardLayoutGUI());
}
private CardLayout cardLayout;
private JTextField edgeTextField, surfaceAreaSolutionTextField;
private JPanel mainPanel;
#Override
public void run() {
JFrame frame = new JFrame("Calculating for Surface Area");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.mainPanel = createMainPanel();
frame.add(mainPanel, BorderLayout.CENTER);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createMainPanel() {
cardLayout = new CardLayout();
JPanel panel = new JPanel(cardLayout);
panel.setBorder(BorderFactory.createEmptyBorder(0, 5, 5, 5));
panel.add(createStartPanel(), "Start");
panel.add(createCubeCalculationPanel(), "Cube");
return panel;
}
private JPanel createStartPanel() {
JPanel panel = new JPanel(new BorderLayout());
panel.setBorder(BorderFactory.createEmptyBorder(0, 5, 5, 5));
panel.add(createTitlePanel(), BorderLayout.NORTH);
panel.add(createButtonPanel(), BorderLayout.CENTER);
return panel;
}
private JPanel createTitlePanel() {
JPanel panel = new JPanel(new FlowLayout());
panel.setBorder(BorderFactory.createEmptyBorder(0, 5, 5, 5));
Font font = new Font(Font.DIALOG, Font.PLAIN, 36);
JLabel label = new JLabel("Calculator for the Surface Area of:");
label.setFont(font);
panel.add(label);
return panel;
}
private JPanel createButtonPanel() {
String[] text = { "Sphere", "Right Cylinder", "Right Cone",
"Rectangular Prism", "Triangular Prism", "Cube",
"Square Pyramid", "Rectangular Pyramid", "Ellipsoid",
"Tetrahedron" };
JPanel panel = new JPanel(new GridLayout(0, 3, 5, 5));
panel.setBorder(BorderFactory.createEmptyBorder(0, 5, 5, 5));
Font font = new Font(null, Font.PLAIN, 24);
ButtonListener listener = new ButtonListener();
for (String s : text) {
JButton button = new JButton(s);
button.addActionListener(listener);
button.setFont(font);
panel.add(button);
}
return panel;
}
private JPanel createCubeCalculationPanel() {
JPanel panel = new JPanel(new GridBagLayout());
panel.setBorder(BorderFactory.createEmptyBorder(0, 5, 5, 5));
Font titleFont = new Font(null, Font.PLAIN, 32);
Font font = new Font(null, Font.PLAIN, 16);
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.LINE_START;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(0, 5, 5, 5);
gbc.weighty = 1.0;
gbc.gridwidth = 2;
gbc.gridx = 0;
gbc.gridy = 0;
JLabel label = new JLabel("SA = 6a²");
label.setFont(titleFont);
panel.add(label, gbc);
gbc.gridwidth = 1;
gbc.gridy++;
label = new JLabel("Edge:");
label.setFont(font);
panel.add(label, gbc);
gbc.gridx++;
edgeTextField = new JTextField(10);
edgeTextField.setFont(font);
panel.add(edgeTextField, gbc);
gbc.gridx = 0;
gbc.gridy++;
label = new JLabel("SA:");
label.setFont(font);
panel.add(label, gbc);
gbc.gridx++;
surfaceAreaSolutionTextField = new JTextField(10);
surfaceAreaSolutionTextField.setFont(font);
surfaceAreaSolutionTextField.setEditable(false);
panel.add(surfaceAreaSolutionTextField, gbc);
gbc.gridwidth = 2;
gbc.gridx = 0;
gbc.gridy++;
JButton calculateButton = new JButton("Calculate");
calculateButton.addActionListener(event -> {
double edge = Double.valueOf(edgeTextField.getText());
double sa = 6.0 * edge * edge;
surfaceAreaSolutionTextField.setText(Double.toString(sa));
});
calculateButton.setFont(font);
panel.add(calculateButton, gbc);
gbc.gridy++;
JButton backButton = new JButton("Back");
backButton.addActionListener(event -> {
cardLayout.show(mainPanel, "Start");
});
backButton.setFont(font);
panel.add(backButton, gbc);
return panel;
}
public class ButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent event) {
JButton button = (JButton) event.getSource();
String text = button.getText();
cardLayout.show(mainPanel, text);
}
}
}
Try this :
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DecimalFormat;
public class Test2 implements ActionListener {
public static void main(String[] args) {
new Test2();
}
static JPanel mainPanel, cubePanel;
static JFrame frame;
static Container container = new Container();
static JLabel calculatorFor;
static JButton sphereButton, rightCylinderButton, rightConeButton, rectangularPrismButton, triangularPrismButton,
cubeButton, squarePyramidButton, rectangularPyramidButton, ellipsoidButton, tetrahedronButton, backToPreviousFrameButton;
static Font font = new Font(null, Font.PLAIN, 30);
static JLabel enterValueForEdge;
static JTextField edgeTextField;
static JTextArea surfaceAreaTextArea, surfaceAreaFormulaTextArea, surfaceAreaSolutionTextArea;
static JButton calculateButton;
static double edge;
static DecimalFormat surfaceAreaDecimal;
public Test2() {
frame = new JFrame("Calculating for Surface Area");
calculatorFor = new JLabel("Calculator for the Surface Area of:");
calculatorFor.setSize(600, 40);
calculatorFor.setLocation(100, 50);
calculatorFor.setFont(font);
calculatorFor.setFocusable(false);
sphereButton = new JButton("Sphere ");
sphereButton.setSize(400, 40);
sphereButton.setLocation(100, 100);
sphereButton.setFont(font);
sphereButton.addActionListener(this);
sphereButton.setFocusable(false);
rightCylinderButton = new JButton("Right Cylinder");
rightCylinderButton.setSize(400, 40);
rightCylinderButton.setLocation(100, 150);
rightCylinderButton.setFont(font);
rightCylinderButton.addActionListener(this);
rightCylinderButton.setFocusable(false);
rightConeButton = new JButton("Right Cone");
rightConeButton.setSize(400, 40);
rightConeButton.setLocation(100, 200);
rightConeButton.setFont(font);
rightConeButton.addActionListener(this);
rightConeButton.setFocusable(false);
rectangularPrismButton = new JButton("Rectangular Prism");
rectangularPrismButton.setSize(400, 40);
rectangularPrismButton.setLocation(100, 250);
rectangularPrismButton.setFont(font);
rectangularPrismButton.addActionListener(this);
rectangularPrismButton.setFocusable(false);
triangularPrismButton = new JButton("Triangular Prism");
triangularPrismButton.setSize(400, 40);
triangularPrismButton.setLocation(100, 300);
triangularPrismButton.setFont(font);
triangularPrismButton.addActionListener(this);
triangularPrismButton.setFocusable(false);
cubeButton = new JButton("Cube");
cubeButton.setSize(400, 40);
cubeButton.setLocation(100, 350);
cubeButton.setFont(font);
cubeButton.addActionListener(this);
cubeButton.setFocusable(false);
squarePyramidButton = new JButton("Square Pyramid");
squarePyramidButton.setSize(400, 40);
squarePyramidButton.setLocation(100, 400);
squarePyramidButton.setFont(font);
squarePyramidButton.addActionListener(this);
squarePyramidButton.setFocusable(false);
rectangularPyramidButton = new JButton("Rectangular Pyramid");
rectangularPyramidButton.setSize(400, 40);
rectangularPyramidButton.setLocation(100, 450);
rectangularPyramidButton.setFont(font);
rectangularPyramidButton.addActionListener(this);
rectangularPyramidButton.setFocusable(false);
ellipsoidButton = new JButton("Ellipsoid");
ellipsoidButton.setSize(400, 40);
ellipsoidButton.setLocation(100, 500);
ellipsoidButton.setFont(font);
ellipsoidButton.addActionListener(this);
ellipsoidButton.setFocusable(false);
tetrahedronButton = new JButton("Tetrahedron");
tetrahedronButton.setSize(400, 40);
tetrahedronButton.setLocation(100, 550);
tetrahedronButton.setFont(font);
tetrahedronButton.addActionListener(this);
tetrahedronButton.setFocusable(false);
backToPreviousFrameButton = new JButton("Back");
backToPreviousFrameButton.setSize(100, 40);
backToPreviousFrameButton.setLocation(900, 600);
backToPreviousFrameButton.setFont(font);
backToPreviousFrameButton.addActionListener(this);
backToPreviousFrameButton.setFocusable(false);
mainPanel = new JPanel();
mainPanel.setBounds(0, 0, 1080, 720);
mainPanel.setLayout(null);
mainPanel.setBackground(Color.decode("#FAF7FC"));
mainPanel.add(calculatorFor);
mainPanel.add(sphereButton);
mainPanel.add(rightCylinderButton);
mainPanel.add(rightConeButton);
mainPanel.add(rectangularPrismButton);
mainPanel.add(triangularPrismButton);
mainPanel.add(cubeButton);
mainPanel.add(squarePyramidButton);
mainPanel.add(rectangularPyramidButton);
mainPanel.add(ellipsoidButton);
mainPanel.add(tetrahedronButton);
mainPanel.add(backToPreviousFrameButton);
frame.getContentPane().add(mainPanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setBackground(Color.decode("#FAF7FC"));
frame.setLayout(new BorderLayout());
frame.setSize(1080, 720);
frame.setResizable(false);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
}
public Container cubePanel() {
enterValueForEdge = new JLabel("Enter Edge:");
enterValueForEdge.setSize(200, 40);
enterValueForEdge.setLocation(100, 50);
enterValueForEdge.setFont(font);
enterValueForEdge.setFocusable(false);
edgeTextField = new JTextField();
edgeTextField.setSize(400, 40);
edgeTextField.setLocation(300, 50);
edgeTextField.setFont(font);
calculateButton = new JButton("Calculate");
calculateButton.setSize(200, 40);
calculateButton.setLocation(100, 100);
calculateButton.setFont(font);
calculateButton.addActionListener(this);
calculateButton.setFocusable(false);
surfaceAreaFormulaTextArea = new JTextArea("SA = 6a²");
surfaceAreaFormulaTextArea.setSize(400, 40);
surfaceAreaFormulaTextArea.setLocation(100, 150);
surfaceAreaFormulaTextArea.setFont(font);
surfaceAreaFormulaTextArea.setEditable(false);
surfaceAreaTextArea = new JTextArea("SA: ");
surfaceAreaTextArea.setSize(500, 40);
surfaceAreaTextArea.setLocation(100, 200);
surfaceAreaTextArea.setFont(font);
surfaceAreaTextArea.setEditable(false);
surfaceAreaSolutionTextArea = new JTextArea();
surfaceAreaSolutionTextArea.setSize(900, 80);
surfaceAreaSolutionTextArea.setLocation(100, 250);
surfaceAreaSolutionTextArea.setFont(font);
surfaceAreaSolutionTextArea.setEditable(false);
surfaceAreaSolutionTextArea.setLineWrap(true);
backToPreviousFrameButton = new JButton("Back");
backToPreviousFrameButton.setSize(100, 40);
backToPreviousFrameButton.setLocation(900, 600);
backToPreviousFrameButton.setFont(font);
backToPreviousFrameButton.addActionListener(this);
backToPreviousFrameButton.setFocusable(false);
cubePanel = new JPanel();
cubePanel.setBounds(0, 0, 1080, 720);
cubePanel.setLayout(null);
cubePanel.setBackground(Color.decode("#FAF7FC"));
container = new Container();
cubePanel.add(enterValueForEdge);
cubePanel.add(edgeTextField);
cubePanel.add(calculateButton);
cubePanel.add(surfaceAreaFormulaTextArea);
cubePanel.add(surfaceAreaTextArea);
cubePanel.add(surfaceAreaSolutionTextArea);
cubePanel.add(backToPreviousFrameButton);
container.add(cubePanel);
container.setLayout(null);
container.setBackground(Color.getColor("#FAF7FH"));
return container;
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == sphereButton) {
new sphereFrame();
frame.dispose();
}
if (e.getSource() == rightCylinderButton) {
new rightCylinderFrame();
frame.dispose();
}
if (e.getSource() == rightConeButton) {
new rightConeFrame();
frame.dispose();
}
if (e.getSource() == rectangularPrismButton) {
new rectangularPrismFrame();
frame.dispose();
}
if (e.getSource() == triangularPrismButton) {
//new triangularPrismFrame();
frame.dispose();
}
if (e.getSource() == cubeButton) {
frame.getContentPane().removeAll();
frame.add(cubePanel());
frame.repaint();
frame.revalidate();
System.out.println("Remove");
frame.getContentPane().add(container);
}
}
}
I created FlashScreen.java as loading screen consist of JProgressBar.
I want that after progressbar percentage is completed current window should be closed and new window should be open.
I made it but after closing first window in next window there is no component in window. Empty window is opening.
Here is code:
FlashScreen.java
package crimeManagement;
import javax.swing.*;
import java.awt.Rectangle;
import java.awt.Font;
import java.awt.Color;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class FlashScreen extends JFrame{
JProgressBar jb;
JLabel lblStat;
int i=0,num=0;
FlashScreen(){
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
setBounds(new Rectangle(400, 200, 0, 0));
jb=new JProgressBar(0,2000);
jb.setBounds(100,219,579,22);
jb.setValue(0);
jb.setStringPainted(true);
getContentPane().add(jb);
setSize(804,405);
getContentPane().setLayout(null);
lblStat = new JLabel("");
lblStat.setForeground(Color.CYAN);
lblStat.setHorizontalAlignment(SwingConstants.CENTER);
lblStat.setHorizontalTextPosition(SwingConstants.CENTER);
lblStat.setFont(new Font("Tahoma", Font.BOLD | Font.ITALIC, 18));
lblStat.setBounds(229, 252, 329, 14);
getContentPane().add(lblStat);
JLabel lblBackGround = new JLabel("");
lblBackGround.setHorizontalTextPosition(SwingConstants.CENTER);
lblBackGround.setHorizontalAlignment(SwingConstants.CENTER);
lblBackGround.setIcon(new ImageIcon(FlashScreen.class.getResource("/Images/FlashImage.jpg")));
lblBackGround.setBounds(0, 0, 798, 376);
getContentPane().add(lblBackGround);
}
public void iterate(){
while(i<=2000){
jb.setValue(i);
i=i+20;
try{
Thread.sleep(50);
if(i==20)
{
lblStat.setText("Loading...");
}
if(i==500)
{
lblStat.setText("Please Wait...");
}
if(i==1000)
{
Thread.sleep(100);
lblStat.setText("Loading Police Station Management System...");
}
if(i==1200)
{
lblStat.setText("Please Wait...");
}
if(i==1600)
{
lblStat.setText("Almost Done...");
}
if(i==1980)
{
lblStat.setText("Done");
}
if(i==2000)
{
this.dispose();
LoginPage lp=new LoginPage();
lp.setVisible(true);
}
}
catch(Exception e){}
}
}
public static void main(String[] args) {
FlashScreen fs=new FlashScreen();
fs.setVisible(true);
fs.iterate();
}
}
**LoginPage.java**
package crimeManagement;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.border.*;
public class LoginPage extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
private JFrame frame;
private JTextField txtUserName;
private JPasswordField txtPass;
public static void main(String[] args) {
LoginPage window = new LoginPage();
window.frame.setVisible(true);
}
public LoginPage() {
frame = new JFrame();
frame.setResizable(false);
frame.getContentPane().setBackground(SystemColor.inactiveCaption);
frame.getContentPane().setFont(new Font("Tahoma", Font.PLAIN, 16));
frame.setBounds(100, 100, 554, 410);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel lblLoginType = new JLabel("Login Type");
lblLoginType.setFont(new Font("Tahoma", Font.PLAIN, 16));
lblLoginType.setBounds(97, 53, 99, 20);
frame.getContentPane().add(lblLoginType);
JLabel lblUsename = new JLabel("User Name");
lblUsename.setFont(new Font("Tahoma", Font.PLAIN, 16));
lblUsename.setBounds(97, 177, 99, 26);
frame.getContentPane().add(lblUsename);
JLabel lblPaaword = new JLabel("Password");
lblPaaword.setFont(new Font("Tahoma", Font.PLAIN, 16));
lblPaaword.setBounds(97, 223, 99, 26);
frame.getContentPane().add(lblPaaword);
JPanel panel = new JPanel();
FlowLayout flowLayout = (FlowLayout) panel.getLayout();
panel.setBackground(SystemColor.inactiveCaptionBorder);
panel.setBounds(210, 47, 143, 93);
frame.getContentPane().add(panel);
TitledBorder tb=new TitledBorder( "Login");
tb.setTitleJustification(TitledBorder.CENTER);
tb.setTitlePosition(TitledBorder.CENTER);
panel.setBorder(BorderFactory.createTitledBorder(tb));
JRadioButton rdbAdmin = new JRadioButton("Admin");
rdbAdmin.setBackground(SystemColor.inactiveCaption);
rdbAdmin.setFont(new Font("Tahoma", Font.PLAIN, 13));
rdbAdmin.setSelected(true);
panel.add(rdbAdmin);
JRadioButton rdbOthers = new JRadioButton("Others");
rdbOthers.setBackground(SystemColor.inactiveCaption);
rdbOthers.setFont(new Font("Tahoma", Font.PLAIN, 13));
panel.add(rdbOthers);
txtUserName = new JTextField();
txtUserName.setBackground(UIManager.getColor("TextField.background"));
txtUserName.setBounds(210, 177, 158, 26);
frame.getContentPane().add(txtUserName);
txtUserName.setColumns(30);
JButton btnLogin = new JButton("Login");
btnLogin.setFont(new Font("Tahoma", Font.PLAIN, 14));
btnLogin.setBounds(210, 286, 71, 23);
frame.getContentPane().add(btnLogin);
JButton btnExit = new JButton("Exit");
btnExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.exit(0);
}
});
btnExit.setFont(new Font("Tahoma", Font.PLAIN, 14));
btnExit.setBounds(297, 286, 71, 23);
frame.getContentPane().add(btnExit);
txtPass = new JPasswordField();
txtPass.setBounds(210, 226, 158, 26);
frame.getContentPane().add(txtPass);
}
}
You're displaying the wrong JFrame. Yes the LoginPage extends JFrame, and yes you display it, but you add no components to it, and instead add all components to a private JFrame field of the class named, frame.
A quick solution is to change your LoginPage class so that it doesn't extend JFrame and then give this class a public getFrame() method:
public JFrame getFrame() {
return frame;
}
and when wanting to show it, call
this.dispose();
LoginPage lp = new LoginPage();
// lp.setVisible(true);
lp.getFrame().setVisible(true);
but having said this, there are still some serious threading issues with your code that you'll eventually want to fix, including trying to avoid calling Thread.sleep() in code that risks being called on the Swing event thread.
Also please check out The Use of Multiple JFrames: Good or Bad Practice? to see why it is often a bad practice to display a bunch of JFrames in your app, and ways around this.
Other issues include use of null layouts. Yes they may seem like an easy way to create complex GUI's quickly -- until you try to show the GUI on another platform and find that they don't look so nice, or have to enhance, debug or change it, and find it very tricky and easy to mess up. Much better to use layout managers.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Window;
import java.awt.Dialog.ModalityType;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class FlashScreenTest {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame mainFrame = new JFrame("Main App");
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.add(new MainAppPanel());
mainFrame.pack();
mainFrame.setLocationRelativeTo(null);
FlashScreenPanel dialogPanel = new FlashScreenPanel();
JDialog dialog = new JDialog(mainFrame, "Flash Screen", ModalityType.APPLICATION_MODAL);
dialog.add(dialogPanel);
dialog.pack();
dialog.setLocationRelativeTo(null);
dialogPanel.startProgress();
dialog.setVisible(true);
mainFrame.setVisible(true);
});
}
}
class FlashScreenPanel extends JPanel {
public static final String LOADING = "Loading...";
public static final String PLEASE_WAIT = "Please Wait...";
public static final String LOADING_POLICE_STATION = "Loading Police Station...";
public static final String ALMOST_DONE = "Almost Done...";
public static final String DONE = "Done";
private static final int TIMER_DELAY = 50;
private JProgressBar jb = new JProgressBar(0, 2000);
private JLabel statusLabel = new JLabel("", SwingConstants.CENTER);
public FlashScreenPanel() {
setPreferredSize(new Dimension(800, 400));
statusLabel.setForeground(Color.CYAN);
statusLabel.setFont(new Font("Tahoma", Font.BOLD | Font.ITALIC, 18));
jb.setStringPainted(true);
JPanel bottomPanel = new JPanel(new BorderLayout(20, 20));
bottomPanel.add(jb, BorderLayout.PAGE_START);
bottomPanel.add(statusLabel, BorderLayout.CENTER);
int eb = 40;
setBorder(BorderFactory.createEmptyBorder(eb, eb, eb, eb));
setLayout(new GridLayout(0, 1));
add(new JLabel()); // dummy component to move prog bar lower
add(bottomPanel);
}
public void startProgress() {
statusLabel.setText(LOADING);
new Timer(TIMER_DELAY, new ActionListener() {
private int i = 0;
#Override
public void actionPerformed(ActionEvent e) {
i += 20;
jb.setValue(i);
if (i == 500) {
statusLabel.setText(PLEASE_WAIT);
} else
if (i == 1000) {
statusLabel.setText(LOADING_POLICE_STATION);
} else
if (i == 1200) {
statusLabel.setText(PLEASE_WAIT);
} else
if (i == 1600) {
statusLabel.setText(ALMOST_DONE);
} else
if (i == 1980) {
statusLabel.setText(DONE);
} else
if (i == 2000) {
((Timer) e.getSource()).stop();
Window win = SwingUtilities.getWindowAncestor(FlashScreenPanel.this);
win.dispose();
}
}
}).start();
}
}
class MainAppPanel extends JPanel {
public MainAppPanel() {
setPreferredSize(new Dimension(600, 400));
}
}
I am creating an ide which will contain a workarea (a jframe) and a toolbox (another jframe). how do I accomplish the task of handling events across these two jframes? For example, if I click on a tool in the toolbox, an action has to take place in the workarea.
Please help me out
CODE FOR TOOLBOX:
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import javax.swing.ImageIcon;
import java.awt.Color;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class ToolboxForPDP extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ToolboxForPDP frame = new ToolboxForPDP();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public ToolboxForPDP() {
setResizable(false);
try {
UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) {
e.printStackTrace();
}
setTitle("Toolbox");
setType(Type.UTILITY);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 157, 445);
contentPane = new JPanel();
contentPane.setBackground(new Color(245, 245, 220));
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton btnNewButton = new JButton("");
btnNewButton.setToolTipText("Select an element in the work area");
btnNewButton.setBackground(new Color(255, 255, 255));
btnNewButton.setIcon(new ImageIcon("D:\\KS\\4-1\\Mini-Project\\PageDesigner PRO(TM)\\PageDesigner PRO(TM)\\resources\\pics\\icons\\toolbox icons\\select.jpg"));
btnNewButton.setBounds(10, 11, 55, 45);
contentPane.add(btnNewButton);
JButton btnNewButton_1 = new JButton("");
btnNewButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
btnNewButton_1.setToolTipText("Insert Image");
btnNewButton_1.setBackground(new Color(255, 255, 255));
btnNewButton_1.setIcon(new ImageIcon("D:\\KS\\4-1\\Mini-Project\\PageDesigner PRO(TM)\\PageDesigner PRO(TM)\\resources\\pics\\icons\\toolbox icons\\image.png"));
btnNewButton_1.setBounds(75, 11, 55, 45);
contentPane.add(btnNewButton_1);
JButton btnNewButton_2 = new JButton("");
btnNewButton_2.setToolTipText("Insert Text");
btnNewButton_2.setIcon(new ImageIcon("D:\\KS\\4-1\\Mini-Project\\PageDesigner PRO(TM)\\PageDesigner PRO(TM)\\resources\\pics\\icons\\toolbox icons\\text.jpg"));
btnNewButton_2.setBackground(new Color(255, 255, 255));
btnNewButton_2.setBounds(10, 67, 55, 45);
contentPane.add(btnNewButton_2);
JButton btnNewButton_3 = new JButton("");
btnNewButton_3.setToolTipText("Insert Hyperlink");
btnNewButton_3.setIcon(new ImageIcon("D:\\KS\\4-1\\Mini-Project\\PageDesigner PRO(TM)\\PageDesigner PRO(TM)\\resources\\pics\\icons\\toolbox icons\\hyperlink.png"));
btnNewButton_3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
btnNewButton_3.setBackground(new Color(255, 255, 255));
btnNewButton_3.setBounds(75, 67, 55, 45);
contentPane.add(btnNewButton_3);
JButton btnNewButton_4 = new JButton("");
btnNewButton_4.setToolTipText("Change Page Background Properties");
btnNewButton_4.setIcon(new ImageIcon("D:\\KS\\4-1\\Mini-Project\\PageDesigner PRO(TM)\\PageDesigner PRO(TM)\\resources\\pics\\icons\\toolbox icons\\fill color.png"));
btnNewButton_4.setBackground(new Color(255, 255, 255));
btnNewButton_4.setBounds(10, 123, 55, 45);
contentPane.add(btnNewButton_4);
JButton btnNewButton_5 = new JButton("");
btnNewButton_5.setIcon(new ImageIcon("D:\\KS\\4-1\\Mini-Project\\PageDesigner PRO(TM)\\PageDesigner PRO(TM)\\resources\\pics\\icons\\toolbox icons\\textbox.jpg"));
btnNewButton_5.setToolTipText("Insert Textbox");
btnNewButton_5.setBackground(new Color(255, 255, 255));
btnNewButton_5.setBounds(10, 179, 55, 45);
contentPane.add(btnNewButton_5);
JButton btnNewButton_6 = new JButton("");
btnNewButton_6.setIcon(new ImageIcon("D:\\KS\\4-1\\Mini-Project\\PageDesigner PRO(TM)\\PageDesigner PRO(TM)\\resources\\pics\\icons\\toolbox icons\\radio Button.gif"));
btnNewButton_6.setToolTipText("Insert Radio Button");
btnNewButton_6.setBackground(new Color(255, 255, 255));
btnNewButton_6.setBounds(10, 235, 55, 45);
contentPane.add(btnNewButton_6);
JButton btnNewButton_7 = new JButton("");
btnNewButton_7.setIcon(new ImageIcon("D:\\KS\\4-1\\Mini-Project\\PageDesigner PRO(TM)\\PageDesigner PRO(TM)\\resources\\pics\\icons\\toolbox icons\\checkbox.gif"));
btnNewButton_7.setToolTipText("Insert Checkbox");
btnNewButton_7.setBackground(new Color(255, 255, 255));
btnNewButton_7.setBounds(10, 291, 55, 45);
contentPane.add(btnNewButton_7);
JButton btnNewButton_8 = new JButton("");
btnNewButton_8.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnNewButton_8.setIcon(new ImageIcon("D:\\KS\\4-1\\Mini-Project\\PageDesigner PRO(TM)\\PageDesigner PRO(TM)\\resources\\pics\\icons\\toolbox icons\\hr.jpg"));
btnNewButton_8.setToolTipText("Insert Horizontal Rule");
btnNewButton_8.setBackground(new Color(255, 255, 255));
btnNewButton_8.setBounds(75, 123, 55, 45);
contentPane.add(btnNewButton_8);
JButton btnNewButton_9 = new JButton("");
btnNewButton_9.setIcon(new ImageIcon("D:\\KS\\4-1\\Mini-Project\\PageDesigner PRO(TM)\\PageDesigner PRO(TM)\\resources\\pics\\icons\\toolbox icons\\button.jpg"));
btnNewButton_9.setToolTipText("Insert Button");
btnNewButton_9.setBackground(new Color(255, 255, 255));
btnNewButton_9.setBounds(75, 179, 55, 45);
contentPane.add(btnNewButton_9);
JButton btnNewButton_10 = new JButton("");
btnNewButton_10.setIcon(new ImageIcon("D:\\KS\\4-1\\Mini-Project\\PageDesigner PRO(TM)\\PageDesigner PRO(TM)\\resources\\pics\\icons\\toolbox icons\\drop-down list.png"));
btnNewButton_10.setToolTipText("Insert Drop-Down List");
btnNewButton_10.setBackground(new Color(255, 255, 255));
btnNewButton_10.setBounds(75, 235, 55, 45);
contentPane.add(btnNewButton_10);
JButton btnNewButton_11 = new JButton("");
btnNewButton_11.setIcon(new ImageIcon("D:\\KS\\4-1\\Mini-Project\\PageDesigner PRO(TM)\\PageDesigner PRO(TM)\\resources\\pics\\icons\\toolbox icons\\list.jpg"));
btnNewButton_11.setToolTipText("Insert List");
btnNewButton_11.setBackground(new Color(255, 255, 255));
btnNewButton_11.setBounds(75, 291, 55, 45);
contentPane.add(btnNewButton_11);
JButton btnNewButton_12 = new JButton("");
btnNewButton_12.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnNewButton_12.setIcon(new ImageIcon("D:\\KS\\4-1\\Mini-Project\\PageDesigner PRO(TM)\\PageDesigner PRO(TM)\\resources\\pics\\icons\\toolbox icons\\icoScript.png"));
btnNewButton_12.setToolTipText("Add Script");
btnNewButton_12.setBackground(new Color(255, 255, 255));
btnNewButton_12.setBounds(42, 347, 55, 45);
contentPane.add(btnNewButton_12);
}
}
CODE FOR WORKAREA:
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.EmptyBorder;
import javax.swing.ButtonGroup;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.ImageIcon;
import java.awt.Toolkit;
public class StartScreen extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
StartScreen frame = new StartScreen();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public StartScreen() {
try {
UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) {
e.printStackTrace();
}
setIconImage(Toolkit.getDefaultToolkit().getImage("D:\\KS\\4-1\\Mini-Project\\PageDesigner PRO(TM)\\PageDesigner PRO(TM)\\resources\\pics\\logos\\swami_vivekananda2.png"));
setTitle("PageDesigner PRO(TM)");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(10, 10, 1350, 700);
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu mnFile = new JMenu("File");
menuBar.add(mnFile);
JMenu mnNew = new JMenu("New");
mnNew.setIcon(new ImageIcon("D:\\KS\\4-1\\Mini-Project\\PageDesigner PRO(TM)\\PageDesigner PRO(TM)\\resources\\pics\\icons\\menu icons\\Folder-New-icon.png"));
mnFile.add(mnNew);
JMenuItem mntmNewProject = new JMenuItem("New Project");
mnNew.add(mntmNewProject);
JMenuItem mntmNewPage = new JMenuItem("New Page");
mnNew.add(mntmNewPage);
mnFile.addSeparator();
JMenuItem mntmSave = new JMenuItem("Save");
mntmSave.setIcon(new ImageIcon("D:\\KS\\4-1\\Mini-Project\\PageDesigner PRO(TM)\\PageDesigner PRO(TM)\\resources\\pics\\icons\\menu icons\\save.png"));
mnFile.add(mntmSave);
JMenuItem mntmSaveAs = new JMenuItem("Save As...");
mnFile.add(mntmSaveAs);
mnFile.addSeparator();
JMenuItem mntmAddToProject = new JMenuItem("Add to project");
mnFile.add(mntmAddToProject);
JMenuItem mntmTestThisPage = new JMenuItem("Test this page");
mnFile.add(mntmTestThisPage);
mnFile.addSeparator();
JCheckBoxMenuItem chckbxmntmShowWelcomeScreen = new JCheckBoxMenuItem("Show Welcome screen at startup");
mnFile.add(chckbxmntmShowWelcomeScreen);
mnFile.addSeparator();
JMenuItem mntmExit = new JMenuItem("Exit");
mntmExit.setIcon(new ImageIcon("D:\\KS\\4-1\\Mini-Project\\PageDesigner PRO(TM)\\PageDesigner PRO(TM)\\resources\\pics\\icons\\menu icons\\exit.png"));
mnFile.add(mntmExit);
JMenu mnEdit = new JMenu("Edit");
menuBar.add(mnEdit);
JMenuItem mntmModifyElementProperties = new JMenuItem("Modify Element Properties");
mnEdit.add(mntmModifyElementProperties);
JMenu mnMode = new JMenu("Mode");
menuBar.add(mnMode);
JRadioButtonMenuItem rdbtnmntmBeginnerMode = new JRadioButtonMenuItem("Beginner Mode");
mnMode.add(rdbtnmntmBeginnerMode);
JRadioButtonMenuItem rdbtnmntmAdvancedMode = new JRadioButtonMenuItem("Advanced Mode");
mnMode.add(rdbtnmntmAdvancedMode);
ButtonGroup modeMenuGroup = new ButtonGroup();
modeMenuGroup.add(rdbtnmntmBeginnerMode);
modeMenuGroup.add(rdbtnmntmAdvancedMode);
JMenu mnHelp = new JMenu("Help");
menuBar.add(mnHelp);
JMenuItem mntmUserGuide = new JMenuItem("User Guide");
mntmUserGuide.setIcon(new ImageIcon("D:\\KS\\4-1\\Mini-Project\\PageDesigner PRO(TM)\\PageDesigner PRO(TM)\\resources\\pics\\icons\\menu icons\\manual icon.gif"));
mnHelp.add(mntmUserGuide);
JMenuItem mntmAbout = new JMenuItem("About...");
mntmAbout.setIcon(new ImageIcon("D:\\KS\\4-1\\Mini-Project\\PageDesigner PRO(TM)\\PageDesigner PRO(TM)\\resources\\pics\\icons\\menu icons\\info_black.png"));
mnHelp.add(mntmAbout);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
}
}
Your question is how to pass information from one JFrame to another, and this can be done as simply as having one class call a method of the other class. That you haven't done this, and that you've only posted a skeleton program, one with components but with no logic suggests to me that you are still very much a beginner Java programmer, and so my main suggestion is that first and foremost you strive to learn to code, and in particular learn about object oriented principles and how they relate to Java. Without these rudiments under your belt, we can give you code and pointers, but it won't help you much. I suggest that you go to the Java Tutorials and start there, but also that you get a decent book or two on the subject such as Bruce Eckel's Thinking in Java, and/or Head First Java.
As for your actual code I suggest that you not create classes that extend JFrame since that locks you into a JFrame, and again as per my comment above, your tool window should be a non-modal JDialog not a JFrame. If you gear your code towards creating JPanels, then you can place them into JFrames, JDialogs, other JPanels, etc... wherever needed, and so this gives you a lot more flexibility.
The main difficulty in the situation of your program is not passing information from one window to another, one object to another, really, but rather when to do so, since the program is event driven. Myself, I like to use PropertyChangeListeners for this, basically using an observer interface that is already part of the Swing GUI structure. For example in the code below I create two main JPanels, one is displayed within a JFrame, the other within a non-modal JDialog, and I pass button press information (the actionCommand String of the button) to the JTextArea in the main GUI via a PropertyChangeListener:
import java.awt.BorderLayout;
import java.awt.Dialog.ModalityType;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.*;
public class Foo3 {
private static void createAndShowGui() {
final MainPanel1 mainPanel1 = new MainPanel1();
final ToolPanel1 toolPanel1 = new ToolPanel1();
JFrame frame = new JFrame("Foo3");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel1);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
JDialog dialog = new JDialog(frame, "Toolbar", ModalityType.MODELESS);
dialog.add(toolPanel1);
dialog.pack();
dialog.setLocationByPlatform(true);
dialog.setVisible(true);
toolPanel1.addPropertyChangeListener(ToolPanel1.ACTION_COMMAND, new PropertyChangeListener() {
#Override
public void propertyChange(PropertyChangeEvent evt) {
mainPanel1.appendActionCommand((String) evt.getNewValue());
}
});
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
class MainPanel1 extends JPanel {
private JTextArea actionCommandArea = new JTextArea(30, 50);
private JScrollPane scrollPane = new JScrollPane(actionCommandArea);
public MainPanel1() {
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
setLayout(new BorderLayout());
add(scrollPane, BorderLayout.CENTER);
}
public void appendActionCommand(String text) {
actionCommandArea.append(text + "\n");
}
}
class ToolPanel1 extends JPanel {
public static final String ACTION_COMMAND = "action command";
public static final String[] BTN_TEXTS = {
"Select Element",
"Insert Image",
"Insert Text",
"Insert Hyperlink",
"Change Page Background",
"Insert Textbox",
"Insert Radio Button",
"Insert Checkbox",
"Insert Horizontal Rule",
"Insert Button",
"Insert Drop-Down List",
"Insert List",
"Add Script"
};
private String actionCommand = "";
public ToolPanel1() {
int rows = 0; // variable number of rows
int cols = 2; // 2 columns
int hgap = 5;
int vgap = hgap;
setLayout(new GridLayout(rows, cols, hgap, vgap));
setBorder(BorderFactory.createEmptyBorder(hgap, hgap, hgap, hgap));
for (String btnText : BTN_TEXTS) {
add(new JButton(new ButtonAction(btnText)));
}
}
public String getActionCommand() {
return actionCommand;
}
private class ButtonAction extends AbstractAction {
public ButtonAction(String name) {
super(name);
}
#Override
public void actionPerformed(ActionEvent e) {
String oldValue = "";
String newValue = e.getActionCommand();
actionCommand = newValue;
ToolPanel1.this.firePropertyChange(ACTION_COMMAND, oldValue, newValue);
}
}
}
A more robust design would be to use a Model-View-Controller type design, but this is a bit more advanced, and you'll need to get some more code experience under your belt before using this, I think. also check out these links to similar questions/answers.
This question already has answers here:
Implementing back/forward buttons in Swing
(3 answers)
Closed 8 years ago.
I want to know how do you go to another panel by pressing a button.
The codes for my main GUI is below:
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
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;
import javax.swing.JTextField;
import javax.swing.border.LineBorder;
public class MainMenu extends JFrame {
private JPanel contentPane, confirmPage_Panel;
private JTextField NumberofSoups_TEXTFIELD;
private JTextField NumberofSandwiches_TEXTFIELD;
private JTextField totalCost_TEXTFIELD;
private JTextField OrderNumber_TEXTFIELD;
private int Soupclicks = 0;
private int Sandwichclicks = 0;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainMenu frame = new MainMenu();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public MainMenu() {
super("Welcome Yo!");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 1268, 716);
contentPane = new JPanel();
contentPane.setBackground(Color.DARK_GRAY);
contentPane.setBorder(new LineBorder(new Color(255, 200, 0), 4, true));
setContentPane(contentPane);
contentPane.setLayout(null);
JPanel Header_Panel = new JPanel();
Header_Panel.setBackground(Color.DARK_GRAY);
Header_Panel.setBounds(145, 11, 977, 35);
contentPane.add(Header_Panel);
JLabel Header_Label = new JLabel("Super Sandwich Store");
Header_Label.setForeground(Color.PINK);
Header_Label.setFont(new Font("Tahoma", Font.PLAIN, 22));
Header_Panel.add(Header_Label);
JPanel Soup_Panel = new JPanel();
Soup_Panel.setBackground(Color.PINK);
Soup_Panel.setBounds(10, 71, 459, 339);
contentPane.add(Soup_Panel);
Soup_Panel.setLayout(null);
JButton Confirm_Button = new JButton("Confirm Now");
Confirm_Button.setFont(new Font("Tahoma", Font.PLAIN, 14));
Confirm_Button.setBounds(511, 558, 121, 23);
contentPane.add(Confirm_Button);
JButton Exit_Button = new JButton("Exit");
Exit_Button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.exit(0);
}
});
Exit_Button.setFont(new Font("Tahoma", Font.PLAIN, 13));
Exit_Button.setBounds(641, 558, 111, 23);
contentPane.add(Exit_Button);
}// end of MainMenu()
}
And when i clicked the confirm button it will invoke this page :
public class ConfirmationGUI extends JFrame {
private JPanel contentPane;
private JTextField ConfirmedOrder_Field;
private JTextField totalCost_Field;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ConfirmationGUI frame = new ConfirmationGUI();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public ConfirmationGUI() {
super("Confirmation Yo!");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 668, 457);
contentPane = new JPanel();
contentPane.setBackground(Color.DARK_GRAY);
contentPane.setBorder(new LineBorder(Color.ORANGE, 4, true));
setContentPane(contentPane);
contentPane.setLayout(null);
JPanel Top_Panel = new JPanel();
Top_Panel.setBackground(Color.DARK_GRAY);
Top_Panel.setBounds(5, 5, 637, 93);
contentPane.add(Top_Panel);
Top_Panel.setLayout(null);
JLabel lblNewLabel = new JLabel("Super Sandwich Store");
lblNewLabel.setForeground(Color.PINK);
lblNewLabel.setBounds(245, 11, 185, 45);
Top_Panel.add(lblNewLabel);
lblNewLabel.setFont(new Font("Tahoma", Font.PLAIN, 18));
}
}
It would be much of a help,
Thank you :)
To switch between JFrames, call setVisible(true) for the JFrame you want to reveal and setVisible(false) for the one you want to hide. CardLayout doesn't apply here.
Suggestions: read the Swing tutorial on layouts, don't use null layouts with absolutely positioning, and familiarize yourself with the differences between ordinary containers and top-level containers.
Some context for this code,
what I am trying to do is create a validation warning if the input containts "" as a value,
so if an error is displayed it displays the message.
If it is valid it does not display a message,
so how do I remove the message when the textField is valid?
The message is a JPanel that contains a JLabel with the text in it,
I add this this JPanel to the frame when it is not valid,
and I am trying to remove it when it is valid.
So what am I doing wrong here?
I am at a basic level with Swing.
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JTextField;
import java.awt.Color;
import java.awt.Font;
import javax.swing.JButton;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class Test {
private JFrame frame;
private JTextField textField;
private JTextField textField_1;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Test window = new Test();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Test() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 401, 232);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JPanel panel = new JPanel();
panel.setBounds(10, 11, 330, 94);
frame.getContentPane().add(panel);
panel.setLayout(null);
JLabel lblNewLabel = new JLabel("Firstname :");
lblNewLabel.setBounds(10, 11, 104, 14);
panel.add(lblNewLabel);
textField = new JTextField();
textField.setBounds(76, 8, 244, 20);
panel.add(textField);
textField.setColumns(10);
JLabel lblLastname = new JLabel("Lastname :");
lblLastname.setBounds(10, 42, 78, 14);
panel.add(lblLastname);
textField_1 = new JTextField();
textField_1.setBounds(76, 39, 244, 20);
panel.add(textField_1);
textField_1.setColumns(10);
JButton btnValidate = new JButton("Validate");
btnValidate.addMouseListener(new MouseAdapter() {
#SuppressWarnings("deprecation")
#Override
public void mousePressed(MouseEvent arg0) {
JPanel panel_1 = new JPanel();
JPanel panel_2 = new JPanel();
if(textField.getText().equals("")) {
panel_1.setBackground(new Color(30, 144, 255));
panel_1.setBounds(100, 116, 330, 26);
JLabel lblMessage = new JLabel("0 :");
lblMessage.setForeground(new Color(255, 255, 255));
lblMessage.setFont(new Font("Tahoma", Font.BOLD, 13));
panel_1.add(lblMessage);
frame.getContentPane().add(panel_1);
frame.revalidate();
frame.repaint(10);
frame.revalidate();
}
else if(textField_1.getText().equals("")) {
panel_2.setBackground(new Color(50, 200, 255));
panel_2.setBounds(10, 134, 330, 26);
JLabel lblMessage = new JLabel("1 :");
lblMessage.setBounds(50, 50, 50, 50);
lblMessage.setAlignmentX(50);
lblMessage.setForeground(new Color(255, 255, 255));
lblMessage.setFont(new Font("Tahoma", Font.BOLD, 13));
panel_2.add(lblMessage);
frame.getContentPane().add(panel_2);
frame.remove(panel_1);
frame.revalidate();
frame.repaint(10);
frame.revalidate();
}
}
});
btnValidate.setBounds(231, 71, 89, 23);
panel.add(btnValidate);
}
}
The easiest way is to simply adjust the visibility (JComponent#setVisible( false ) ).
If you really want to remove the component completely, you have to remove and revalidate, as documented in the Container#remove method
This method changes layout-related information, and therefore, invalidates the component hierarchy. If the container has already been displayed, the hierarchy must be validated thereafter in order to reflect the changes.
which results in code like
panel.remove( componentToRemove );
panel.revalidate();
panel.repaint();
As a side note: please replace the null layout and those setBounds call by a proper LayoutManager. You might want to take a look excellent 'Nested layout example' available on SO to see what is possible with layout managers. The Swing tag info on SO contains some extra useful links when starting to work with layout managers
yourpanel.setVisible(false); should hide your panel, where "yourPanel" is your JPanel instance