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.
Related
I created a Swing application. I'm using a JProgressBar to show the progres and I want the progress to change when some tasks execute inside a button handler(ActionListener.actionPerformed), but it ins't working. Here is the code:
package com.capgemini.skillparser.ui;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.filechooser.FileSystemView;
import com.capgemini.skillparser.domain.Employee;
import com.capgemini.skillparser.excel.impl.SkillsXlsxReader;
import com.capgemini.skillparser.excel.impl.SkillsXlsxWriter;
import com.capgemini.skillparser.text.impl.EmployeeNumbersTextReader;
public class TelaPrincipal extends JFrame {
private JPanel contentPane;
private JTextField textField;
private JTextField textField_1;
private JTextField textField_2;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
TelaPrincipal frame = new TelaPrincipal();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public TelaPrincipal() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 427);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel label = new JLabel(
new ImageIcon(
new ImageIcon(getClass().getClassLoader().getResource("capgemini-logo.jpg"))
.getImage().getScaledInstance(300, 100, Image.SCALE_DEFAULT)
)
);
label.setBounds(10, 11, 414, 73);
contentPane.add(label);
textField = new JTextField();
textField.setBackground(Color.LIGHT_GRAY);
textField.setBounds(10, 113, 414, 20);
contentPane.add(textField);
textField.setColumns(10);
JButton btnSelecionarPlanilha = new JButton("Selecionar planilha");
btnSelecionarPlanilha.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser j = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory());
FileNameExtensionFilter filter = new FileNameExtensionFilter("*.xlsx", "xlsx");
j.setFileFilter(filter);
int r = j.showSaveDialog(null);
if (r == JFileChooser.APPROVE_OPTION) {
textField.setText(j.getSelectedFile().getAbsolutePath());
}
}
});
btnSelecionarPlanilha.setBounds(10, 144, 217, 23);
contentPane.add(btnSelecionarPlanilha);
textField_1 = new JTextField();
textField_1.setBackground(Color.LIGHT_GRAY);
textField_1.setBounds(10, 178, 414, 20);
contentPane.add(textField_1);
textField_1.setColumns(10);
JButton btnSelecionarArquivoTxtfiltro = new JButton("Selecionar arquivo txt (filtro)");
btnSelecionarArquivoTxtfiltro.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser j = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory());
FileNameExtensionFilter filter = new FileNameExtensionFilter("*.txt", "txt");
j.setFileFilter(filter);
int r = j.showSaveDialog(null);
if (r == JFileChooser.APPROVE_OPTION) {
textField_1.setText(j.getSelectedFile().getAbsolutePath());
}
}
});
btnSelecionarArquivoTxtfiltro.setBounds(10, 209, 217, 23);
contentPane.add(btnSelecionarArquivoTxtfiltro);
textField_2 = new JTextField();
textField_2.setBackground(Color.LIGHT_GRAY);
textField_2.setBounds(10, 243, 414, 20);
contentPane.add(textField_2);
textField_2.setColumns(10);
JButton btnSelecionarDestino = new JButton("Selecionar destino");
btnSelecionarDestino.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser j = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory());
j.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int r = j.showSaveDialog(null);
if (r == JFileChooser.APPROVE_OPTION) {
textField_2.setText(j.getSelectedFile().getAbsolutePath());
}
}
});
btnSelecionarDestino.setBounds(10, 274, 217, 23);
contentPane.add(btnSelecionarDestino);
JProgressBar progressBar = new JProgressBar();
progressBar.setBounds(10, 318, 414, 23);
progressBar.setValue(0);
progressBar.setStringPainted(true);
contentPane.add(progressBar);
JButton btnGerarPlanilhaAjustada = new JButton("Gerar Planilha Ajustada");
btnGerarPlanilhaAjustada.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//---------------PROBLEM HERE---------------------------------------
try {
progressBar.setIndeterminate(true);
progressBar.setValue(30);
//read a xlsx file
progressBar.setValue(50);
//write a xlsx file
progressBar.setValue(100);
progressBar.setIndeterminate(false);
//nothing above related to progressBar works properly, these statements only execute after the button handler code finishes
}catch(Exception ex) {
ex.printStackTrace();
}
}
});
btnGerarPlanilhaAjustada.setBounds(101, 354, 230, 23);
contentPane.add(btnGerarPlanilhaAjustada);
}
}
I tried many alternative codes, but nothing worked. Some places suggests multi-thread approaches but I don't know how to structure my code to work with multi-thread in a manner that works well. All my tries in this sense have failed.
Can someone help me please? Thank you
Reading and writing are "heavy" operations that might take time to finish. That's why you will have to do them in background, otherwise the GUI thread, a.k.a the Event Dispatch Thread will be busy hence events will not be able to take place (gui will freeze).
You have to create a SwingWorker. The whole idea is this:
Button gets clicked
SwingWorker starts
Worker does a part-step of a heavy operation in background
Worker publishes the progress bar value to the GUI thread
Repeat 3 & 4
Worker is done.
See my example in your code (comments inside the code):
public class TelaPrincipal extends JFrame {
private SwingWorker<Void, Integer> worker;
private JPanel contentPane;
private JTextField textField;
private JTextField textField_1;
private JTextField textField_2;
private JProgressBar progressBar;
/**
* Launch the application.
*/
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
TelaPrincipal frame = new TelaPrincipal();
frame.setVisible(true);
});
}
/**
* Create the frame.
*/
public TelaPrincipal() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 427);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel label = new JLabel();
label.setBounds(10, 11, 414, 73);
contentPane.add(label);
textField = new JTextField();
textField.setBackground(Color.LIGHT_GRAY);
textField.setBounds(10, 113, 414, 20);
contentPane.add(textField);
textField.setColumns(10);
JButton btnSelecionarPlanilha = new JButton("Selecionar planilha");
btnSelecionarPlanilha.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JFileChooser j = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory());
FileNameExtensionFilter filter = new FileNameExtensionFilter("*.xlsx", "xlsx");
j.setFileFilter(filter);
int r = j.showSaveDialog(null);
if (r == JFileChooser.APPROVE_OPTION) {
textField.setText(j.getSelectedFile().getAbsolutePath());
}
}
});
btnSelecionarPlanilha.setBounds(10, 144, 217, 23);
contentPane.add(btnSelecionarPlanilha);
textField_1 = new JTextField();
textField_1.setBackground(Color.LIGHT_GRAY);
textField_1.setBounds(10, 178, 414, 20);
contentPane.add(textField_1);
textField_1.setColumns(10);
JButton btnSelecionarArquivoTxtfiltro = new JButton("Selecionar arquivo txt (filtro)");
btnSelecionarArquivoTxtfiltro.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JFileChooser j = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory());
FileNameExtensionFilter filter = new FileNameExtensionFilter("*.txt", "txt");
j.setFileFilter(filter);
int r = j.showSaveDialog(null);
if (r == JFileChooser.APPROVE_OPTION) {
textField_1.setText(j.getSelectedFile().getAbsolutePath());
}
}
});
btnSelecionarArquivoTxtfiltro.setBounds(10, 209, 217, 23);
contentPane.add(btnSelecionarArquivoTxtfiltro);
textField_2 = new JTextField();
textField_2.setBackground(Color.LIGHT_GRAY);
textField_2.setBounds(10, 243, 414, 20);
contentPane.add(textField_2);
textField_2.setColumns(10);
JButton btnSelecionarDestino = new JButton("Selecionar destino");
btnSelecionarDestino.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JFileChooser j = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory());
j.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int r = j.showSaveDialog(null);
if (r == JFileChooser.APPROVE_OPTION) {
textField_2.setText(j.getSelectedFile().getAbsolutePath());
}
}
});
btnSelecionarDestino.setBounds(10, 274, 217, 23);
contentPane.add(btnSelecionarDestino);
progressBar = new JProgressBar();
progressBar.setBounds(10, 318, 414, 23);
progressBar.setValue(0);
progressBar.setStringPainted(true);
contentPane.add(progressBar);
JButton btnGerarPlanilhaAjustada = new JButton("Gerar Planilha Ajustada");
btnGerarPlanilhaAjustada.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (!worker.isDone())
worker.cancel(true); //destroy previous worker
initWorker();
worker.execute();
}
});
btnGerarPlanilhaAjustada.setBounds(101, 354, 230, 23);
contentPane.add(btnGerarPlanilhaAjustada);
initWorker();
}
private void initWorker() {
worker = new SwingWorker<Void, Integer>() {
#Override
protected void process(List<Integer> chunks) {
int value = chunks.get(0);
progressBar.setValue(value);
}
#Override
protected Void doInBackground() throws Exception {
publish(10); //progress bar value that will be sent to process() method
Thread.sleep(2000); //assume read file takes 2 seconds
publish(50); //progress bar value that will be sent to process() method
Thread.sleep(2000); //assume another bg operation takes 2 secs
publish(99);
return null;
}
};
}
}
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());
}
}
I've made the initialize method public, didn't help and I've set visible to true both here and the external class as seen below, any help would be appreciated. I created the gui using the window builder tool from eclipse
GeneralWindow frame = new GeneralWindow();
frame.setVisible(true);
package gui;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.JLabel;
import javax.swing.JTextArea;
import java.awt.Font;
public class GeneralWindow extends JFrame{
private JFrame frame;
private JTextField textField;
/**
* Launch the application.
*/
public static void main(String[] args) {
try {
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (Exception e) {
// If Nimbus is not available, you can set the GUI to another look and feel.
}
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
GeneralWindow window = new GeneralWindow();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public GeneralWindow() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JButton btnNewButton = new JButton("Order");
btnNewButton.setBounds(309, 12, 115, 23);
frame.getContentPane().add(btnNewButton);
JButton btnNewButton_1 = new JButton("Search");
btnNewButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnNewButton_1.setBounds(309, 46, 115, 23);
frame.getContentPane().add(btnNewButton_1);
JButton btnNewButton_2 = new JButton("Stock");
btnNewButton_2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
btnNewButton_2.setBounds(309, 80, 115, 23);
frame.getContentPane().add(btnNewButton_2);
JButton btnNewButton_3 = new JButton("Emplyoees");
btnNewButton_3.setBounds(309, 114, 115, 23);
frame.getContentPane().add(btnNewButton_3);
JButton btnNewButton_4 = new JButton("Price Amend");
btnNewButton_4.setBounds(309, 148, 115, 23);
frame.getContentPane().add(btnNewButton_4);
JButton btnNewButton_5 = new JButton("Total");
btnNewButton_5.setBounds(309, 182, 115, 23);
frame.getContentPane().add(btnNewButton_5);
textField = new JTextField();
textField.setBounds(10, 228, 178, 20);
frame.getContentPane().add(textField);
textField.setColumns(10);
JLabel lblProductcodeBar = new JLabel("Productcode Bar");
lblProductcodeBar.setFont(new Font("Tahoma", Font.BOLD, 11));
lblProductcodeBar.setBounds(10, 209, 125, 14);
frame.getContentPane().add(lblProductcodeBar);
JButton btnEnter = new JButton("Enter");
btnEnter.setBounds(198, 227, 89, 23);
frame.getContentPane().add(btnEnter);
JTextArea textArea = new JTextArea();
textArea.setBounds(10, 11, 277, 196);
frame.getContentPane().add(textArea);
}
}
You're making the frame frame, of type GeneralWindow, visible. But you never add any component to that frame. Instead, your initialize method creates yet another frame, and adds many components to that frame. Don't create another frame, and add the components to this, instead.
In Your initialize() just change the frame to this keyword
e.g
//Remove this line
frame = new JFrame();
//change frame to this keyword
this.setBounds(100, 100, 450, 300);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.getContentPane().setLayout(null);
That its u r done...
Whilst the two answers provide here give a correct solution, they both reinforce the view that you should extend JFrame. This is not good advice in general, as you should favour composition over inheritance. Indeed the way you were writing the code to include a JFrame as a private member was the correct instinct.
I've included a stripped down version of your code that doesn't extend JFrame Instead it creates an instance of the JFrame when you call the createAndDisplayFrame() method.
public class GeneralWindow {
private JFrame frame;
private JButton orderButton;
public static void main(final String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
GeneralWindow window = new GeneralWindow();
window.crateAndDisplayFrame();
}
});
}
public void crateAndDisplayFrame() {
initialize();
frame.setVisible(true);
}
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
orderButton = new JButton("Order");
orderButton.setBounds(309, 12, 115, 23);
frame.getContentPane().add(orderButton);
}
}
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));
}
}
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.