What is wrong with this Java random software code? - java

I have made software in Java that generates random number in range. But it don't work. Sorry for strange language and comments. I have three classes: main, for generating and GUI. When I click button to generate it shows 0 on screen. Please help me.
public class glavnaKlasa {
static public int broj;
public static void main(String[] args) {
GUI guiObject = new GUI();
guiObject.mainGUI();
generisanje generisanjeObject = new generisanje();
broj = generisanjeObject.glavno(guiObject.min, guiObject.max);
}
}
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import java.awt.Font;
import java.awt.Color;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class GUI {
private JFrame frmNasumicniBroj;
private JTextField textField;
private JTextField textField_1;
private JLabel lblNasumicniBroj;
private JTextField textField_2;
/**
* Launch the application.
*/
public static void mainGUI() {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
GUI window = new GUI();
window.frmNasumicniBroj.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public GUI() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
public int min, max;
private void initialize() {
frmNasumicniBroj = new JFrame();
frmNasumicniBroj.setTitle("Nasumicni broj");
frmNasumicniBroj.getContentPane().setBackground(Color.CYAN);
frmNasumicniBroj.setBounds(100, 100, 400, 300);
frmNasumicniBroj.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmNasumicniBroj.getContentPane().setLayout(null);
JLabel lblNewLabel = new JLabel("Donja granica: ");
lblNewLabel.setForeground(Color.YELLOW);
lblNewLabel.setFont(new Font("Wide Latin", Font.PLAIN, 12));
lblNewLabel.setBounds(10, 11, 154, 14);
frmNasumicniBroj.getContentPane().add(lblNewLabel);
textField = new JTextField();
textField.setBounds(200, 8, 154, 20);
frmNasumicniBroj.getContentPane().add(textField);
textField.setColumns(10);
JLabel lblGornjaGranica = new JLabel("Gornja granica: ");
lblGornjaGranica.setForeground(Color.YELLOW);
lblGornjaGranica.setFont(new Font("Wide Latin", Font.PLAIN, 12));
lblGornjaGranica.setBounds(10, 36, 165, 14);
frmNasumicniBroj.getContentPane().add(lblGornjaGranica);
textField_1 = new JTextField();
textField_1.setColumns(10);
textField_1.setBounds(200, 33, 154, 20);
frmNasumicniBroj.getContentPane().add(textField_1);
lblNasumicniBroj = new JLabel("Nasumicni broj: ");
lblNasumicniBroj.setForeground(Color.YELLOW);
lblNasumicniBroj.setFont(new Font("Wide Latin", Font.PLAIN, 12));
lblNasumicniBroj.setBounds(10, 144, 180, 14);
frmNasumicniBroj.getContentPane().add(lblNasumicniBroj);
textField_2 = new JTextField();
textField_2.setEditable(false);
textField_2.setBounds(200, 141, 154, 20);
frmNasumicniBroj.getContentPane().add(textField_2);
textField_2.setColumns(10);
JButton btnNewButton = new JButton("GENERISI");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try{
min = Integer.parseInt(textField.getText());
max = Integer.parseInt(textField_1.getText());
glavnaKlasa glKlasa = new glavnaKlasa();
String brString = Integer.toString(glKlasa.broj);
textField_2.setText(brString);
}catch (Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
});
btnNewButton.setFont(new Font("Tahoma", Font.BOLD, 14));
btnNewButton.setBounds(10, 61, 345, 72);
frmNasumicniBroj.getContentPane().add(btnNewButton);
JLabel lblVerzija = new JLabel("Verzija: 1.0");
lblVerzija.setFont(new Font("Tahoma", Font.BOLD | Font.ITALIC, 11));
lblVerzija.setBounds(10, 180, 71, 14);
frmNasumicniBroj.getContentPane().add(lblVerzija);
JLabel label_1 = new JLabel("Autor: Djordje Milanovic");
label_1.setFont(new Font("Tahoma", Font.BOLD | Font.ITALIC, 11));
label_1.setBounds(10, 205, 141, 14);
frmNasumicniBroj.getContentPane().add(label_1);
JLabel label_2 = new JLabel("Copyright: Alfin Informatics");
label_2.setFont(new Font("Tahoma", Font.BOLD | Font.ITALIC, 11));
label_2.setBounds(9, 236, 166, 14);
frmNasumicniBroj.getContentPane().add(label_2);
}}
import java.util.Random;
import javax.swing.JOptionPane;
public class generisanje {
public static int glavno(int min, int max){
if (min >= max) {
JOptionPane.showMessageDialog(null, "Maksimalni broj mora biti veci od minimalnog");
}
Random rnd = new Random();
return rnd.nextInt((max - min) + 1) + min;
}
}

