JProgressBar does not update inside actionPerformed - Java Swing - java

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;
}
};
}
}

Related

JAVA - can't get return from isSelected()

I have this part of code here, but whenever I launch the program I only get left brain. even though I check one or the other box.
chckbxMusic = new JCheckBox("Music");
chckbxMusic.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
chckbxMath.setSelected(false);
}
});
chckbxMusic.setBounds(46, 107, 85, 23);
Question_1.add(chckbxMusic);
chckbxMath = new JCheckBox("Math");
chckbxMath.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
chckbxMusic.setSelected(false);
}
});
chckbxMath.setBounds(243, 107, 128, 23);
Question_1.add(chckbxMath);
if(chckbxMusic.isSelected()) brain_right++;
else brain_left++;
Ok maybe the full code can help a bit more..
I rewrite it a little bit, but the result is always 0 for both variables??
import java.awt.EventQueue;
import javax.swing.JFrame;
import java.awt.CardLayout;
import javax.swing.JPanel;
import javax.swing.JCheckBox;
import javax.swing.JButton;
import javax.swing.JLabel;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.ChangeEvent;
public class PrgVeloce {
private JFrame frame;
private JPanel Question;
private JPanel Result;
public int brain_left;
public int brain_right;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
PrgVeloce window = new PrgVeloce();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public PrgVeloce() {
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(new CardLayout(0, 0));
Question = new JPanel();
frame.getContentPane().add(Question, "name_971195205673");
Question.setLayout(null);
final JCheckBox chckbxMath = new JCheckBox("Math");
chckbxMath.setBounds(39, 115, 128, 23);
Question.add(chckbxMath);
final JCheckBox chckbxMusic = new JCheckBox("Music");
chckbxMusic.setBounds(237, 115, 128, 23);
Question.add(chckbxMusic);
JButton btnNext = new JButton("Next");
btnNext.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(chckbxMusic.isSelected())
{
brain_left = 10;
}
if(chckbxMath.isSelected())
{
brain_right = 10;
}
Question.setVisible(false);
Result.setVisible(true);
}
});
btnNext.setBounds(158, 210, 117, 29);
Question.add(btnNext);
Result = new JPanel();
frame.getContentPane().add(Result, "name_978670915264");
Result.setLayout(null);
JLabel lblEmisferoDx = new JLabel("Right brain:");
lblEmisferoDx.setBounds(90, 118, 110, 16);
Result.add(lblEmisferoDx);
JLabel lblNewLabel = new JLabel("Left Brain:");
lblNewLabel.setBounds(90, 157, 84, 16);
Result.add(lblNewLabel);
JLabel lblNewLabel_1 = new JLabel(brain_right + "%");
lblNewLabel_1.setBounds(218, 118, 61, 16);
Result.add(lblNewLabel_1);
JLabel lblNewLabel_2 = new JLabel(brain_left + "%");
lblNewLabel_2.setBounds(218, 157, 61, 16);
Result.add(lblNewLabel_2);
}
}

Passing info from one Jframe to another

