I'm new in Java programming so that's why I'm here seeking your kind help stackoverflowers.
I have this problem which I could not find the solution on internet, I hope someone could inform me where is my mistake and how can I fix it.
My problem is that when I try to insert the data, everything goes fine, the window opens, I can insert the data, button looks just fine.
But it gives me this message
java.sql.SQLIntegrityConstraintViolationException: Column 'prenom' cannot be null
Which I assume was a problem with php mySQL, then I changed all variables to NULL, activating the button "Null" for all of them.
It then WORKED, but all informations were saved as "null" in my database, which didn't really solve my problem.
My goal is to insert data (name, lastname, phone, email) into a data base (php mySQL) through eclipse. I did a program which I'm obliged to use window builder to insert that data, so graphical user interface MUST be used
What I expect to happen is to save data normally. Like, name = Mike, lastname = Tyson, phone = +55555, email = mtyson#gmail.com
And it shows in my database, not null message.
Thank you everyone
package interfaceGraphique;
import accesBaseDeDonnees.ClientsBDD;
import entites.Clients;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.AbstractButton;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.awt.event.ActionEvent;
import javax.swing.JTextField;
import javax.swing.JLabel;
import java.awt.Color;
public class InterfaceClients extends JFrame {
static InterfaceClients window;
private JPanel contentPane;
private JTextField txtPrenom;
private JTextField txtNom;
private JTextField txtTelephone;
private JTextField txtEmail;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
InterfaceClients frame = new InterfaceClients();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public InterfaceClients() {
setBackground(new Color(0, 0, 0));
setOpacity(1.0f);
setTitle("Ajouter un client");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton btnNewButton = new JButton("Enregistrer");
btnNewButton.addActionListener(new ActionListener() {
private AbstractButton labelResult;
#Override
public void actionPerformed(ActionEvent e) {
String prenom = txtPrenom.getText();
String nom = txtNom.getText();
String telephone = txtTelephone.getText();
String email = txtEmail.getText();
Clients Clients = new Clients(prenom, nom, telephone, email);
ClientsBDD clientsBDD = new ClientsBDD();
Connection cn = clientsBDD.makeConnection();
clientsBDD.insert(Clients, cn);
clientsBDD.closeConnection(cn);
//labelResult = null;
//labelResult.setText("Client ajoute avec succes");
}
});
btnNewButton.setBounds(45, 227, 112, 23);
contentPane.add(btnNewButton);
txtPrenom = new JTextField();
txtPrenom.setBounds(124, 39, 258, 20);
contentPane.add(txtPrenom);
txtPrenom.setColumns(10);
txtNom = new JTextField();
txtNom.setColumns(10);
txtNom.setBounds(124, 82, 258, 20);
contentPane.add(txtNom);
txtTelephone = new JTextField();
txtTelephone.setColumns(10);
txtTelephone.setBounds(124, 125, 258, 20);
contentPane.add(txtTelephone);
txtEmail = new JTextField();
txtEmail.setColumns(10);
txtEmail.setBounds(124, 166, 258, 20);
contentPane.add(txtEmail);
JLabel lblNewLabel = new JLabel("Prenom");
lblNewLabel.setBounds(45, 42, 67, 14);
contentPane.add(lblNewLabel);
JLabel lblMarque = new JLabel("Nom");
lblMarque.setBounds(45, 85, 46, 14);
contentPane.add(lblMarque);
JLabel lblNewLabel_1_1 = new JLabel("Telephone");
lblNewLabel_1_1.setBounds(45, 128, 67, 14);
contentPane.add(lblNewLabel_1_1);
JLabel lblNewLabel_1_1_1 = new JLabel("Email");
lblNewLabel_1_1_1.setBounds(45, 169, 89, 14);
contentPane.add(lblNewLabel_1_1_1);
JLabel labelResult = new JLabel("");
labelResult.setBounds(194, 229, 227, 16);
contentPane.add(labelResult);
}
}
Related
I have this code and I can't get it to run. I'm new with JAVA. I was trying to make a login and registration form with JAVA swing, and I finished designing GUI part and I also connected the code with mySQL database. But I don't know why that I can't run the code. I tried debugging it, but can't find the bug. I am using eclipse and I also referenced mySQL jar.
Please let me know, if I'm doing anything wrong. Thank you for the help :)
package login_register_form;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.JOptionPane;
import javax.swing.JButton;
import java.sql.*;
import javax.swing.JComboBox;
public class RegisterPage implements ActionListener{
JFrame frame;
String[] position = {"Admin", "Manager", "Assistant"};
JTextField firstName;
JTextField lastName;
JTextField userName;
JTextField email;
JPasswordField password;
JPasswordField confirmPW;
JButton registerButton;
JButton cancelButton;
JComboBox jobPosition = new JComboBox(position);
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
RegisterPage window = new RegisterPage();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application. Calling methods from constructor
*/
public RegisterPage() {
createWindow();
initialize();
actionEvent();
}
/**
* Create a main window
*/
public void createWindow() {
frame = new JFrame();
frame.setTitle("Registration Page");
frame.getContentPane().setBackground(Color.GRAY);
frame.setBounds(100, 100, 1113, 806);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
// panel: orange colored background
JPanel panel = new JPanel();
panel.setBackground(new Color(255,165,0,200));
panel.setBounds(300, 150, 500, 472);
frame.getContentPane().add(panel);
panel.setLayout(null);
// label: scaled background
JLabel background = new JLabel("");
background.setBounds(6, 6, 1100, 772);
ImageIcon icon = new ImageIcon(this.getClass().getResource("/background.jpg"));
Image img = icon.getImage();
Image imgScale = img.getScaledInstance(background.getWidth(), background.getHeight(), Image.SCALE_SMOOTH);
ImageIcon scaledIcon = new ImageIcon(imgScale);
background.setIcon(scaledIcon);
frame.getContentPane().add(background);
// title: "Register Page"
JLabel registerPage = new JLabel("Register Page");
registerPage.setFont(new Font("Lucida Grande", Font.BOLD, 19));
registerPage.setBounds(182, 40, 135, 29);
panel.add(registerPage);
// input: first name
firstName = new JTextField();
firstName.setBounds(145, 76, 210, 32);
panel.add(firstName);
firstName.setColumns(10);
// input: last name
lastName = new JTextField();
lastName.setBounds(145, 120, 210, 32);
panel.add(lastName);
lastName.setColumns(10);
// input: user name
userName = new JTextField();
userName.setBounds(145, 164, 210, 32);
panel.add(userName);
userName.setColumns(10);
// input: password
password = new JPasswordField();
password.setBounds(145, 208, 210, 32);
panel.add(password);
// input: confirm password
confirmPW = new JPasswordField();
confirmPW.setBounds(145, 252, 210, 32);
panel.add(confirmPW);
// input: email
email = new JTextField();
email.setBounds(145, 296, 210, 32);
panel.add(email);
email.setColumns(10);
// input: position
jobPosition.setBounds(145, 340, 210, 32);
panel.add(jobPosition);
// button: cancel
JButton cancelButton = new JButton("Cancel");
cancelButton.setBounds(109, 400, 117, 40);
panel.add(cancelButton);
// button: register
JButton registerButton = new JButton("Register");
registerButton.setBounds(275, 400, 117, 40);
panel.add(registerButton);
// label: first name
JLabel fName = new JLabel("First Name");
fName.setBounds(36, 84, 85, 16);
panel.add(fName);
// label: last name
JLabel lName = new JLabel("Last Name");
lName.setBounds(36, 128, 85, 16);
panel.add(lName);
// label: user name
JLabel uName = new JLabel("User Name");
uName.setBounds(36, 172, 85, 16);
panel.add(uName);
// label: password
JLabel pWord = new JLabel("Password");
pWord.setBounds(36, 216, 85, 16);
panel.add(pWord);
// label: re-password
JLabel cPW = new JLabel("Re-Password");
cPW.setBounds(36, 260, 85, 16);
panel.add(cPW);
// label: email
JLabel eMail = new JLabel("Email");
eMail.setBounds(36, 304, 85, 16);
panel.add(eMail);
// label: position
JLabel position = new JLabel("Position");
position.setBounds(36, 347, 101, 16);
panel.add(position);
}
public void actionEvent() {
// Adding action listener to buttons
registerButton.addActionListener(this);
cancelButton.addActionListener(this);
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource()==registerButton) {
try {
//Creating Connection Object
Connection connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/myDatabase","root", "root");
//Prepared Statement
PreparedStatement Pstatement=connection.prepareStatement("insert into student value(?,?,?,?,?,?)");
// Specifying the values of it's parameter
Pstatement.setString(1, firstName.getText());
Pstatement.setString(2, lastName.getText());
Pstatement.setString(3, userName.getText());
Pstatement.setString(4, password.getText());
Pstatement.setString(5, confirmPW.getText());
Pstatement.setString(6, email.getText());
Pstatement.setString(7, jobPosition.getSelectedItem().toString());
//Checking for the password match
if (password.getText().equalsIgnoreCase(confirmPW.getText())) {
// Executing query
Pstatement.executeUpdate();
JOptionPane.showMessageDialog(null, "Data Registered Successfully");
} else {
JOptionPane.showMessageDialog(null, "Password did not match");
}
} catch (SQLException e1) {
e1.printStackTrace();
}
}
if (e.getSource()==cancelButton) {
// Clearing Fields
firstName.setText("");
lastName.setText("");
userName.setText("");
password.setText("");
confirmPW.setText("");
email.setText("");
jobPosition.setSelectedItem("Admin");
}
}
}
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.
Hi I'm trying to display an ArrayList of Objects on a Jlist. While displaying the ArrayList, I'm trying to be able to add or delete objects to the ArrayList through the GUI.
1) How can I display the ArrayList objects on the Jlist? 2)How can I delete an object by selecting it on the JList?
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.ArrayList;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JTabbedPane;
import javax.swing.ListSelectionModel;
import javax.swing.JList;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import javax.swing.DefaultListCellRenderer;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.JRadioButton;
import javax.swing.JLabel;
import java.awt.event.ActionListener;
public class DriverFrame extends JFrame implements ItemListener{
private JPanel contentPane;
private JList driverlist;
private ArrayList drivers= new ArrayList<Driver>();
JTextField textFieldFirstName;
JTextField textFieldLastName;
JTextField textFieldTruckNumber;
JTextField textFieldTrailerNumber;
private JTextField textField;
private JTextField textField_1;
private JTextField textField_2;
private JTextField textField_3;
private JTextField textField_4;
private JTextField textField_5;
private JTextField textField_6;
private JTextField textField_7;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
DriverFrame frame = new DriverFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public DriverFrame() {
Driver guy1= new Driver("Jeff","Blank","4125","1234",1400);
Driver guy2= new Driver("Marcus","Geralds","0093","1203",1800);
Driver guy3= new Driver("Steve","Wemmings","2010","2046",2100);
Driver guy4= new Driver("Kyle","Patricks","8427","5625",900);
Driver guy5= new Driver("Ficel","Metter","9124","4536",5500);
setBackground(Color.WHITE);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 500, 500);
setResizable(false);
contentPane = new JPanel();
contentPane.setBackground(Color.WHITE);
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
tabbedPane.setBackground(Color.WHITE);
tabbedPane.setBounds(5, 5, 495, 480);
contentPane.add(tabbedPane);
//Drivers TabbedPan ********
JPanel Drivers = new JPanel();
Drivers.setBackground(Color.WHITE);
tabbedPane.addTab("Drivers", null, Drivers, null);
Drivers.setLayout(null);
//List to display drivers
JList<Object> driverlist = new JList<>(drivers.toArray(new String[0]));
driverlist.setBackground(Color.WHITE);
driverlist.setVisibleRowCount(8);
driverlist.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
Drivers.add(driverlist);
driverlist.setBounds(221,6,247,234);
JTextPane txtpnFirstName = new JTextPane();
txtpnFirstName.setText("First name");
txtpnFirstName.setBounds(5, 20, 140, 15);
Drivers.add(txtpnFirstName);
txtpnFirstName.setEditable(false);
textFieldFirstName = new JTextField();
textFieldFirstName.setBounds(5, 40, 140, 30);
Drivers.add(textFieldFirstName);
textFieldFirstName.setColumns(10);
JTextPane txtpnLastName = new JTextPane();
txtpnLastName.setText("Last Name");
txtpnLastName.setBounds(5, 75, 140, 15);
Drivers.add(txtpnLastName);
txtpnLastName.setEditable(false);
textFieldLastName = new JTextField();
textFieldLastName.setBounds(5, 95, 140, 30);
Drivers.add(textFieldLastName);
textFieldLastName.setColumns(10);
JTextPane txtpnTruckNumber = new JTextPane();
txtpnTruckNumber.setText("Truck Number");
txtpnTruckNumber.setBounds(5, 130, 140, 15);
Drivers.add(txtpnTruckNumber);
txtpnTruckNumber.setEditable(false);
textFieldTruckNumber = new JTextField();
textFieldTruckNumber.setBounds(5, 150, 140, 30);
Drivers.add(textFieldTruckNumber);
textFieldTruckNumber.setColumns(10);
JTextPane txtpnTrailerNumber = new JTextPane();
txtpnTrailerNumber.setText("Trailer Number");
txtpnTrailerNumber.setBounds(5, 185, 140, 15);
Drivers.add(txtpnTrailerNumber);
txtpnTrailerNumber.setEditable(false);
textFieldTrailerNumber = new JTextField();
textFieldTrailerNumber.setBounds(5, 205, 140, 30);
Drivers.add(textFieldTrailerNumber);
textFieldTrailerNumber.setColumns(10);
JButton btnAddDriver = new JButton("Add Driver");
btnAddDriver.setBounds(5, 285, 117, 29);
Drivers.add(btnAddDriver);
JButton btnNewButton = new JButton("Delete Driver");
btnNewButton.setBounds(302, 285, 117, 29);
Drivers.add(btnNewButton);
btnAddDriver.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Driver blah = new Driver();
blah.setFirst(textFieldFirstName.getText());
blah.setLast(textFieldLastName.getText());
blah.setTnum(textFieldTruckNumber.getText());
blah.setTrailer(textFieldTrailerNumber.getText());
drivers.add(blah);
System.out.println(blah.printDriver());
System.out.println(drivers.size());
//drivers.remove(example);
}
});
//End of DriversPane******
//New Expenses Tab*****
JPanel NewExpense = new JPanel();
tabbedPane.addTab("New Expense", null, NewExpense, null);
JButton buttontest = new JButton();
NewExpense.add(buttontest);
//End of New Expense Tab****
//Income Tab****
JPanel Income = new JPanel();
Income.setBackground(Color.WHITE);
tabbedPane.addTab("Income", null, Income, null);
Income.setLayout(null);
JComboBox comboBox_3 = new JComboBox();
comboBox_3.setBounds(6, 70, 138, 27);
Income.add(comboBox_3);
JTextPane txtpnDriver_3 = new JTextPane();
txtpnDriver_3.setText("Driver:");
txtpnDriver_3.setBounds(6, 42, 42, 16);
Income.add(txtpnDriver_3);
JTextPane txtpnLoadLocationstate = new JTextPane();
txtpnLoadLocationstate.setText("Load Location(State): ");
txtpnLoadLocationstate.setBounds(6, 161, 138, 16);
Income.add(txtpnLoadLocationstate);
textField_6 = new JTextField();
textField_6.setBounds(6, 205, 130, 26);
Income.add(textField_6);
textField_6.setColumns(10);
JTextPane txtpnLoadAmount = new JTextPane();
txtpnLoadAmount.setText("Load Amount $$:");
txtpnLoadAmount.setBounds(6, 299, 108, 16);
Income.add(txtpnLoadAmount);
textField_7 = new JTextField();
textField_7.setBounds(6, 339, 130, 26);
Income.add(textField_7);
textField_7.setColumns(10);
//End of Income Tab****
//Results Tab***
JPanel Results = new JPanel();
Results.setBackground(Color.WHITE);
tabbedPane.addTab("Result", null, Results, null);
Results.setLayout(null);
JComboBox comboBox_4 = new JComboBox();
comboBox_4.setBounds(6, 69, 140, 27);
Results.add(comboBox_4);
JTextPane txtpnDriver_4 = new JTextPane();
txtpnDriver_4.setText("Driver:");
txtpnDriver_4.setBounds(6, 42, 140, 16);
Results.add(txtpnDriver_4);
JTextArea txtrHowMuchTo = new JTextArea();
txtrHowMuchTo.setText("How much to pay driver. How much are the expenses of the driver");
txtrHowMuchTo.setBounds(6, 124, 234, 304);
Results.add(txtrHowMuchTo);
JTextPane txtpnDriverInformation = new JTextPane();
txtpnDriverInformation.setText("Driver Information");
txtpnDriverInformation.setBounds(16, 108, 140, 16);
Results.add(txtpnDriverInformation);
JTextPane txtpnCompanyInfo = new JTextPane();
txtpnCompanyInfo.setText("Company Info:");
txtpnCompanyInfo.setBounds(414, 80, 178, 16);
Results.add(txtpnCompanyInfo);
JTextArea txtrIncome = new JTextArea();
txtrIncome.setText("Income Expenses");
txtrIncome.setBounds(390, 124, 294, 304);
Results.add(txtrIncome);
//End of Results Tab****
}
#Override
public void itemStateChanged(ItemEvent e) {
// TODO Auto-generated method stub
}
}
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
This is kinda a silly question, but I'm beggining with java swing and have been doing kinda great, but I really can't make a JTable appear in my form, so far a blank square appears but no columns at all, here's a snippet:
DefaultTableModel modelo = new DefaultTableModel();
modelo.setColumnCount(1);
tblTrans = new JTable(modelo);
modelo.addColumn("Prueba");
tblTrans.revalidate();
tblTrans.setBounds(316, 47, 248, 243);
contentPane.add(tblTrans);
Here's the complete code in case you need it:
package mx.adk.grafos;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.DefaultListModel;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.ListSelectionModel;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JList;
import javax.swing.JTable;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Set;
import java.util.TreeSet;
public class GUI extends JFrame implements ActionListener {
private JPanel contentPane;
private JTextField txtEstados;
private JTextField txtLenguaje;
private JTextField txtFinal;
private JTable tblTrans;
private JList lstEstados;
private JList lstLenguaje;
DefaultListModel listaEstados;
TreeSet<String> setEstados = new TreeSet<String>();
DefaultListModel listaLenguaje;
TreeSet<Character> setLenguaje = new TreeSet<Character>();
/*
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
GUI frame = new GUI();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
*/
public void actionPerformed(ActionEvent e) {
String comando = e.getActionCommand();
if(comando.equalsIgnoreCase("btnAEstados")){
String tmp = txtEstados.getText();
if(setEstados.add(tmp)){
listaEstados.addElement(tmp);
}
return;
}
if(comando.equalsIgnoreCase("btneestados")){
String tmp = (String) lstEstados.getSelectedValue();
setEstados.remove(tmp);
listaEstados.removeElement(tmp);
}
if(comando.equalsIgnoreCase("btnALenguaje")){
char tmp = txtLenguaje.getText().charAt(0);
if(setLenguaje.add(tmp)){
listaLenguaje.addElement(tmp);
}
return;
}
if(comando.equalsIgnoreCase("btnelenguaje")){
char tmp = (char) lstLenguaje.getSelectedValue().toString().charAt(0);
setLenguaje.remove(tmp);
listaLenguaje.removeElement(tmp);
}
}
public GUI() {
setTitle("Automata finito no deterministico");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 599, 368);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
txtEstados = new JTextField();
txtEstados.setBounds(26, 82, 72, 28);
contentPane.add(txtEstados);
txtEstados.setColumns(10);
JButton btnAEstados = new JButton(">>");
btnAEstados.setBounds(103, 69, 51, 29);
contentPane.add(btnAEstados);
btnAEstados.addActionListener(this);
btnAEstados.setActionCommand("btnAEstados");
listaEstados = new DefaultListModel();
lstEstados = new JList(listaEstados);
lstEstados.setBounds(154, 46, 105, 109);
contentPane.add(lstEstados);
lstEstados.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
JLabel lblEstados = new JLabel("Estados");
lblEstados.setBounds(83, 19, 59, 16);
contentPane.add(lblEstados);
JButton btnEEstados = new JButton("<<");
btnEEstados.setBounds(103, 96, 51, 29);
contentPane.add(btnEEstados);
btnEEstados.addActionListener(this);
btnEEstados.setActionCommand("btnEEstados");
JButton btnELenguaje = new JButton("<<");
btnELenguaje.setBounds(103, 231, 51, 29);
contentPane.add(btnELenguaje);
btnELenguaje.addActionListener(this);
btnELenguaje.setActionCommand("btnELenguaje");
JButton btnALenguaje = new JButton(">>");
btnALenguaje.setBounds(103, 204, 51, 29);
contentPane.add(btnALenguaje);
btnALenguaje.addActionListener(this);
btnALenguaje.setActionCommand("btnALenguaje");
txtLenguaje = new JTextField();
txtLenguaje.setColumns(10);
txtLenguaje.setBounds(26, 217, 72, 28);
contentPane.add(txtLenguaje);
listaLenguaje = new DefaultListModel();
lstLenguaje = new JList(listaLenguaje);
lstLenguaje.setBounds(154, 181, 105, 109);
contentPane.add(lstLenguaje);
lstLenguaje.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
JLabel lblLenguaje = new JLabel("Lenguaje");
lblLenguaje.setBounds(95, 161, 59, 16);
contentPane.add(lblLenguaje);
txtFinal = new JTextField();
txtFinal.setText("QFinal");
txtFinal.setColumns(10);
txtFinal.setBounds(26, 298, 72, 28);
contentPane.add(txtFinal);
DefaultTableModel modelo = new DefaultTableModel();
modelo.setColumnCount(1);
tblTrans = new JTable(modelo);
modelo.addColumn("Prueba");
tblTrans.revalidate();
tblTrans.setBounds(316, 47, 248, 243);
contentPane.add(tblTrans);
JLabel lblTransiciones = new JLabel("Transiciones");
lblTransiciones.setBounds(394, 19, 89, 16);
contentPane.add(lblTransiciones);
JButton btnAceptar = new JButton("Aceptar");
btnAceptar.setBounds(476, 311, 117, 29);
contentPane.add(btnAceptar);
btnAceptar.addActionListener(this);
btnAceptar.setActionCommand("btnAceptar");
}
}
What I want to accomplish is to add a column for each "Estado" given, the program is about non deterministic automata, and a row for each "Lenguaje" given so I can make the transition matrix, I do know how to make this each time the buttons are pressed, but it appears like the column is being added but it's not visible at all, just a blank square.
Corrections suggested:
DefaultTableModel modelo = new DefaultTableModel();
modelo.setColumnCount(1);
tblTrans = new JTable(modelo);
panel.add(tblTrans);
panel.setBounds(316, 47, 248, 243);
modelo.addColumn("Test");
tblTrans.revalidate();
contentPane.add(panel);
I was right about the scroll pane. This is working for me:
DefaultTableModel modelo = new DefaultTableModel();
modelo.setColumnCount(1);
modelo.addColumn("Prueba");
tblTrans = new JTable(modelo);
JScrollPane sPane = new JScrollPane(tblTrans);
sPane.setBounds(316, 47, 248, 243);
contentPane.add(sPane);