This:
glavnaKlasa glKlasa = new glavnaKlasa();
creates the object with empty constructor, your main will not run there, so broj remains uninitialized.
Actually, you don't need to instantiate this class there, just this:
public void actionPerformed(ActionEvent arg0) {
try{
min = Integer.parseInt(textField.getText());
max = Integer.parseInt(textField_1.getText());
int broj = generisanje.glavno(guiObject.min, guiObject.max);
String brString = Integer.toString(broj);
textField_2.setText(brString);
}catch (Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
Also consider working according to Java coding standards ( class name first uppercase and so on, it will be much easier to maintain the code).

Related

How to display multiple jpassword field in pop up in swing java?

I have 2 JTextField and 2 JPasswordField component in my swing java which frame looks as below:
When ShowAllDetails button is clicked, all the entered details is displayed in JtextArea as shown below:
Below is the code for the same:
package popUpTest;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JTextArea;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class PopUpTest
{
private JFrame frame;
private JPasswordField passSourcePassword;
private JTextField txtSourceUserName;
private JTextField txtTargetUserName;
private JPasswordField passTargetPassword;
/**
* Launch the application.
*/
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
try
{
PopUpTest window = new PopUpTest();
window.frame.setVisible(true);
} catch (Exception e)
{
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public PopUpTest()
{
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize()
{
frame = new JFrame();
frame.setBounds(100, 100, 444, 403);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel lblSourceUserName = new JLabel("SourceUserName:");
lblSourceUserName.setFont(new Font("Tahoma", Font.BOLD, 16));
lblSourceUserName.setBounds(15, 62, 170, 20);
frame.getContentPane().add(lblSourceUserName);
passSourcePassword = new JPasswordField();
passSourcePassword.setBounds(15, 153, 147, 26);
frame.getContentPane().add(passSourcePassword);
JLabel lblSourcePassword = new JLabel("SourcePassword:");
lblSourcePassword.setFont(new Font("Tahoma", Font.BOLD, 16));
lblSourcePassword.setBounds(15, 132, 147, 20);
frame.getContentPane().add(lblSourcePassword);
txtSourceUserName = new JTextField();
txtSourceUserName.setBounds(16, 81, 146, 26);
frame.getContentPane().add(txtSourceUserName);
txtSourceUserName.setColumns(10);
JLabel lblTargetUserName = new JLabel("TargetUserName:");
lblTargetUserName.setFont(new Font("Tahoma", Font.BOLD, 16));
lblTargetUserName.setBounds(240, 62, 170, 20);
frame.getContentPane().add(lblTargetUserName);
txtTargetUserName = new JTextField();
txtTargetUserName.setColumns(10);
txtTargetUserName.setBounds(241, 81, 146, 26);
frame.getContentPane().add(txtTargetUserName);
JLabel lblTargetPassword = new JLabel("TargetPassword:");
lblTargetPassword.setFont(new Font("Tahoma", Font.BOLD, 16));
lblTargetPassword.setBounds(240, 132, 147, 20);
frame.getContentPane().add(lblTargetPassword);
passTargetPassword = new JPasswordField();
passTargetPassword.setBounds(240, 153, 147, 26);
frame.getContentPane().add(passTargetPassword);
JLabel lblEnterBelowDetails = new JLabel("Enter Below Details:");
lblEnterBelowDetails.setFont(new Font("Tahoma", Font.BOLD, 16));
lblEnterBelowDetails.setBounds(15, 26, 187, 20);
frame.getContentPane().add(lblEnterBelowDetails);
JTextArea textArea = new JTextArea();
textArea.setBounds(15, 252, 365, 85);
frame.getContentPane().add(textArea);
JButton btnShowAllDetails = new JButton("Show All Details:");
btnShowAllDetails.setBounds(15, 207, 226, 29);
frame.getContentPane().add(btnShowAllDetails);
btnShowAllDetails.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
textArea.append(txtSourceUserName.getText() + "\n");
textArea.append(passSourcePassword.getText() + "\n");
textArea.append(txtTargetUserName.getText() + "\n");
textArea.append(passTargetPassword.getText() + "\n");
}
});
}
}
Now instead of diplaying these 4 components on loading the main frame instead, i want to diplay these 4 components in a Pop up Window on click of a button as below:
Also on clicking of Show All Details button should work as before.(i.e. it should populate JtextArea with the values entered in Pop Up)
How can I achieve this?
I have gone through other blogs as well however didn't find to show such multiple JPasswordField/JTextField in popup.Any guidance would be highly appreciated.
Just add the new components (JTextFields and JPasswordFields) within a button listener and call repaint() and revalidate() on the frame after that.
Here is a solution without proper layout:
EDIT:
package popUpTest;
import java.awt.EventQueue;
import javax.swing.*;
import java.awt.Font;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class PopUpTest
{
private JFrame frame;
private JPasswordField passSourcePassword;
private JTextField txtSourceUserName;
private JTextField txtTargetUserName;
private JPasswordField passTargetPassword;
private JTextArea textArea;
/**
* Launch the application.
*/
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
try
{
PopUpTest window = new PopUpTest();
window.frame.setVisible(true);
} catch (Exception e)
{
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public PopUpTest()
{
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize()
{
frame = new JFrame();
frame.setBounds(100, 100, 444, 403);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JButton popUpButton = new JButton("Click to Show Pop Up To Enter Detail");
popUpButton.setBounds(15, 100, 365, 85);
popUpButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
new MyDialog();
}
});
frame.getContentPane().add(popUpButton);
textArea = new JTextArea();
textArea.setBounds(15, 252, 365, 85);
frame.getContentPane().add(textArea);
JButton btnShowAllDetails = new JButton("Show All Details:");
btnShowAllDetails.setBounds(15, 207, 226, 29);
frame.getContentPane().add(btnShowAllDetails);
btnShowAllDetails.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
textArea.append(txtSourceUserName.getText() + "\n");
textArea.append(passSourcePassword.getText() + "\n");
textArea.append(txtTargetUserName.getText() + "\n");
textArea.append(passTargetPassword.getText() + "\n");
}
});
}
public JTextArea getTextArea() {
return textArea;
}
private class MyDialog extends JDialog {
private final JPasswordField passSourcePassword;
private final JTextField txtSourceUserName;
private final JTextField txtTargetUserName;
private final JPasswordField passTargetPassword;
public MyDialog() {
setSize(600, 500);
setLayout(null);
JLabel lblEnterBelowDetails = new JLabel("Enter Below Details:");
lblEnterBelowDetails.setFont(new Font("Tahoma", Font.BOLD, 16));
lblEnterBelowDetails.setBounds(15, 26, 187, 20);
add(lblEnterBelowDetails);
JLabel lblSourceUserName = new JLabel("SourceUserName:");
lblSourceUserName.setFont(new Font("Tahoma", Font.BOLD, 16));
lblSourceUserName.setBounds(15, 62, 170, 20);
add(lblSourceUserName);
passSourcePassword = new JPasswordField();
passSourcePassword.setBounds(15, 153, 147, 26);
add(passSourcePassword);
JLabel lblSourcePassword = new JLabel("SourcePassword:");
lblSourcePassword.setFont(new Font("Tahoma", Font.BOLD, 16));
lblSourcePassword.setBounds(15, 132, 147, 20);
add(lblSourcePassword);
txtSourceUserName = new JTextField();
txtSourceUserName.setBounds(16, 81, 146, 26);
add(txtSourceUserName);
txtSourceUserName.setColumns(10);
JLabel lblTargetUserName = new JLabel("TargetUserName:");
lblTargetUserName.setFont(new Font("Tahoma", Font.BOLD, 16));
lblTargetUserName.setBounds(240, 62, 170, 20);
add(lblTargetUserName);
txtTargetUserName = new JTextField();
txtTargetUserName.setColumns(10);
txtTargetUserName.setBounds(241, 81, 146, 26);
add(txtTargetUserName);
JLabel lblTargetPassword = new JLabel("TargetPassword:");
lblTargetPassword.setFont(new Font("Tahoma", Font.BOLD, 16));
lblTargetPassword.setBounds(240, 132, 147, 20);
add(lblTargetPassword);
passTargetPassword = new JPasswordField();
passTargetPassword.setBounds(240, 153, 147, 26);
add(passTargetPassword);
JButton publishButton = new JButton("Publish");
publishButton.setBounds(100, 200, 146, 26);
add(publishButton);
publishButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
textArea.append(txtSourceUserName.getText() + "\n");
textArea.append(passSourcePassword.getText() + "\n");
textArea.append(txtTargetUserName.getText() + "\n");
textArea.append(passTargetPassword.getText() + "\n");
dispose();
}
});
setVisible(true);
}
}
}
By the way: try to read about layout managers as soon as possible, because absolute coordinates are a pain in the ass ;-)