I have my original text field in my first frame and I need it to be displayed in my other jframe. The code is:
JButton btnContinue = new JButton("Continue");
btnContinue.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String msg = nameL.getText();
frame2 fram = new frame2 ();
fram.setVisible(true);
frame.dispose();
new order (msg) .setVisible(true);
'nameL' is the textbox the user enters their name in.
This code describe where it should be displayed:
public order(String para){
getComponents();
JLabel lblNewLabel_1 = new JLabel("");
lblNewLabel_1.setBounds(91, 27, 254, 84);
contentPane.add(lblNewLabel_1);
lblNewLabel_1.setText(para);
this is my first class where the user inputs their name
public order(String para){
getComponents();
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JTextField;
import javax.swing.JTextArea;
import java.awt.Color;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Font;
public class frame1 {
public JFrame frame;
public JTextField nameL;
public JTextField textField_1;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
frame1 window = new frame1();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public frame1() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.getContentPane().setEnabled(false);
frame.setResizable(false);
frame.getContentPane().setBackground(Color.GRAY);
frame.setForeground(Color.WHITE);
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JButton btnContinue = new JButton("Continue");
btnContinue.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String msg = nameL.getText();
frame2 fram = new frame2 ();
fram.setVisible(true);
frame.dispose();
new order (msg) .setVisible(true);
}
}
);
btnContinue.setBounds(0, 249, 450, 29);
frame.getContentPane().add(btnContinue);
JTextArea txtrPleaseEnterYour = new JTextArea();
txtrPleaseEnterYour.setEditable(false);
txtrPleaseEnterYour.setBackground(Color.LIGHT_GRAY);
txtrPleaseEnterYour.setBounds(0, 0, 450, 32);
txtrPleaseEnterYour.setText("\tPlease enter your name and email below\n If you do not have or want to provide an email, Leave the space blank");
frame.getContentPane().add(txtrPleaseEnterYour);
JTextArea txtrEnterYourFull = new JTextArea();
txtrEnterYourFull.setEditable(false);
txtrEnterYourFull.setFont(new Font("Lucida Grande", Font.PLAIN, 15));
txtrEnterYourFull.setBackground(Color.GRAY);
txtrEnterYourFull.setText("Enter your full name");
txtrEnterYourFull.setBounds(52, 58, 166, 29);
frame.getContentPane().add(txtrEnterYourFull);
nameL = new JTextField();
nameL.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
}
);
nameL.setBackground(Color.LIGHT_GRAY);
nameL.setBounds(52, 93, 284, 26);
frame.getContentPane().add(nameL);
nameL.setColumns(10);
JTextArea txtroptionalEnterYour = new JTextArea();
txtroptionalEnterYour.setEditable(false);
txtroptionalEnterYour.setFont(new Font("Lucida Grande", Font.PLAIN, 15));
txtroptionalEnterYour.setBackground(Color.GRAY);
txtroptionalEnterYour.setText("(Optional) Enter your email");
txtroptionalEnterYour.setBounds(52, 139, 193, 29);
frame.getContentPane().add(txtroptionalEnterYour);
textField_1 = new JTextField();
textField_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
textField_1.setBackground(Color.LIGHT_GRAY);
textField_1.setBounds(52, 180, 284, 26);
frame.getContentPane().add(textField_1);
textField_1.setColumns(10);
}
}
my second class where the text field has to be set
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import java.awt.Color;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JLabel;
public class order extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
public JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
order frame = new order();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public order() {
setAlwaysOnTop(false);
setTitle("Order Details // Finalization");
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setBounds(100, 100, 451, 523);
contentPane = new JPanel();
contentPane.setBackground(Color.LIGHT_GRAY);
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton btnNewButton = new JButton("Submit Order");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setAlwaysOnTop(true);
JOptionPane.showMessageDialog(null, "Your Order Has Been Confirmed", "enjoy your meal", JOptionPane.YES_NO_OPTION);
}
});
btnNewButton.setBounds(164, 466, 117, 29);
contentPane.add(btnNewButton);
}
public order(String para){
getComponents();
JLabel lblNewLabel_1 = new JLabel("");
lblNewLabel_1.setBounds(91, 27, 254, 84);
contentPane.add(lblNewLabel_1);
lblNewLabel_1.setText(para);
}
}
Open both JFrames, have them listen to the EventQueue for a custom "string display" event.
Wrap the string to be displayed in a custom event.
Throw that on the event queue, allowing both the JFrames to receive the event, which they will then display accordingly.
---- Edited with an update ----
Ok, so you're a bit new to Swing, but hopefully not too new to Java. You'll need to understand sub-classing and the "Listener" design pattern.
Events are things that Components listen for. They ask the dispatcher (the Swing dispatcher is fed by the EventQueue) to "tell them about events" and the dispatcher then sends the desired events to them.
Before you get too deep in solving your problem, it sounds like you need to get some familiarity with Swing and its event dispatch, so read up on it here.

how to handle events across multiple windows (different jframes) using JAVA?

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.

Toggle Java JPanels - each panel deifferent class