add dynamic checkbox in java windowbuilder

I want to add a dynamic checkbox after selecting an item in combo box.
I am working on eclipse and design my frame on window builder.
final JComboBox<String> comboBox = new JComboBox<String>();
comboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String typeName = comboBox.getSelectedItem().toString();
for (int i = 0; i < SqlQuery.getCoursesName(typeName).size(); i++) {
JCheckBox c = new JCheckBox(SqlQuery.getCoursesName(typeName).get(i));
c.setVisible(true);
coursePanel.add(c);
frame.repaint();
frame.validate();
System.out.println(c.getText());
}
}
});
comboBox.setBounds(208, 221, 91, 20);
frame.getContentPane().add(comboBox);
edit: thats my full code.
public class registerForm {
private JFrame frame;
private JTextField txtFirstName;
private JTextField txtLastName;
private JTextField txtPassword;
private JTextField txtEmail;
List<Integer> coursesId; // ן¿½ן¿½ן¿½ן¿½ן¿½ ן¿½ן¿½ ן¿½ן¿½ן¿½ן¿½ן¿½ ן¿½ן¿½ ן¿½ן¿½ן¿½ן¿½ן¿½ן¿½
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
registerForm window = new registerForm();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public registerForm() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 442);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel lblNewLabel = new JLabel("\u05D4\u05E8\u05E9\u05DE\u05D4");
lblNewLabel.setBounds(165, 11, 91, 29);
lblNewLabel.setFont(new Font("Tahoma", Font.BOLD, 24));
frame.getContentPane().add(lblNewLabel);
JLabel label = new JLabel("\u05E9\u05DD \u05E4\u05E8\u05D8\u05D9:");
label.setBounds(363, 55, 61, 14);
label.setFont(new Font("Tahoma", Font.PLAIN, 14));
frame.getContentPane().add(label);
txtFirstName = new JTextField();
txtFirstName.setBounds(75, 51, 221, 20);
frame.getContentPane().add(txtFirstName);
txtFirstName.setColumns(10);
JLabel label_1 = new JLabel("\u05E9\u05DD \u05DE\u05E9\u05E4\u05D7\u05D4:");
label_1.setBounds(344, 80, 80, 14);
label_1.setFont(new Font("Tahoma", Font.PLAIN, 14));
frame.getContentPane().add(label_1);
txtLastName = new JTextField();
txtLastName.setBounds(75, 82, 221, 20);
txtLastName.setColumns(10);
frame.getContentPane().add(txtLastName);
txtPassword = new JTextField();
txtPassword.setBounds(75, 140, 221, 20);
txtPassword.setColumns(10);
frame.getContentPane().add(txtPassword);
JLabel label_2 = new JLabel("\u05DE\u05D9\u05D9\u05DC:");
label_2.setBounds(392, 110, 32, 14);
label_2.setFont(new Font("Tahoma", Font.PLAIN, 14));
frame.getContentPane().add(label_2);
txtEmail = new JTextField();
txtEmail.setBounds(75, 109, 221, 20);
txtEmail.setColumns(10);
frame.getContentPane().add(txtEmail);
JLabel label_3 = new JLabel("\u05E1\u05D9\u05E1\u05DE\u05D0:");
label_3.setBounds(373, 141, 51, 14);
label_3.setFont(new Font("Tahoma", Font.PLAIN, 14));
frame.getContentPane().add(label_3);
final JDateChooser dateChooser = new JDateChooser();
dateChooser.setBounds(75, 171, 221, 39);
frame.getContentPane().add(dateChooser);
JLabel label_4 = new JLabel("\u05EA\u05D0\u05E8\u05D9\u05DA \u05DC\u05D9\u05D3\u05D4:");
label_4.setBounds(344, 167, 90, 14);
label_4.setFont(new Font("Tahoma", Font.PLAIN, 14));
frame.getContentPane().add(label_4);
JButton btnSend = new JButton("\u05E9\u05DC\u05D7");
btnSend.setBounds(258, 334, 61, 58);
btnSend.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// date
Date date = new Date(dateChooser.getDate().getTime());
}
});
frame.getContentPane().add(btnSend);
JButton button = new JButton("\u05E0\u05E7\u05D4");
button.setBounds(175, 334, 61, 58);
frame.getContentPane().add(button);
JLabel label_5 = new JLabel("\u05DE\u05D2\u05DE\u05D4:");
label_5.setFont(new Font("Tahoma", Font.PLAIN, 14));
label_5.setBounds(382, 218, 42, 14);
frame.getContentPane().add(label_5);
final JPanel coursePanel = new JPanel();
coursePanel.setBounds(10, 249, 286, 74);
frame.getContentPane().add(coursePanel);
coursePanel.setLayout(null);
final JComboBox<String> comboBox = new JComboBox<String>();
comboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String typeName = comboBox.getSelectedItem().toString();
for (int i = 0; i < SqlQuery.getCoursesName(typeName).size(); i++) {
JCheckBox c = new JCheckBox(SqlQuery.getCoursesName(typeName).get(i));
int selectedIndex = comboBox.getSelectedIndex();
boolean isInPanel = c.getParent() == coursePanel;
if (selectedIndex == 1 && !isInPanel) {
coursePanel.add(c);
coursePanel.repaint(); //Repaint the proper panel that has this component.
coursePanel.revalidate();
} else if (isInPanel && selectedIndex != 1) {
coursePanel.remove(c);
coursePanel.repaint(); //Repaint the proper panel that has this component.
coursePanel.revalidate();
}
coursePanel.repaint();
coursePanel.validate();
System.out.println(c.getText());
}
}
});
comboBox.setBounds(208, 221, 91, 20);
frame.getContentPane().add(comboBox);
// fill comboBox
List<String> lst = SqlQuery.getTypes();
for (int i = 0; i < lst.size(); i++)
comboBox.addItem(lst.get(i));
JLabel label_6 = new JLabel("\u05E9\u05DC\u05D9\u05D8\u05D4 \u05D1\u05E7\u05D5\u05E8\u05E1\u05D9\u05DD");
label_6.setFont(new Font("Tahoma", Font.PLAIN, 14));
label_6.setBounds(321, 245, 103, 14);
frame.getContentPane().add(label_6);
}
}
Hope you understand what I wrote. I want to show a list of coursesName after click on the comboBox.
Why the frame does'nt show the checkbox?
Thank you.
First and foremost. The comboBox.setBounds() is a very bad practice. Take some time and see Layout Managers. Also add 'swing' tag in your post since you are referring to Swing library.
The frame doesn't show the component because you repaint the wrong one. You add the checkbox in coursePanel, which means you have to repaint() & revalidate() coursePanel. So coursePanel.repaint() instead of frame.repaint() will help you.
Also checkBox.setVisible(true)is not required, since checkBox is visible by default.
Finally i have added the way of how i would do it.
package test;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Test {
private JFrame frame;
private JCheckBox checkBox;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Test window = new Test();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Test() {
frame = new JFrame();
frame.setPreferredSize(new Dimension(300, 300));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(createPanel());
frame.pack();
}
private JPanel createPanel() {
JPanel p = new JPanel(new FlowLayout());
checkBox = new JCheckBox("I am a checkbox"); //Create the checkbox
JComboBox<String> combo = new JComboBox<>();
combo.addItem("Hello");
combo.addItem("Stack");
combo.addItem("OverFlow");
combo.addActionListener(e -> {
//Its better to handle indices when there is not dynmic data to your combobox
int selectedIndex = combo.getSelectedIndex();
boolean isInPanel = checkBox.getParent() == p;
if (selectedIndex == 1 && !isInPanel) {
p.add(checkBox);
p.repaint(); //Repaint the proper panel that has this component.
p.revalidate();
} else if (isInPanel && selectedIndex != 1) {
p.remove(checkBox);
p.repaint(); //Repaint the proper panel that has this component.
p.revalidate();
}
});
p.add(combo);
return p;
}
}
The answer to your problem (make the checkbox visible) after comments:
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class registerForm {
private JFrame frame;
private JTextField txtFirstName;
private JTextField txtLastName;
private JTextField txtPassword;
private JTextField txtEmail;
private JCheckBox checkBox;
List<Integer> coursesId; // ן¿½ן¿½ן¿½ן¿½ן¿½ ן¿½ן¿½ ן¿½ן¿½ן¿½ן¿½ן¿½ ן¿½ן¿½ ן¿½ן¿½ן¿½ן¿½ן¿½ן¿½
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
registerForm window = new registerForm();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public registerForm() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 442);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel lblNewLabel = new JLabel("\u05D4\u05E8\u05E9\u05DE\u05D4");
lblNewLabel.setBounds(165, 11, 91, 29);
lblNewLabel.setFont(new Font("Tahoma", Font.BOLD, 24));
frame.getContentPane().add(lblNewLabel);
JLabel label = new JLabel("\u05E9\u05DD \u05E4\u05E8\u05D8\u05D9:");
label.setBounds(363, 55, 61, 14);
label.setFont(new Font("Tahoma", Font.PLAIN, 14));
frame.getContentPane().add(label);
txtFirstName = new JTextField();
txtFirstName.setBounds(75, 51, 221, 20);
frame.getContentPane().add(txtFirstName);
txtFirstName.setColumns(10);
JLabel label_1 = new JLabel("\u05E9\u05DD \u05DE\u05E9\u05E4\u05D7\u05D4:");
label_1.setBounds(344, 80, 80, 14);
label_1.setFont(new Font("Tahoma", Font.PLAIN, 14));
frame.getContentPane().add(label_1);
txtLastName = new JTextField();
txtLastName.setBounds(75, 82, 221, 20);
txtLastName.setColumns(10);
frame.getContentPane().add(txtLastName);
txtPassword = new JTextField();
txtPassword.setBounds(75, 140, 221, 20);
txtPassword.setColumns(10);
frame.getContentPane().add(txtPassword);
JLabel label_2 = new JLabel("\u05DE\u05D9\u05D9\u05DC:");
label_2.setBounds(392, 110, 32, 14);
label_2.setFont(new Font("Tahoma", Font.PLAIN, 14));
frame.getContentPane().add(label_2);
txtEmail = new JTextField();
txtEmail.setBounds(75, 109, 221, 20);
txtEmail.setColumns(10);
frame.getContentPane().add(txtEmail);
JLabel label_3 = new JLabel("\u05E1\u05D9\u05E1\u05DE\u05D0:");
label_3.setBounds(373, 141, 51, 14);
label_3.setFont(new Font("Tahoma", Font.PLAIN, 14));
frame.getContentPane().add(label_3);
JLabel label_4 = new JLabel("\u05EA\u05D0\u05E8\u05D9\u05DA \u05DC\u05D9\u05D3\u05D4:");
label_4.setBounds(344, 167, 90, 14);
label_4.setFont(new Font("Tahoma", Font.PLAIN, 14));
frame.getContentPane().add(label_4);
JButton button = new JButton("\u05E0\u05E7\u05D4");
button.setBounds(175, 334, 61, 58);
frame.getContentPane().add(button);
JLabel label_5 = new JLabel("\u05DE\u05D2\u05DE\u05D4:");
label_5.setFont(new Font("Tahoma", Font.PLAIN, 14));
label_5.setBounds(382, 218, 42, 14);
frame.getContentPane().add(label_5);
final JPanel coursePanel = new JPanel();
coursePanel.setBounds(10, 249, 286, 74);
frame.getContentPane().add(coursePanel);
coursePanel.setLayout(null);
List<String> lst = new ArrayList<>();
lst.add("Hello");
lst.add("Stack");
lst.add("Over");
lst.add("Flow");
//Prepare the checkBox
checkBox = new JCheckBox("nothing");
final JComboBox<String> comboBox = new JComboBox<String>();
comboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String typeName = comboBox.getSelectedItem().toString();
for (int i = 0; i < lst.size(); i++) {
checkBox.setText(typeName);
//set the same bounds as comboBox but reduce its X by 80.
//Compare checkBoxbounds and combobox bounds
//Remind: setBounds is baaaaad practice.
checkBox.setBounds(128, 221, 91, 20);
//if you want to add it in coursePanel, change all frame.getContentPane() to coursePanel
int selectedIndex = comboBox.getSelectedIndex();
boolean isInPanel = checkBox.getParent() == frame.getContentPane();
if (selectedIndex == 1 && !isInPanel) {
frame.getContentPane().add(checkBox);
} else if (isInPanel && selectedIndex != 1) {
frame.getContentPane().remove(checkBox);
}
frame.getContentPane().repaint();
frame.getContentPane().validate();
System.out.println(checkBox.getText());
}
}
});
comboBox.setBounds(208, 221, 91, 20);
frame.getContentPane().add(comboBox);
// fill comboBox
for (int i = 0; i < lst.size(); i++)
comboBox.addItem(lst.get(i));
JLabel label_6 = new JLabel("\u05E9\u05DC\u05D9\u05D8\u05D4 \u05D1\u05E7\u05D5\u05E8\u05E1\u05D9\u05DD");
label_6.setFont(new Font("Tahoma", Font.PLAIN, 14));
label_6.setBounds(321, 245, 103, 14);
frame.getContentPane().add(label_6);
}
}
Another option is to create the checkbox as a field outside of the actionlistener (like i did) and set its bounds with window builder and use setVisible(false). Then on your listener, setVisible(true)

Exported GUI project won't open/run, exported using eclipse oxygen Java

I've been having trouble with exporting my GUI project from Eclipse Oxygen. At first I tried exporting my project by going to export>Runnable Jar File>Main Class, but when I try and open my program nothing shows up. Then I tried opening the GUI inside its own class by specifying a Main method in there, and I keep getting the error that I put in the title. Any help would be appreciated. I'll post both of my classes here.
Also I used WindowBuilder plugin to build my GUI.
Main class
package me.iran.cryptotracker;
import java.util.ArrayList;
import lombok.Getter;
import me.iran.cryptotracker.window.Window;
public class CryptoTracker {
private static SaveFile saveFile = new SaveFile();
private static ReadFile readFile = new ReadFile();
#Getter
public static ArrayList<Crypto> allCrypto = new ArrayList<Crypto>();
public static void main(String[] args) {
readFile.openFile();
readFile.readFile();
readFile.closeFile();
saveFile.openFile();
saveFile.updateFile();
saveFile.closeFile();
Window.open();
}
}
Window1 Class
package me.iran.cryptotracker.window;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTable;
import javax.swing.SpringLayout;
import javax.swing.UIManager;
import javax.swing.table.DefaultTableModel;
import lombok.Getter;
import me.iran.cryptotracker.Crypto;
import me.iran.cryptotracker.CryptoTracker;
import me.iran.cryptotracker.ReadFile;
import me.iran.cryptotracker.SaveFile;
public class Window {
static #Getter
private JFrame frame;
#Getter
private static JTable table;
/**
* Launch the application.
*/
public static void open() {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Window window = new Window();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Window() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBackground(Color.DARK_GRAY);
frame.getContentPane().setBackground(Color.DARK_GRAY);
frame.setBounds(100, 100, 571, 622);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
table = new JTable();
table.setBorder(UIManager.getBorder("Table.focusCellHighlightBorder"));
table.setBackground(new Color(169, 169, 169));
Object columnName[] = {"Name", "Date", "Initial Price", "Stock", "URL"};
DefaultTableModel model = new DefaultTableModel(columnName, 0);
model.addRow(columnName);
for(Crypto crypto : CryptoTracker.allCrypto) {
String name = crypto.getName();
String date = crypto.getDate();
double initial = crypto.getInitialPrice();
double amount = crypto.getAmount();
String url = crypto.getUrl();
Object[] data = {name, date, initial + "", amount + "", url};
model.addRow(data);
}
SpringLayout springLayout = new SpringLayout();
springLayout.putConstraint(SpringLayout.NORTH, table, 37, SpringLayout.NORTH, frame.getContentPane());
springLayout.putConstraint(SpringLayout.WEST, table, 30, SpringLayout.WEST, frame.getContentPane());
springLayout.putConstraint(SpringLayout.SOUTH, table, 478, SpringLayout.NORTH, frame.getContentPane());
springLayout.putConstraint(SpringLayout.EAST, table, 464, SpringLayout.WEST, frame.getContentPane());
frame.getContentPane().setLayout(springLayout);
table.setModel(model);
frame.getContentPane().add(table);
JButton btnAdd = new JButton("Add Currency");
springLayout.putConstraint(SpringLayout.NORTH, btnAdd, -48, SpringLayout.SOUTH, frame.getContentPane());
springLayout.putConstraint(SpringLayout.WEST, btnAdd, 0, SpringLayout.WEST, table);
springLayout.putConstraint(SpringLayout.SOUTH, btnAdd, -25, SpringLayout.SOUTH, frame.getContentPane());
springLayout.putConstraint(SpringLayout.EAST, btnAdd, 150, SpringLayout.WEST, frame.getContentPane());
frame.getContentPane().add(btnAdd);
btnAdd.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
frame.setVisible(false);
AddWindow.open();
}
});
}
public static void updateTable(JTable table) {
DefaultTableModel model = (DefaultTableModel) table.getModel();
model.setRowCount(0);
Object columnName[] = {"Name", "Date", "Initial Price", "Stock", "URL"};
model.addRow(columnName);
for(Crypto crypto : CryptoTracker.allCrypto) {
String name = crypto.getName();
String date = crypto.getDate();
double initial = crypto.getInitialPrice();
double amount = crypto.getAmount();
String url = crypto.getUrl();
Object[] data = {name, date, initial + "", amount + "", url};
model.addRow(data);
}
table.setModel(model);
}
}
Window 2 Class
package me.iran.cryptotracker.window;
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.JTextField;
import me.iran.cryptotracker.Crypto;
import me.iran.cryptotracker.CryptoTracker;
import me.iran.cryptotracker.SaveFile;
public class AddWindow {
private JFrame frame;
private JTextField txtName;
private JTextField txtDate;
private JTextField txtCost;
private JTextField txtAmount;
private JTextField txtURL;
private SaveFile saveFile = new SaveFile();
public static void open() {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
AddWindow window = new AddWindow();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public AddWindow() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.getContentPane().setBackground(Color.LIGHT_GRAY);
frame.getContentPane().setLayout(null);
txtName = new JTextField();
txtName.setFont(new Font("Cambria Math", Font.PLAIN, 14));
txtName.setBounds(107, 11, 138, 20);
frame.getContentPane().add(txtName);
txtName.setColumns(10);
txtDate = new JTextField();
txtDate.setFont(new Font("Cambria Math", Font.PLAIN, 14));
txtDate.setColumns(10);
txtDate.setBounds(107, 44, 138, 20);
frame.getContentPane().add(txtDate);
txtCost = new JTextField();
txtCost.setFont(new Font("Cambria Math", Font.PLAIN, 14));
txtCost.setColumns(10);
txtCost.setBounds(107, 75, 138, 20);
frame.getContentPane().add(txtCost);
txtAmount = new JTextField();
txtAmount.setFont(new Font("Cambria Math", Font.PLAIN, 14));
txtAmount.setColumns(10);
txtAmount.setBounds(107, 106, 138, 20);
frame.getContentPane().add(txtAmount);
txtURL = new JTextField();
txtURL.setFont(new Font("Cambria Math", Font.PLAIN, 14));
txtURL.setColumns(10);
txtURL.setBounds(107, 137, 138, 20);
frame.getContentPane().add(txtURL);
JLabel lblName = new JLabel("Name");
lblName.setFont(new Font("Cambria Math", Font.PLAIN, 14));
lblName.setBounds(22, 11, 46, 14);
frame.getContentPane().add(lblName);
JLabel lblDate = new JLabel("Date");
lblDate.setFont(new Font("Cambria Math", Font.PLAIN, 14));
lblDate.setBounds(22, 44, 46, 14);
frame.getContentPane().add(lblDate);
JLabel lblInitialCost = new JLabel("Initial Cost");
lblInitialCost.setFont(new Font("Cambria Math", Font.PLAIN, 14));
lblInitialCost.setBounds(22, 75, 75, 14);
frame.getContentPane().add(lblInitialCost);
JLabel lblAmount = new JLabel("Amount");
lblAmount.setFont(new Font("Cambria Math", Font.PLAIN, 14));
lblAmount.setBounds(22, 106, 63, 14);
frame.getContentPane().add(lblAmount);
JLabel lblUrl = new JLabel("URL");
lblUrl.setFont(new Font("Cambria Math", Font.PLAIN, 14));
lblUrl.setBounds(22, 137, 46, 14);
frame.getContentPane().add(lblUrl);
final JLabel lblError = new JLabel("");
lblError.setFont(new Font("Cambria Math", Font.PLAIN, 14));
lblError.setBounds(278, 59, 284, 102);
frame.getContentPane().add(lblError);
JButton btnAddCurrency = new JButton("Add Currency");
btnAddCurrency.setBounds(355, 11, 138, 38);
frame.getContentPane().add(btnAddCurrency);
frame.setBackground(Color.LIGHT_GRAY);
frame.setBounds(100, 100, 588, 211);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
btnAddCurrency.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
if(!txtName.getText().isEmpty() && !txtDate.getText().isEmpty() && !txtURL.getText().isEmpty() && !txtCost.getText().isEmpty() && !txtAmount.getText().isEmpty()) {
String name = txtName.getText();
String date = txtDate.getText();
String url = txtURL.getText();
try {
double initial = Double.parseDouble(txtCost.getText());
double amount = Double.parseDouble(txtAmount.getText());
CryptoTracker.allCrypto.add(new Crypto(name, date, url, initial, amount));
saveFile.openFile();
saveFile.updateFile();
saveFile.closeFile();
frame.setVisible(false);
Window.getFrame().setVisible(true);
Window.updateTable(Window.getTable());
} catch(Exception exc) {
lblError.setText("You have not entered a number in the Initial Cost and/or Amount field");
}
}
}
});
}
}
Turns out that winrar does not like runnable jar files. I had tried Right Clicking the file and running it as a java application SE binary, but it would not work. So after #Adam Horvath mentioned that it worked for him I set the exported jar to default java jar and it opened up just fine.