I'm a beginer in Java GUI, and i have an issue with trying to toggle between panel in other class.
My main Class "MyBoxGUI" has 2 Panels, "Login" and "UserMenu"
The default is "Login" panel, when pressing "OK" the window moved to "UserMenu" Panel.
So far so good while in the same class.
The issue is, when i set a new panel in new class and setvisibe that panel, i can't go back to "UserMenu" panel - (The actionlistener is working fine).
Can someone help me please?
MyBoxGUI Class
package main;
import java.awt.EventQueue;
import javax.swing.JFrame;
import java.awt.CardLayout;
import java.awt.Component;
//import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JLabel;
import java.awt.Font;
import java.awt.Color;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import java.awt.Toolkit;
import GUIs.*;
//import ocsf.client.*;
public class MyBoxGUI extends JPanel
{
private Mtds mtd;
public JFrame frmMybox;
private static JTextField UserName;
private static JTextField port;
private static JTextField IP;
private static JPasswordField passwordField;
public final JPanel Login = new JPanel();
public final JPanel UserMenu = new JPanel();
/**
* Launch the application.
*/
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
try
{
MyBoxGUI window = new MyBoxGUI();
window.frmMybox.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public MyBoxGUI()
{
mtd = new Mtds();
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize()
{
frmMybox = new JFrame();
frmMybox.setFont(new Font("Tempus Sans ITC", Font.BOLD, 15));
// frmMybox.setIconImage(Toolkit.getDefaultToolkit().getImage(MyBoxGUI.class.getResource("/images/gift-ideas-gift-card-bridal-gift-baby-shower-gift-gift-box-groom-gift-christmas-gift-party-gift-gift-for-wedding-friend-gift-birthday-gift-baby-gift-good-gift-box-ideas-for-friend-necklace-gift-box.jpg")));
frmMybox.setBounds(100, 100, 800, 500);
frmMybox.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmMybox.getContentPane().setLayout(new CardLayout(0, 0));
frmMybox.setTitle("MyBox");
frmMybox.getContentPane().add(Login);
Login.setLayout(null);
JButton btnNewButton = new JButton("OK");
btnNewButton.addActionListener(new ActionListener()
{
#SuppressWarnings("deprecation")
public void actionPerformed(ActionEvent arg0)
{
Boolean ok = false;
String UName, Pass, Prt, SIP;
UName = UserName.getText();
Pass = passwordField.getText();
Prt = port.getText();
SIP = IP.getText();
if( ( mtd.isUserValid(UName) && mtd.isPasswordValid(Pass) && mtd.isPortValid(Prt) && mtd.isIPValid(SIP))
&& ( !UName.equals("") && !Pass.equals("") && !Prt.equals("") && !SIP.equals("") ) )
ok = true;
else
{
if(!mtd.isUserValid(UName) || UName.equals(""))
JOptionPane.showMessageDialog(frmMybox,"User Name Can Contain Only The Following Characters: ( 0-9 , a-z , A-Z , _ )"
+ " ","Invalid characters",JOptionPane.WARNING_MESSAGE);
else if(!mtd.isPasswordValid(Pass) || Pass.equals(""))
JOptionPane.showMessageDialog(frmMybox,"Invalid characters","Error Message",JOptionPane.WARNING_MESSAGE);
else if(!mtd.isPortValid(Prt) || Prt.equals(""))
JOptionPane.showMessageDialog(frmMybox,"Port Can Contain Only Numbers","Invalid characters",JOptionPane.WARNING_MESSAGE);
else if(!mtd.isIPValid(SIP) || SIP.equals(""))
JOptionPane.showMessageDialog(frmMybox,"IP Address Can Contain Only Numbers seperated By Dots '.' ","Invalid characters",JOptionPane.WARNING_MESSAGE);
}
if(ok)
{
//LoginController user = new LoginController();
//chat= new ClientGUI(IP.getText(),port.getText());
//client = ClientGUI.getClient();
//msg=new Msg("login",user);
//client.handleMessageFromClientUI(msg);
setScreen(Login,UserMenu);
// frmMybox.getContentPane().add(UserMenu, "UserMenu");
// UserMenu.setVisible(true);
// Login.setVisible(false);
}
}
});
btnNewButton.setBounds(344, 313, 82, 48);
Login.add(btnNewButton);
JLabel lblWellcomeToMybox = new JLabel("Wellcome to MyBox");
lblWellcomeToMybox.setForeground(new Color(51, 204, 255));
lblWellcomeToMybox.setFont(new Font("Arial", Font.PLAIN, 36));
lblWellcomeToMybox.setBounds(224, 23, 327, 42);
Login.add(lblWellcomeToMybox);
JLabel lblUserName = new JLabel("User Name:");
lblUserName.setBounds(268, 109, 89, 14);
lblUserName.setFont(new Font("Arial", Font.PLAIN, 14));
Login.add(lblUserName);
JLabel lblPassword = new JLabel("Password:");
lblPassword.setBounds(268, 139, 69, 14);
lblPassword.setFont(new Font("Arial", Font.PLAIN, 14));
Login.add(lblPassword);
JLabel lblServerPort = new JLabel("Server port:");
lblServerPort.setBounds(268, 197, 82, 14);
lblServerPort.setFont(new Font("Arial", Font.PLAIN, 14));
Login.add(lblServerPort);
JLabel lblServerIp = new JLabel("Server IP:");
lblServerIp.setBounds(266, 222, 71, 14);
lblServerIp.setFont(new Font("Arial", Font.PLAIN, 14));
Login.add(lblServerIp);
UserName = new JTextField();
UserName.setBounds(406, 107, 96, 20);
Login.add(UserName);
UserName.setColumns(10);
port = new JTextField();
port.setBounds(406, 195, 96, 20);
Login.add(port);
port.setColumns(10);
IP = new JTextField();
IP.setBounds(406, 220, 96, 20);
Login.add(IP);
IP.setColumns(10);
passwordField = new JPasswordField();
passwordField.setBounds(406, 137, 96, 20);
Login.add(passwordField);
frmMybox.getContentPane().add(UserMenu, "User Menu");
UserMenu.setLayout(null);
JButton LeaveGOI = new JButton("Back");
LeaveGOI.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0)
{
setScreen(UserMenu,Login);
}
});
LeaveGOI.setBounds(10, 66, 153, 23);
UserMenu.add(LeaveGOI);
JButton btnJoinAGoi = new JButton("Join a GOI");
btnJoinAGoi.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
}
});
btnJoinAGoi.setBounds(10, 100, 153, 23);
UserMenu.add(btnJoinAGoi);
JButton btnSearchForA = new JButton("Search for a GOI");
btnSearchForA.setBounds(10, 134, 153, 23);
UserMenu.add(btnSearchForA);
JButton btnCreateAGoi = new JButton("Create a GOI");
btnCreateAGoi.setBounds(10, 32, 153, 23);
UserMenu.add(btnCreateAGoi);
JButton btnFilesSharedWith = new JButton("Files shared with you");
btnFilesSharedWith.setBounds(271, 66, 153, 23);
UserMenu.add(btnFilesSharedWith);
JButton btnUploadAFile = new JButton("Upload a file");
btnUploadAFile.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
JPanel UpLoad = new UploadFile();
setScreen(UserMenu,UpLoad);
// frmMybox.getContentPane().add(UpLoad, "UpLoad");
// UserMenu.setVisible(false);
// UpLoad.setVisible(true);
}
});
btnUploadAFile.setBounds(271, 32, 153, 23);
UserMenu.add(btnUploadAFile);
JButton btnSignout = new JButton("Sign-Out");
btnSignout.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int dialog=JOptionPane.showConfirmDialog(Login, getUserName()+", are you sure you wants to leave?", "Do you want to leave?", JOptionPane.YES_NO_OPTION);
if(dialog==0){
//client.quit();
}
}
});
btnSignout.setBounds(293, 227, 131, 23);
UserMenu.add(btnSignout);
JButton btnHelpme = new JButton("Help-Me");
btnHelpme.addActionListener(new ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
JOptionPane.showMessageDialog(Login,"Hello "+ getUserName()+", wellcom to Mybox!\n"
+ "Inside GOIs buttons you can ask to join, leave and even create a GOI.\n"
+ "Inside Files buttons you can check and edit files people shared with you.\n"
+ "You can even become an uploader and share files you own.\n"
+ "We wish you good luck and have fun using MyBox!");
}
});
btnHelpme.setBounds(10, 227, 131, 23);
UserMenu.add(btnHelpme);
}
public static String getUserName(){
return UserName.getText();
}
#SuppressWarnings("deprecation")
public static String getPassword(){
return passwordField.getText();
}
public static String getIP(){
return IP.getText();
}
public static String getPort(){
return port.getText();
}
public void setScreen(JPanel fls, JPanel tru)
{
frmMybox.getContentPane().add(tru);
tru.setVisible(true);
fls.setVisible(false);
}
}
UploadFile Class
package GUIs;
import javax.swing.JPanel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JTextField;
import main.MyBoxGUI;
public class UploadFile extends MyBoxGUI {
private JTextField textField;
/**
* Create the panel.
*/
public static final JPanel UpLoad = new JPanel();
public UploadFile()
{
setBounds(100, 100, 800, 500);
setLayout(null);
JButton btnNewButton = new JButton("Back");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0)
{
setScreen(UpLoad,UserMenu);
System.out.print("A+++");
}
});
btnNewButton.setBounds(126, 145, 205, 30);
add(btnNewButton);
textField = new JTextField();
textField.setBounds(409, 150, 300, 20);
add(textField);
textField.setColumns(10);
JButton btnDone = new JButton("Done");
btnDone.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnDone.setBounds(365, 223, 89, 30);
add(btnDone);
JButton btnHelpMe = new JButton("Help Me");
btnHelpMe.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnHelpMe.setBounds(188, 390, 122, 52);
add(btnHelpMe);
JButton SignOut = new JButton("Sign-Out");
SignOut.setBounds(501, 392, 122, 48);
add(SignOut);
}
}
public void setScreen(JPanel fls, JPanel tru)
{
frmMybox.getContentPane().add(tru);
tru.setVisible(true);
fls.setVisible(false);
frmMybox.getContentPane().revalidate();
frmMybox.getContentPane().repaint();
}
update your setScreen method as above.