How to get value from another Class in Java which does not contain void main?

I have three classes as follows:
-OnePa (it contains public static void main())
-New
-Choose
Under the same package.
I want to get the value of "string name" which is declared and stored in New.java
from Choose.java
package com.ash;
import javax.swing.JFrame;
public class New1 extends JFrame {
/**
*
*/
private static final long serialVersionUID = 4648531955064052430L;
private JPanel contentPane;
private JTextField textField;
private JTextField textField_1;
private JTextField textField_3;
private JFormattedTextField textField_2;
private JComboBox comboBox;
String FNm;
String LNm;
Connection con;
Choose CT11=new Choose();
//Mask-Formatter is created
protected MaskFormatter createFormatter(String s){
MaskFormatter formatter=null;
try{
formatter=new MaskFormatter(s);
}catch(java.text.ParseException exc){
System.err.println("formatter is bad:"+exc.getMessage());
System.exit(-1);
}
return formatter;
}
public New1() {
setTitle("New ");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 585, 415);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblNewLabel = new JLabel("First Name");
lblNewLabel.setFont(new Font("Times New Roman", Font.BOLD, 13));
lblNewLabel.setBounds(40, 62, 91, 28);
contentPane.add(lblNewLabel);
JLabel lblLastName = new JLabel("Last Name");
lblLastName.setFont(new Font("Times New Roman", Font.BOLD, 13));
lblLastName.setBounds(40, 101, 91, 28);
contentPane.add(lblLastName);
textField = new JTextField();
textField.setBounds(150, 66, 146, 20);
contentPane.add(textField);
textField.setColumns(10);
textField_1 = new JTextField();
textField_1.setColumns(10);
textField_1.setBounds(150, 105, 146, 20);
contentPane.add(textField_1);
JButton btnNewButton = new JButton("Next >>");
btnNewButton.setBounds(150, 289, 89, 23);
contentPane.add(btnNewButton);
ImageIcon home = new ImageIcon("D:\\Source AP\\home.jpg");
JButton HomeButton = new JButton(home);
HomeButton.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
textField.setText(null);
textField_1.setText(null);
textField_2.setText(null);
textField_3.setText(null);
dispose();
}
});
HomeButton.setBounds(26, 289, 45, 38);
contentPane.add(HomeButton);
btnNewButton.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
//Storing Values in String
GetValues();
label.setVisible(false);
label_1.setVisible(false);
label_2.setVisible(false);
label_3.setVisible(false);
lblNewLabel_1.setVisible(false);
if((FNm.length()==0 || FNm.trim().length()==0)||
(LNm.length()==0 || LNm.trim().length()==0)))
{
System.out.println("It is blank or contains white
spaces");
}
else{
System.out.println("Success");
//Connection
try {
con=DbConnPa.getConObj();
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
DbConnPa.Reg1(con, FNm, LNm, Age, RefDoc, Sex);
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
CT11.setVisible(true);
//hides the current JFrame
dispose();
}
}
});
}
public void GetValues(){
FNm=textField.getText();
LNm=textField_1.getText();
}
}
Choose.java:
package com.ash;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JCheckBox;
import javax.swing.JButton;
import java.awt.EventQueue;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.Font;
import javax.swing.JLabel;
public class Choose extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1946720589313613447L;
private JPanel contentPane;
int i=0;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Choose frame = new Choose();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Choose() {
setTitle("Choose ");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 910, 516);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton btnNewButton = new JButton("Next >>");
btnNewButton.setBounds(39, 396, 89, 23);
contentPane.add(btnNewButton);
JCheckBox checkBox = new JCheckBox("Hello");
checkBox.setFont(new Font("Times New Roman", Font.PLAIN, 13));
checkBox.setBounds(39, 120, 132, 23);
contentPane.add(checkBox);
JLabel lblFirstName = new JLabel("First Name :");
lblFirstName.setFont(new Font("Times New Roman", Font.BOLD, 13));
lblFirstName.setBounds(39, 11, 82, 16);
contentPane.add(lblFirstName);
JLabel lblLastName = new JLabel("Last Name :");
lblLastName.setFont(new Font("Times New Roman", Font.BOLD, 13));
lblLastName.setBounds(39, 34, 82, 16);
contentPane.add(lblLastName);
JLabel Ctname = new JLabel();
Ctname.setBounds(131, 12, 132, 16);
contentPane.add(Ctname);
JLabel Ctlst = new JLabel();
Ctlst.setBounds(131, 35, 132, 16);
contentPane.add(Ctlst);
contentPane.add(Ctref);
btnNewButton.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
//if Chk1 is selected it will return TRUE else FALES.
Boolean afb=checkBox.isSelected();
if(afb== true)
{
System.out.println("Is selected");
}
}
});
}
}
Create a method in Choose.java called public void setName(String name), then when you call GetValues() in New.java pass the variable FNm to Choose.java as follows: CT11.setName(FNm). Now you have passed the name to the choose class where you can store it in a global variable and do with it what you please.
Most likely from a method or constructor in Choose.java.
main() is just like any other method in java, except for one thing - at runtime, it is used by jvm to find an entry point to the application.
So if you know how to access the field from main(), you can most likely access the variable using the same approach from any other method given that the field itself or any of it's accessors is accessible.

Error with logic or repaint/revalidate Java JFrame

What I am trying to do is this,
when I enter the details it will validate if the textFiled is empty when a button is pressed, if it is empty it will display a message saying that.
Then it will move to the next textFile similar to many web based registration forms,
what I am trying to find out is why wont the message change?
Pasting this code into an ecilpse file and running it should display the simple frame and what I am trying to do.
The message displays on the bottom of the frame when the firstname field is empty,
can anyone explain why it doesn't show the next message when the firstname field containes text and the middlename contains no text?
Most of the logic is at the bottom of the code.
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Toolkit;
import javax.swing.JFrame;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.Color;
import javax.swing.UIManager;
import javax.swing.JPanel;
import com.jgoodies.forms.layout.FormLayout;
import com.jgoodies.forms.layout.ColumnSpec;
import com.jgoodies.forms.layout.RowSpec;
import com.jgoodies.forms.factories.FormFactory;
import javax.swing.JLabel;
import javax.swing.JTextField;
import java.awt.Font;
import javax.swing.SwingConstants;
import javax.swing.JRadioButton;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;
import javax.swing.JButton;
import javax.swing.JComboBox;
public class start {
private JFrame frame;
private JTextField tfFirstname;
private JTextField tfMiddlenames;
private JTextField tfSurname;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
start window = new start();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public start() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 505, 429);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
final JPanel panelClientNew = new JPanel();
panelClientNew.setBackground(new Color(0, 102, 255));
panelClientNew.setBounds(10, 11, 469, 299);
frame.getContentPane().add(panelClientNew);
panelClientNew.setLayout(null);
JLabel lblFirstname = new JLabel("Firstname :");
lblFirstname.setHorizontalAlignment(SwingConstants.RIGHT);
lblFirstname.setVerticalAlignment(SwingConstants.BOTTOM);
lblFirstname.setForeground(new Color(255, 255, 255));
lblFirstname.setFont(new Font("Tahoma", Font.BOLD, 13));
lblFirstname.setBounds(10, 16, 163, 14);
panelClientNew.add(lblFirstname);
tfFirstname = new JTextField();
tfFirstname.setFont(new Font("Tahoma", Font.PLAIN, 13));
tfFirstname.setBounds(177, 10, 282, 27);
panelClientNew.add(tfFirstname);
tfFirstname.setColumns(10);
JLabel lblMiddlenames = new JLabel("Middlenames :");
lblMiddlenames.setHorizontalAlignment(SwingConstants.RIGHT);
lblMiddlenames.setForeground(new Color(255, 255, 255));
lblMiddlenames.setFont(new Font("Tahoma", Font.BOLD, 13));
lblMiddlenames.setBounds(10, 47, 163, 14);
panelClientNew.add(lblMiddlenames);
tfMiddlenames = new JTextField();
tfMiddlenames.setFont(new Font("Tahoma", Font.PLAIN, 13));
tfMiddlenames.setBounds(177, 41, 282, 27);
panelClientNew.add(tfMiddlenames);
tfMiddlenames.setColumns(10);
JLabel lblSurname = new JLabel("Surname :");
lblSurname.setHorizontalAlignment(SwingConstants.RIGHT);
lblSurname.setForeground(new Color(255, 255, 255));
lblSurname.setFont(new Font("Tahoma", Font.BOLD, 13));
lblSurname.setBounds(10, 78, 163, 14);
panelClientNew.add(lblSurname);
tfSurname = new JTextField();
tfSurname.setFont(new Font("Tahoma", Font.PLAIN, 13));
tfSurname.setBounds(177, 72, 282, 27);
panelClientNew.add(tfSurname);
tfSurname.setColumns(10);
JButton btnAdd = new JButton("Add");
btnAdd.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent arg0) {
/*
*
*
*
*I am trying to create a message that validates on certain circumstances
*
*
*
*/
if(tfFirstname.getText().equals(null) || tfFirstname.getText().equals("") || tfFirstname.getText().equals(false)) {
JPanel panelMessage = new JPanel();
panelMessage.setBackground(new Color(30, 144, 255));
panelMessage.setBounds(10, 321, 469, 29);
frame.getContentPane().add(panelMessage);
JLabel lblPersonSaved = new JLabel("Please Enter Firstname :");
lblPersonSaved.setForeground(new Color(255, 255, 255));
lblPersonSaved.setFont(new Font("Tahoma", Font.BOLD, 15));
panelMessage.add(lblPersonSaved);
frame.revalidate();
panelMessage.revalidate();
frame.repaint();
}
else if (tfMiddlenames.getText().equals(null) || tfMiddlenames.getText().equals("") || tfMiddlenames.getText().equals(false)) {
JPanel panelMessage = new JPanel();
panelMessage.setBackground(new Color(30, 144, 255));
panelMessage.setBounds(10, 321, 469, 29);
frame.getContentPane().add(panelMessage);
JLabel lblPersonSaved = new JLabel("Please Enter Middlenames :");
lblPersonSaved.setForeground(new Color(255, 255, 255));
lblPersonSaved.setFont(new Font("Tahoma", Font.BOLD, 15));
panelMessage.add(lblPersonSaved);
frame.revalidate();
panelMessage.revalidate();
frame.repaint();
}
else if (tfSurname.getText().equals(null) || tfSurname.getText().equals("") || tfSurname.getText().equals(false)) {
JPanel panelMessage = new JPanel();
panelMessage.setBackground(new Color(30, 144, 255));
panelMessage.setBounds(10, 321, 469, 29);
frame.getContentPane().add(panelMessage);
JLabel lblPersonSaved = new JLabel("Please Enter Surname :");
lblPersonSaved.setForeground(new Color(255, 255, 255));
lblPersonSaved.setFont(new Font("Tahoma", Font.BOLD, 15));
panelMessage.add(lblPersonSaved);
frame.revalidate();
panelMessage.revalidate();
frame.repaint();
}
else {
//Validation has passed
}
}
});
btnAdd.setBounds(370, 265, 89, 23);
panelClientNew.add(btnAdd);
}
}
I recommend that you use an InputVerifier as this will verify that the contents of the JTextField are correct (any way that you wish to define this) before allowing you to even leave the JTextField. Now it won't stop you from pressing other JButtons and whatnot, so you'll need to take other precautions if you have a submit button. An example of a simple InputVerifier that checks to see if the JTextField is empty is shown below:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
#SuppressWarnings("serial")
public class InputVerifierExample extends JPanel {
public static final Color WARNING_COLOR = Color.red;
private JTextField firstNameField = new JTextField(10);
private JTextField middleNameField = new JTextField(10);
private JTextField lastNameField = new JTextField(10);
private JTextField[] nameFields = {
firstNameField,
middleNameField,
lastNameField };
private JLabel warningLabel = new JLabel(" ");
public InputVerifierExample() {
warningLabel.setOpaque(true);
JPanel namePanel = new JPanel();
namePanel.add(new JLabel("Name:"));
MyInputVerifier verifier = new MyInputVerifier();
for (JTextField field : nameFields) {
field.setInputVerifier(verifier);
namePanel.add(field);
}
namePanel.add(new JButton(new SubmitBtnAction()));
setLayout(new BorderLayout());
add(namePanel, BorderLayout.CENTER);
add(warningLabel, BorderLayout.SOUTH);
}
private class SubmitBtnAction extends AbstractAction {
public SubmitBtnAction() {
super("Submit");
}
#Override
public void actionPerformed(ActionEvent e) {
// first check all fields aren't empty
for (JTextField field : nameFields) {
if (field.getText().trim().isEmpty()) {
return; // return if empty
}
}
String name = "";
for (JTextField field : nameFields) {
name += field.getText() + " ";
field.setText("");
}
name = name.trim();
JOptionPane.showMessageDialog(InputVerifierExample.this, name, "Name Entered",
JOptionPane.INFORMATION_MESSAGE);
}
}
private class MyInputVerifier extends InputVerifier {
#Override
public boolean verify(JComponent input) {
JTextField field = (JTextField) input;
if (field.getText().trim().isEmpty()) {
warningLabel.setText("Please do not leave this field empty");
warningLabel.setBackground(WARNING_COLOR);
return false;
}
warningLabel.setText("");
warningLabel.setBackground(null);
return true;
}
}
private static void createAndShowGui() {
JFrame frame = new JFrame("InputVerifier Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new InputVerifierExample());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
have look at DocumentListener,
on start_up to enable only first JTextField, if any (up to you) character was typed into first JTextField, then enable second JTextField, and so on...,
if you want to filtering, change or replace output came from keyboard the to use DocumentFilter
change background for example to Color.red (from DocumentListeners events), in the case that one of JTextFields contains incorect lenght, data e.g.
agree with HFOE about LayoutManagers

Categories