Frame active, but setting visible to false = nullpointer

So i have a bit of a weird issue, i just posted and fixed my other error, but that seems to have created this one, and it makes no sense.
Basically, the user presses a button, this window opens, then whether he presses cancel, or register, this window should setVisible to false. but when this code gets executed, it says my window is null.
package frontend;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
public class Registration extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
private static boolean ranOnce = false;
private JPanel contentPane;
private Registration reg;
private JTextField userTF;
private JTextField passTF;
private JTextField emailTF;
private LoginProcess lp = new LoginProcess();
private JLabel error;
private JButton cancelBtn;
/**
* Create the frame.
*/
public Registration() {
if (!ranOnce) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
reg = new Registration();
reg.setVisible(true);
ranOnce = true;
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 245, 212);
setLocationRelativeTo(null);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblUsername = new JLabel("Username:");
lblUsername.setBounds(10, 11, 75, 14);
contentPane.add(lblUsername);
JLabel lblPassword = new JLabel("Password:");
lblPassword.setBounds(10, 36, 75, 14);
contentPane.add(lblPassword);
JLabel lblEmail = new JLabel("Email:");
lblEmail.setBounds(10, 61, 75, 14);
contentPane.add(lblEmail);
userTF = new JTextField();
userTF.setBounds(95, 8, 130, 20);
contentPane.add(userTF);
userTF.setColumns(10);
passTF = new JTextField();
passTF.setColumns(10);
passTF.setBounds(95, 33, 130, 20);
contentPane.add(passTF);
emailTF = new JTextField();
emailTF.setColumns(10);
emailTF.setBounds(95, 58, 130, 20);
contentPane.add(emailTF);
error = new JLabel("");
error.setBounds(10, 154, 215, 14);
contentPane.add(error);
JButton regBtn = new JButton("Register");
regBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (!userTF.getText().equals("") || !passTF.getText().equals("") || !emailTF.getText().equals("")) {
try {
if (lp.newUser(userTF.getText(), passTF.getText(), emailTF.getText())) {
// THIS IS LINE 117 reg.setVisible(false);
Main.mainFrame.setVisible(true);
} else {
if (lp.duplicateAccount) {
error.setText("Error: Username already in use.");
}
}
} catch (SQLException e) {
}
}
}
});
regBtn.setBounds(10, 120, 215, 23);
contentPane.add(regBtn);
cancelBtn = new JButton("Cancel");
cancelBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
reg.setVisible(false);
Main.mainFrame.setVisible(true);
}
});
cancelBtn.setBounds(10, 86, 215, 23);
contentPane.add(cancelBtn);
}
}
this is the abnormal error:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at frontend.Registration$3.actionPerformed(Registration.java:117)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
i really have no clue as to why it's saying my window is null, when it's not. it has to be something i've done when initialising the window.
Why is it not working ?
You are not using Singleton design pattern correctly. Did you notice that you have two JFrame popping up ?
if (!ranOnce)
{
EventQueue.invokeLater(new Runnable()//this call the run method in a separate thread
{
public void run()
{
try
{
// for the current instance of Registration, you are setting
// the reg variable by calling another instance of Registration => thats not the correct way to do a Singleton
reg = new Registration();
reg.setVisible(true);
ranOnce = true;
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
}
So, let's assume you are calling new Registration() in your main method, you will enter the public Registration() constructor (let's call it instance1) and set the variable reg by calling one more time the constructor new Registration() (instance2) but by this time, ranOnce will be true and so EventQueue.invokeLater will not be called => reg will not be set in instance2 => NullPointerException when clicking on Jbutton in the second frame (the one on the top) (instance2). Clicking on first frame (instance1) button's will hide the second frame (instance2).
How to fix it ?
Use a proper Singleton :
private static final long serialVersionUID = 1L;
private static boolean ranOnce = false;
private JPanel contentPane;
private static Registration reg;
private JTextField userTF;
private JTextField passTF;
private JTextField emailTF;
private LoginProcess lp = new LoginProcess();
private JLabel error;
private JButton cancelBtn;
public static synchronized Registration getRegistration()
{
if(reg == null)
reg = new Registration();
return reg;
}
/**
* Create the frame.
*/
private Registration()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 245, 212);
setLocationRelativeTo(null);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblUsername = new JLabel("Username:");
lblUsername.setBounds(10, 11, 75, 14);
contentPane.add(lblUsername);
JLabel lblPassword = new JLabel("Password:");
lblPassword.setBounds(10, 36, 75, 14);
contentPane.add(lblPassword);
JLabel lblEmail = new JLabel("Email:");
lblEmail.setBounds(10, 61, 75, 14);
contentPane.add(lblEmail);
userTF = new JTextField();
userTF.setBounds(95, 8, 130, 20);
contentPane.add(userTF);
userTF.setColumns(10);
passTF = new JTextField();
passTF.setColumns(10);
passTF.setBounds(95, 33, 130, 20);
contentPane.add(passTF);
emailTF = new JTextField();
emailTF.setColumns(10);
emailTF.setBounds(95, 58, 130, 20);
contentPane.add(emailTF);
error = new JLabel("");
error.setBounds(10, 154, 215, 14);
contentPane.add(error);
JButton regBtn = new JButton("Register");
regBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (!userTF.getText().equals("") || !passTF.getText().equals("") || !emailTF.getText().equals("")) {
try {
if (lp.newUser(userTF.getText(), passTF.getText(), emailTF.getText())) {
setVisible(false);
Main.mainFrame.setVisible(true);
} else {
if (lp.duplicateAccount) {
error.setText("Error: Username already in use.");
}
}
} catch (SQLException e) {
}
}
}
});
regBtn.setBounds(10, 120, 215, 23);
contentPane.add(regBtn);
cancelBtn = new JButton("Cancel");
cancelBtn.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
setVisible(false);
}
});
cancelBtn.setBounds(10, 86, 215, 23);
contentPane.add(cancelBtn);
}
public static void main(String[] args)
{
Registration registration = Registration.getRegistration();
registration.setVisible(true);
}
Try setVisible(fasle) instead of reg.setVisible(false)

Categories

Resources