This question already exists:
JTextarea gives out weird text [closed]
Closed 29 days ago.
Hey I’m working on a Selling class of a simple Java Swing GUI supermarket project. When I add the first item to the billingtxt, it lists them normally as if there is nothing wrong! But if I add more items, it will bring out weird text as shown in the image.
First item works just fine but second will bring weird text
This is the text Im talking about:
My code is shared underneath. Any help would be greatly appreciated! Thanks in advance:)
package supermarket1;
import java.awt.Color;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import net.proteanit.sql.DbUtils;
/**
*
* #author patrickschnepf
*/
public class Selling1 extends javax.swing.JFrame {
/**
* Creates new form Selling1
*/
public Selling1() {
initComponents();
SelectSeller();
}
Connection Con = null;
Statement St = null;
ResultSet Rs = null;
public void SelectSeller()
{
try {
Con = DriverManager.getConnection("jdbc:derby://localhost:1527/SuperMarketdb1","User1","1234");
St = Con.createStatement();
Rs = St.executeQuery("Select * from User1.PRODUCTTBL");
ProductTable.setModel(DbUtils.resultSetToTableModel(Rs));
} catch (Exception e) {
e.printStackTrace();
}
}
int PrId, newQty;
public void update()
{
newQty = AvailQty - Integer.valueOf(ProdQty.getText());
try{
Con = DriverManager.getConnection("jdbc:derby://localhost:1527/SuperMarketdb1","User1","1234");
String Query ="Update User1.PRODUCTTBL set PRODQUANTITY="+newQty+""+" where PRODID="+PrId;
Statement Add = Con.createStatement();
Add.executeUpdate(Query);
SelectSeller();
}catch(SQLException e){
e.printStackTrace();
}
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jLabel8 = new javax.swing.JLabel();
jPanel2 = new javax.swing.JPanel();
jScrollPane1 = new javax.swing.JScrollPane();
ProductTable = new javax.swing.JTable();
jLabel9 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jScrollPane2 = new javax.swing.JScrollPane();
BillTxt = new javax.swing.JTextArea();
AddBtn = new javax.swing.JButton();
jLabel4 = new javax.swing.JLabel();
ProdName = new javax.swing.JTextField();
jLabel5 = new javax.swing.JLabel();
ProdQty = new javax.swing.JTextField();
ClearBtn = new javax.swing.JButton();
EditBtn = new javax.swing.JButton();
SummeLbl = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
jLabel1 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel1.setBackground(new java.awt.Color(0, 153, 0));
jLabel8.setFont(new java.awt.Font("Arial Black", 1, 20)); // NOI18N
jLabel8.setForeground(new java.awt.Color(255, 255, 255));
jLabel8.setText("X");
jLabel8.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel8MouseClicked(evt);
}
public void mouseEntered(java.awt.event.MouseEvent evt) {
jLabel8MouseEntered(evt);
}
});
jPanel2.setBackground(new java.awt.Color(255, 255, 255));
ProductTable.setAutoCreateRowSorter(true);
ProductTable.setFont(new java.awt.Font("Arial Black", 1, 12)); // NOI18N
ProductTable.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"ProdID", "Name", "Menge", "Preis", "Kategorie"
}
));
ProductTable.setRowHeight(25);
ProductTable.setSelectionBackground(new java.awt.Color(255, 102, 0));
ProductTable.setSelectionForeground(new java.awt.Color(255, 255, 255));
ProductTable.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
ProductTableMouseClicked(evt);
}
});
jScrollPane1.setViewportView(ProductTable);
jLabel9.setFont(new java.awt.Font("Arial Black", 1, 14)); // NOI18N
jLabel9.setForeground(new java.awt.Color(255, 102, 0));
jLabel9.setText("Wählen sie die zu Verkaufende Produkte aus:");
jLabel3.setFont(new java.awt.Font("Arial Black", 1, 20)); // NOI18N
jLabel3.setForeground(new java.awt.Color(255, 102, 0));
jLabel3.setText("Produkt Liste");
BillTxt.setColumns(20);
BillTxt.setFont(new java.awt.Font("Arial Black", 0, 14)); // NOI18N
BillTxt.setRows(5);
jScrollPane2.setViewportView(BillTxt);
AddBtn.setFont(new java.awt.Font("Arial Black", 1, 12)); // NOI18N
AddBtn.setForeground(new java.awt.Color(255, 102, 0));
AddBtn.setText("Zur Rechnung hinzufügen");
AddBtn.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
AddBtnMouseClicked(evt);
}
});
jLabel4.setFont(new java.awt.Font("Arial Black", 1, 14)); // NOI18N
jLabel4.setForeground(new java.awt.Color(255, 102, 0));
jLabel4.setText("Name:");
ProdName.setFont(new java.awt.Font("Arial Black", 1, 12)); // NOI18N
ProdName.setForeground(new java.awt.Color(255, 102, 0));
jLabel5.setFont(new java.awt.Font("Arial Black", 1, 14)); // NOI18N
jLabel5.setForeground(new java.awt.Color(255, 102, 0));
jLabel5.setText("Menge:");
ProdQty.setFont(new java.awt.Font("Arial Black", 1, 12)); // NOI18N
ProdQty.setForeground(new java.awt.Color(255, 102, 0));
ClearBtn.setFont(new java.awt.Font("Arial Black", 1, 12)); // NOI18N
ClearBtn.setForeground(new java.awt.Color(255, 102, 0));
ClearBtn.setText("Zurücksetzen");
ClearBtn.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
ClearBtnMouseClicked(evt);
}
});
ClearBtn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ClearBtnActionPerformed(evt);
}
});
EditBtn.setFont(new java.awt.Font("Arial Black", 1, 12)); // NOI18N
EditBtn.setForeground(new java.awt.Color(255, 102, 0));
EditBtn.setText("Drucken");
EditBtn.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
EditBtnMouseClicked(evt);
}
});
SummeLbl.setFont(new java.awt.Font("Arial Black", 1, 14)); // NOI18N
SummeLbl.setForeground(new java.awt.Color(255, 102, 0));
SummeLbl.setText("Summe: ");
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(244, 244, 244)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel5)
.addComponent(jLabel4))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(ProdQty, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(ProdName, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(150, 150, 150)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 396, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 38, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
.addComponent(jLabel9)
.addGap(68, 68, 68))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
.addComponent(AddBtn)
.addGap(150, 150, 150)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(jLabel3)
.addGap(151, 151, 151))
.addGroup(jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 396, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
.addComponent(SummeLbl)
.addGap(159, 159, 159)))
.addGap(38, 38, 38))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel2Layout.createSequentialGroup()
.addGap(85, 85, 85)
.addComponent(EditBtn)
.addGap(63, 63, 63)
.addComponent(ClearBtn)
.addContainerGap())))))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(19, 19, 19)
.addComponent(jLabel3)
.addGap(18, 18, 18)
.addComponent(jLabel9)
.addGap(15, 15, 15)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(ProdName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel4))
.addGap(18, 18, 18)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(ProdQty, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel5))))
.addGap(17, 17, 17)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 178, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(AddBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(SummeLbl)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(EditBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(ClearBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)))
);
jLabel7.setFont(new java.awt.Font("Arial Black", 1, 20)); // NOI18N
jLabel7.setForeground(new java.awt.Color(255, 255, 255));
jLabel7.setText("Logout");
jLabel7.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel7MouseClicked(evt);
}
});
jLabel1.setFont(new java.awt.Font("Arial Black", 1, 20)); // NOI18N
jLabel1.setForeground(new java.awt.Color(255, 255, 255));
jLabel1.setText("Kasse");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel1)
.addGap(342, 342, 342)
.addComponent(jLabel8)
.addContainerGap())
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(26, 26, 26)
.addComponent(jLabel7)
.addGap(18, 18, 18)
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel7)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel8)
.addComponent(jLabel1))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(22, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
pack();
}// </editor-fold>
Double Uprice, ProdTot=0.0,GrdTot=0.0;
int AvailQty;
private void ProductTableMouseClicked(java.awt.event.MouseEvent evt) {
DefaultTableModel model = (DefaultTableModel)ProductTable.getModel();
int MyIndex = ProductTable.getSelectedRow();
PrId = Integer.valueOf(model.getValueAt(MyIndex, 0).toString());
AvailQty = Integer.valueOf(model.getValueAt(MyIndex, 2).toString());
ProdName.setText(model.getValueAt(MyIndex, 1).toString());
Uprice = Double.valueOf(model.getValueAt(MyIndex, 3).toString());
}
int i = 0;
private void AddBtnMouseClicked(java.awt.event.MouseEvent evt) {
if(ProdQty.getText().isEmpty() || ProdName.getText().isEmpty() )
{
JOptionPane.showMessageDialog(this, "Fehlende Informationen");
}
else if(AvailQty <= Integer.valueOf(ProdQty.getText()))
{
JOptionPane.showMessageDialog(this, "Nicht genug auf Lager");
}
else{
i++;
ProdTot = Uprice * Double.valueOf(ProdQty.getText());
GrdTot = GrdTot+ProdTot;
if( i == 1)
{
BillTxt.setText(BillTxt.getText()+"============Tante Emma Laden============\n"+"Nummer Produkt Preis Menge Summe\n"+i+" "+ProdName.getText()+" "+Uprice+" "+ProdQty.getText()+" "+ProdTot+"\n\t");
}else
{
BillTxt.setText(BillTxt.getText()+" "+i+" "+ProdName+" "+Uprice+" "+ProdQty.getText()+" "+ProdTot+"\n");
}
SummeLbl.setText("Zu zahlen: "+GrdTot + " €");
update();
}
}
private void ClearBtnMouseClicked(java.awt.event.MouseEvent evt) {
ProdName.setText("");
BillTxt.setText("");
ProdQty.setText("");
SummeLbl.setText("Summe: ");
}
private void ClearBtnActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void EditBtnMouseClicked(java.awt.event.MouseEvent evt) {
try{
BillTxt.print();
}catch (Exception e)
{
}
}
private void jLabel8MouseClicked(java.awt.event.MouseEvent evt) {
System.exit(0);
}
private void jLabel8MouseEntered(java.awt.event.MouseEvent evt) {
jLabel8.setForeground(Color.red);
}
private void jLabel7MouseClicked(java.awt.event.MouseEvent evt) {
new Login().setVisible(true);
this.dispose();
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Selling1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Selling1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Selling1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Selling1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Selling1().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton AddBtn;
private javax.swing.JTextArea BillTxt;
private javax.swing.JButton ClearBtn;
private javax.swing.JButton EditBtn;
private javax.swing.JTextField ProdName;
private javax.swing.JTextField ProdQty;
private javax.swing.JTable ProductTable;
private javax.swing.JLabel SummeLbl;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
// End of variables declaration
}
Ive tried looking for errors but there were non and
You have an object named ProdName that is lying; it's not a name at all, it's a JTextField object. It isn't text, it's a field that can contain text. That field should be named prodNameField for some example (in java we writeVariableNamesLikeThis and TypesLikeThis. You're signing yourself up for a life of annoyance if you don't adjust your style, all java code is written like that).
In your code you have this line:
BillTxt.setText(BillTxt.getText()+" "+i+" "+ProdName+" "+Uprice+" "+ProdQty.getText()+" "+ProdTot+"\n");
This calls toString() on ProdName and concatenates that to the rest of the strings in this statement. The toString of a JTextField is the 'strange text' you see. You want to [A] make that ProdName.getText(), and [B] you want to adjust all your variable names because the problem with them is that they are confusing, and this question proves that it has confused you. prodQtyField, prodNameField, etcetera.
Related
Hi at the moment I can't log in to MySQL database with SQL statement and open next MenuForm. Not sure what's wrong with it. There is no error. I have added additional if "//if(password.contains("123") && username.contains("test")) {" to check if it works and it does work but still can't compare it with MySQL.
private void jButton_LoginActionPerformed(java.awt.event.ActionEvent evt) {
PreparedStatement st;
ResultSet rs;
// get the username & password
String username = jTextField_Username.getText();
String password = String.valueOf(jPasswordField.getPassword());
//create a select query to check if the username and the password exist in the database
String query = "SELECT * FROM users_db.users WHERE 'username' = ? and 'password' = ?";
try {
st = My_CNX.getConnection().prepareStatement(query);
st.setString(1, username);
st.setString(2, password);
rs = st.executeQuery();
//if(password.contains("123") && username.contains("test")) {
if(rs.next()){
// show a new form
MenuForm form = new MenuForm();
form.setVisible(true);
form.pack(); // rozmiarem ma się zająć automatycznie manager rozmiaru? druga opcja to ustalenie romziaru x i y, za pomocą innej funkcji
form.setLocationRelativeTo(null);
//close the current form(login form)
form.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.dispose();
}else{
// error message
JOptionPane.showMessageDialog(null, "Invalid Username or Password", "Login Error",2);
}
} catch (SQLException ex) {
Logger.getLogger(Login_Form.class.getName()).log(Level.SEVERE, null, ex);
}
}
I have added whole code here.
I have included the whole login Form below.
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Login_register_design;
import java.awt.Color;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.swing.border.Border;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
/**
*
* #author tomas
*/
public class Login_Form extends javax.swing.JFrame {
/**
* Creates new form Login_Form
*/
public Login_Form() {
initComponents();
/* - Downalod The Connector For Java & MySQL database*/
/* Link -> https://dev.mysql.com/downloads/connector/j/ */
/* OPEN */
/*Create a connection with the database */
// Center the form
this.setLocationRelativeTo(null);
// create a yellow border for the panel_title
// 0 border in the top
Border jpanel_title_border = BorderFactory.createMatteBorder(1, 1, 1, 1, Color.blue);
// set the border to the jpanel_title
jPanel_title.setBorder(jpanel_title_border);
// create a orange border for the global panel
Border global_panel_border = BorderFactory.createMatteBorder(1, 1, 1, 1, Color.orange);
jPanel5.setBorder(global_panel_border);
// create a black border for the close & minimize jlables
Border label_border = BorderFactory.createMatteBorder(1, 1, 1, 1, Color.black);
jLabel_minimize.setBorder(label_border);
jLabel_close.setBorder(label_border);
// create border for the username and password field
Border field_border = BorderFactory.createMatteBorder(1, 5, 1, 1, Color.white);
jTextField_Username.setBorder(field_border);
jPasswordField.setBorder(field_border);
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jPanel5 = new javax.swing.JPanel();
jPanel2 = new javax.swing.JPanel();
jPanel4 = new javax.swing.JPanel();
jLabel_username = new javax.swing.JLabel();
jLabel_password = new javax.swing.JLabel();
jTextField_Username = new javax.swing.JTextField();
jPasswordField = new javax.swing.JPasswordField();
jButton_Login = new javax.swing.JButton();
jPanel3 = new javax.swing.JPanel();
jLabel_minimize = new javax.swing.JLabel();
jLabel_close = new javax.swing.JLabel();
jPanel_title = new javax.swing.JPanel();
jLabel3 = new javax.swing.JLabel();
jPanel1.setForeground(new java.awt.Color(0, 255, 153));
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 462, Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 330, Short.MAX_VALUE)
);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setUndecorated(true);
jPanel2.setBackground(new java.awt.Color(0, 204, 204));
jLabel_username.setIcon(new javax.swing.ImageIcon(getClass().getResource("/grafika/Loginemail-100px.png"))); // NOI18N
jLabel_password.setIcon(new javax.swing.ImageIcon(getClass().getResource("/grafika/Hasło-100px.png"))); // NOI18N
jTextField_Username.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jTextField_Username.setForeground(new java.awt.Color(153, 153, 153));
jTextField_Username.setText("username");
jTextField_Username.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
jTextField_UsernameFocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
jTextField_UsernameFocusLost(evt);
}
});
jTextField_Username.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField_UsernameActionPerformed(evt);
}
});
jPasswordField.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jPasswordField.setForeground(new java.awt.Color(153, 153, 153));
jPasswordField.setText("password");
jPasswordField.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
jPasswordFieldFocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
jPasswordFieldFocusLost(evt);
}
});
jButton_Login.setBackground(new java.awt.Color(0, 84, 140));
jButton_Login.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); // NOI18N
jButton_Login.setForeground(new java.awt.Color(255, 255, 255));
jButton_Login.setText("Login");
jButton_Login.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
jButton_Login.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseEntered(java.awt.event.MouseEvent evt) {
jButton_LoginMouseEntered(evt);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
jButton_LoginMouseExited(evt);
}
});
jButton_Login.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_LoginActionPerformed(evt);
}
});
jPanel3.setBackground(new java.awt.Color(0, 153, 153));
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 0, Short.MAX_VALUE)
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 0, Short.MAX_VALUE)
);
javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
jPanel4.setLayout(jPanel4Layout);
jPanel4Layout.setHorizontalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addGap(24, 24, 24)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jButton_Login, javax.swing.GroupLayout.PREFERRED_SIZE, 382, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel4Layout.createSequentialGroup()
.addComponent(jLabel_password)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPasswordField, javax.swing.GroupLayout.PREFERRED_SIZE, 278, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel4Layout.createSequentialGroup()
.addComponent(jLabel_username)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextField_Username, javax.swing.GroupLayout.PREFERRED_SIZE, 279, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(24, Short.MAX_VALUE))
.addGroup(jPanel4Layout.createSequentialGroup()
.addGap(174, 174, 174)
.addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
jPanel4Layout.setVerticalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addGap(45, 45, 45)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jTextField_Username)
.addComponent(jLabel_username, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel_password, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPasswordField))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton_Login, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(53, Short.MAX_VALUE))
);
// set icon to the jlabel
// set icon to the jlabel
jLabel_minimize.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
jLabel_minimize.setText("-");
jLabel_minimize.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
jLabel_minimize.setPreferredSize(new java.awt.Dimension(17, 29));
jLabel_minimize.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel_minimizeMouseClicked(evt);
}
public void mouseEntered(java.awt.event.MouseEvent evt) {
jLabel_minimizeMouseEntered(evt);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
jLabel_minimizeMouseExited(evt);
}
});
jLabel_close.setFont(new java.awt.Font("Arial", 1, 18)); // NOI18N
jLabel_close.setText("X");
jLabel_close.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
jLabel_close.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel_closeMouseClicked(evt);
}
public void mouseEntered(java.awt.event.MouseEvent evt) {
jLabel_closeMouseEntered(evt);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
jLabel_closeMouseExited(evt);
}
});
jPanel_title.setBackground(new java.awt.Color(51, 153, 255));
jLabel3.setBackground(new java.awt.Color(51, 153, 255));
jLabel3.setFont(new java.awt.Font("Arial", 1, 48)); // NOI18N
jLabel3.setForeground(new java.awt.Color(255, 255, 255));
jLabel3.setText("Login");
javax.swing.GroupLayout jPanel_titleLayout = new javax.swing.GroupLayout(jPanel_title);
jPanel_title.setLayout(jPanel_titleLayout);
jPanel_titleLayout.setHorizontalGroup(
jPanel_titleLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel_titleLayout.createSequentialGroup()
.addGap(40, 40, 40)
.addComponent(jLabel3)
.addContainerGap(42, Short.MAX_VALUE))
);
jPanel_titleLayout.setVerticalGroup(
jPanel_titleLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel_titleLayout.createSequentialGroup()
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 52, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 10, Short.MAX_VALUE))
);
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(118, 118, 118)
.addComponent(jPanel_title, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(57, 57, 57)
.addComponent(jLabel_minimize, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel_close))
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(14, Short.MAX_VALUE))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(11, 11, 11)
.addComponent(jPanel_title, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(18, 18, 18)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel_close)
.addComponent(jLabel_minimize, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 31, Short.MAX_VALUE)
.addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
jPanel5.setLayout(jPanel5Layout);
jPanel5Layout.setHorizontalGroup(
jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel5Layout.createSequentialGroup()
.addGap(22, 22, 22)
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(23, Short.MAX_VALUE))
);
jPanel5Layout.setVerticalGroup(
jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel5Layout.createSequentialGroup()
.addGap(20, 20, 20)
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(19, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
pack();
}// </editor-fold>
private void jLabel_minimizeMouseEntered(java.awt.event.MouseEvent evt) {
Border label_border = BorderFactory.createMatteBorder(1, 1, 1, 1, Color.white);
jLabel_minimize.setBorder(label_border);
jLabel_minimize.setForeground(Color.white);
}
private void jLabel_minimizeMouseExited(java.awt.event.MouseEvent evt) {
Border label_border = BorderFactory.createMatteBorder(1, 1, 1, 1, Color.black);
jLabel_minimize.setBorder(label_border);
jLabel_minimize.setForeground(Color.black);
}
private void jLabel_closeMouseEntered(java.awt.event.MouseEvent evt) {
Border label_border = BorderFactory.createMatteBorder(1, 1, 1, 1, Color.white);
jLabel_close.setBorder(label_border);
jLabel_close.setForeground(Color.white);
}
private void jLabel_closeMouseExited(java.awt.event.MouseEvent evt) {
Border label_border = BorderFactory.createMatteBorder(1, 1, 1, 1, Color.black);
jLabel_close.setBorder(label_border);
jLabel_close.setForeground(Color.black);
}
private void jTextField_UsernameFocusGained(java.awt.event.FocusEvent evt) {
// clear the testfield on focus if the text is "username"
if(jTextField_Username.getText().trim().toLowerCase().equals("username"));
{
jTextField_Username.setText("");
jTextField_Username.setForeground(Color.black);
}
Border jpanel_icon = BorderFactory.createMatteBorder(1, 1, 1, 1, Color.blue);
jLabel_username.setBorder(jpanel_icon);
}
private void jTextField_UsernameFocusLost(java.awt.event.FocusEvent evt) {
// if the text field is equal to username or empty
// we will set the "username" text in the field on
// on focus lost event
if(jTextField_Username.getText().trim().equals("") ||
jTextField_Username.getText().trim().toLowerCase().equals("username"))
{
jTextField_Username.setText("username");
jTextField_Username.setForeground(new Color(153,153,153));
}
// create a border with the color of the parent jpanel for the icons label to remove the move
Border label_icons_border = BorderFactory.createMatteBorder(1, 1, 1, 1, new Color(153,153,153));
jLabel_username.setBorder(label_icons_border);
}
private void jPasswordFieldFocusGained(java.awt.event.FocusEvent evt) {
// clear the password on focus if the text is "password"
// get the password text
String pass = String.valueOf(jPasswordField.getPassword());
if(pass.trim().toLowerCase().equals("password"));
{
jPasswordField.setText("");
jPasswordField.setForeground(Color.black);
}
// set a yellow border to the jlabel icon
Border jpanel_icon = BorderFactory.createMatteBorder(1, 1, 1, 1, Color.blue);
// set the border to the jpanel_title
jLabel_password.setBorder(jpanel_icon);
}
private void jPasswordFieldFocusLost(java.awt.event.FocusEvent evt) {
// get the password text
String pass = String.valueOf(jPasswordField.getPassword());
if(pass.trim().equals("") ||
pass.trim().toLowerCase().equals("password"))
{
jPasswordField.setText("password");
jPasswordField.setForeground(new Color(153,153,153));
}
// create a border with the color of the parent jpanel for the icons label to remove the move
Border label_icons_border = BorderFactory.createMatteBorder(1, 1, 1, 1, new Color(153,153,153));
jLabel_password.setBorder(label_icons_border);
}
private void jButton_LoginActionPerformed(java.awt.event.ActionEvent evt) {
PreparedStatement st;
ResultSet rs;
// get the username & password
String username = jTextField_Username.getText();
String password = String.valueOf(jPasswordField.getPassword());
//create a select query to check if the username and the password exist in the database
String query = "SELECT * FROM users_db.users WHERE 'username' = ? and 'password' = ?";
try {
st = My_CNX.getConnection().prepareStatement(query);
st.setString(1, username);
st.setString(2, password);
rs = st.executeQuery();
//if(password.contains("123") && username.contains("test")) {
if(rs.next()){
// show a new form
MenuForm form = new MenuForm();
form.setVisible(true);
form.pack(); // rozmiarem ma się zająć automatycznie manager rozmiaru? druga opcja to ustalenie romziaru x i y, za pomocą innej funkcji
form.setLocationRelativeTo(null);
//close the current form(login form)
form.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.dispose();
}else{
// error message
JOptionPane.showMessageDialog(null, "Invalid Username or Password", "Login Error",2);
}
} catch (SQLException ex) {
Logger.getLogger(Login_Form.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void jButton_LoginMouseEntered(java.awt.event.MouseEvent evt) {
//set jbutton backbround
jButton_Login.setBackground(new Color(0, 101, 183));
}
private void jButton_LoginMouseExited(java.awt.event.MouseEvent evt) {
//set jbutton backbround
jButton_Login.setBackground(new Color(0, 84, 104));
}
private void jLabel_minimizeMouseClicked(java.awt.event.MouseEvent evt) {
this.setState(JFrame.ICONIFIED);
}
private void jLabel_closeMouseClicked(java.awt.event.MouseEvent evt) {
System.exit(0);
}
private void jTextField_UsernameActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Login_Form.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Login_Form.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Login_Form.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Login_Form.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Login_Form().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton_Login;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel_close;
private javax.swing.JLabel jLabel_minimize;
private javax.swing.JLabel jLabel_password;
private javax.swing.JLabel jLabel_username;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPanel4;
private javax.swing.JPanel jPanel5;
private javax.swing.JPanel jPanel_title;
private javax.swing.JPasswordField jPasswordField;
private javax.swing.JTextField jTextField_Username;
// End of variables declaration
}
Replace
"SELECT * FROM users_db.users WHERE 'username' = ? and 'password' = ?"
with
"SELECT * FROM users_db.users WHERE username = ? AND password = ?"
Note that I have removed single quotes enclosing fields.
I am making a movie ticket management system. And for that, I want to generate a PDF. But the PDF is not making properly. When I set the visibility of my jframe true, I see that my jframe is updated properly. But when i generate PDF from that , it does not show me the updated value. It show me the default value in my PDF. How can I solve this?
Here I cannot show you all my code because of the limit of words in a post. In UserHistoryPanel.java, I want that when I pressed jButton1, PrintTicket jframe should be printed.
Here is my code:
UserHistoryPanel.java
package paneles;
import cambodia.raven.DateChooser;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
public class UserHistoryPanel extends javax.swing.JPanel {
String UserName, theatreName, theatreAddress;
Integer UserId;
/**
* Creates new form UserHistoryPanel
*/
public UserHistoryPanel() {
initComponents();
}
public UserHistoryPanel(String userName) {
initComponents();
UserName = userName;
DefaultTableModel model = (DefaultTableModel)HistoryTable.getModel();
model.setRowCount(0);
show_history();
jTextField1.setText("");
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
int i = HistoryTable.getSelectedRow();
TableModel model = HistoryTable.getModel();
String OrderId = model.getValueAt(i, 0).toString();
String movieName = model.getValueAt(i, 3).toString();
theatreName = model.getValueAt(i, 4).toString();
String hall = model.getValueAt(i, 5).toString();
String date = model.getValueAt(i, 1).toString();
String time = model.getValueAt(i, 2).toString();
find_theatreDeatils();
new PrintTicket(OrderId,UserName, movieName, theatreName, hall, theatreAddress, date, time).setVisible(true);
PrinterJob job = PrinterJob.getPrinterJob();
job.setJobName("Cineplex Management System");
job.setPrintable(new Printable(){
public int print(Graphics pg,PageFormat pf, int pageNum){
pf.setOrientation(PageFormat.LANDSCAPE);
if(pageNum>0){
return Printable.NO_SUCH_PAGE;
}
Graphics2D g2 = (Graphics2D)pg;
g2.translate(pf.getImageableX(), pf.getImageableY());
g2.scale(1,1.1);
JPanel jPanel1 = new PrintTicket().getjPanel1();
jPanel1.paint(g2);
return Printable.PAGE_EXISTS;
}
});
boolean ok = job.printDialog();
if(ok){
try{
job.print();
}
catch (PrinterException ex){
}
}
}
// Variables declaration - do not modify
private javax.swing.JTable HistoryTable;
private cambodia.raven.DateChooser dateChooser1;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton3;
private javax.swing.JButton jButton5;
private javax.swing.JButton jButton6;
private javax.swing.JLabel jLabel7;
private javax.swing.JPanel jPanel2;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JSeparator jSeparator3;
private javax.swing.JTextField jTextField1;
// End of variables declaration
}
PrintTicket.java
package paneles;
import javax.swing.JPanel;
public class PrintTicket extends javax.swing.JFrame {
/**
* Creates new form PrintTicket
*/
public PrintTicket() {
initComponents();
}
public PrintTicket(String OrderId,String UserName, String Movie, String Theatre, String Hall, String TheatreAddress, String Date, String Time) {
initComponents();
orderId.setText(OrderId);
userName.setText(UserName);
movie.setText(Movie);
theatre.setText(Theatre);
hall.setText(Hall);
theatreAddress.setText(TheatreAddress);
date.setText(Date);
time.setText(Time);
}
public JPanel getjPanel1() {
return jPanel1;
}
public void setjPanel1(JPanel jPanel1) {
this.jPanel1 = jPanel1;
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
jLabel8 = new javax.swing.JLabel();
jLabel9 = new javax.swing.JLabel();
jLabel10 = new javax.swing.JLabel();
jLabel11 = new javax.swing.JLabel();
date = new javax.swing.JLabel();
orderId = new javax.swing.JLabel();
userName = new javax.swing.JLabel();
movie = new javax.swing.JLabel();
theatre = new javax.swing.JLabel();
hall = new javax.swing.JLabel();
theatreAddress = new javax.swing.JLabel();
time = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setMinimumSize(new java.awt.Dimension(654, 723));
getContentPane().setLayout(null);
jLabel2.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel2.setText("Ticket and Invoice");
jLabel3.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jLabel3.setText("Order Id:");
jLabel4.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jLabel4.setText("Username:");
jLabel5.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jLabel5.setText("Movie:");
jLabel6.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jLabel6.setText("Theatre:");
jLabel7.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jLabel7.setText("Hall:");
jLabel8.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jLabel8.setText("Theatre Address:");
jLabel9.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jLabel9.setText("Date:");
jLabel10.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jLabel10.setText("Time:");
jLabel11.setFont(new java.awt.Font("Tahoma", 1, 36)); // NOI18N
jLabel11.setText("Cineplex Mangement System");
date.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
orderId.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
userName.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
movie.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
theatre.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
hall.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
theatreAddress.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
time.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addGap(0, 58, Short.MAX_VALUE)
.addComponent(jLabel11, javax.swing.GroupLayout.PREFERRED_SIZE, 572, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(20, 20, 20))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(37, 37, 37)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 108, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 108, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(75, 75, 75)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(userName, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 390, Short.MAX_VALUE)
.addComponent(movie, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(theatre, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(orderId, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addComponent(jLabel9, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel8, javax.swing.GroupLayout.PREFERRED_SIZE, 177, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 108, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel10, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(hall, javax.swing.GroupLayout.DEFAULT_SIZE, 390, Short.MAX_VALUE)
.addComponent(theatreAddress, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(date, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(time, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 108, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 108, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(76, 76, 76)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 456, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel11, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 68, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(orderId, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 54, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(userName, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 68, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(movie, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(theatre, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 68, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(hall))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel8, javax.swing.GroupLayout.PREFERRED_SIZE, 68, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(theatreAddress, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel9, javax.swing.GroupLayout.PREFERRED_SIZE, 68, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(date, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel10, javax.swing.GroupLayout.PREFERRED_SIZE, 68, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(time, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(45, 45, 45))
);
getContentPane().add(jPanel1);
jPanel1.setBounds(0, 0, 650, 720);
pack();
}// </editor-fold>
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(PrintTicket.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(PrintTicket.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(PrintTicket.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(PrintTicket.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new PrintTicket().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JLabel date;
private javax.swing.JLabel hall;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel11;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JPanel jPanel1;
private javax.swing.JLabel movie;
private javax.swing.JLabel orderId;
private javax.swing.JLabel theatre;
private javax.swing.JLabel theatreAddress;
private javax.swing.JLabel time;
private javax.swing.JLabel userName;
// End of variables declaration
}
I am Currently building a GUI for a tic tak toe game and i have finished it all, however when I tried to run it failed so I checked the code to find the problem and the only one i can currently find is that initComponents is red lined and I am Having a hard time finding out why.
I am currently new to Java and have only started coding recently so any assistance in this will be very appreciated.
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import java.awt.Component;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author matt
*/
public class TicTacToe extends javax.swing.JFrame {
/**
* Creates new form TicTacToe
*/
public TicTacToe() {
initComponents();
addAction();
}
public void winEffect(JButton b1, JButton b2, JButton b3)
{
b1.setBackground(Color.black);
b2.setBackground(Color.black);
b3.setBackground(Color.BLACK);
b1.setForeground(Color.WHITE);
b2.setForeground(Color.WHITE);
b3.setForeground(Color.WHITE);
String msg = b1.getText()+ " Is the winner";
jLabelMSG.setText(msg);
}
boolean win=false;
public void getthewinner(){
if(jButton1.getText().equals("")&& jButton1.getText().equals(jButton2.getText())&& jButton1.getText().equals(jButton3.getText())){
winEffect(jButton1, jButton2, jButton3);
win=true;
}
if(jButton4.getText().equals("")&& jButton4.getText().equals(jButton5.getText())&& jButton4.getText().equals(jButton6.getText())){
winEffect(jButton4, jButton5, jButton6);
win=true;
}
if(jButton7.getText().equals("")&& jButton7.getText().equals(jButton8.getText())&& jButton7.getText().equals(jButton9.getText())){
winEffect(jButton7, jButton8, jButton9);
win=true;
}
if(jButton1.getText().equals("")&& jButton1.getText().equals(jButton4.getText())&& jButton1.getText().equals(jButton7.getText())){
winEffect(jButton1, jButton4, jButton7);
win=true;
}
if(jButton2.getText().equals("")&& jButton2.getText().equals(jButton5.getText())&& jButton2.getText().equals(jButton9.getText())){
winEffect(jButton2, jButton5, jButton8);
win=true;
}
if(jButton3.getText().equals("")&& jButton3.getText().equals(jButton6.getText())&& jButton3.getText().equals(jButton9.getText())){
winEffect(jButton3, jButton6, jButton9);
win=true;
}
if(jButton1.getText().equals("")&& jButton1.getText().equals(jButton5.getText())&& jButton1.getText().equals(jButton9.getText())){
winEffect(jButton1, jButton5, jButton9);
win=true;
}
if(jButton3.getText().equals("")&& jButton3.getText().equals(jButton5.getText())&& jButton3.getText().equals(jButton7.getText())){
winEffect(jButton3, jButton5, jButton7);
win=true;
}
else if(allButtonTextLegnth()==9 && win==false){
jLabelMSG.setText("no one wins");
}
}
public int allButtonTextLegnth(){
String txt ="";
Component[]comps= jPanel3.getComponents();
for(Component comp :comps){
if(comp instanceof JButton){
JButton button = (JButton)comp;
txt = txt +button.getText();
}
}
return txt.length();
}
int x_or_o =0;
public ActionListener createAction(JButton button){
ActionListener al = new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
if(button.getText().equals("")){
if((x_or_o %2)==0){
button.setText("x");
button.setForeground(Color.BLUE);
jLabelMSG.setText("o turn now");
getthewinner();
}else{
button.setText("o");
button.setForeground(Color.red);
jLabelMSG.setText("x turn now");
getthewinner();
}
x_or_o ++;
}
}
};
return al;
}
//function to add action to the buttons
public void addAction(){
Component[]comps= jPanel3.getComponents();
for(Component comp :comps){
if(comp instanceof JButton){
JButton button = (JButton)comp;
button.addActionListener(createAction(button));
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
jButton4 = new javax.swing.JButton();
jButton5 = new javax.swing.JButton();
jButton6 = new javax.swing.JButton();
jButton7 = new javax.swing.JButton();
jButton8 = new javax.swing.JButton();
jButton9 = new javax.swing.JButton();
jPanel3 = new javax.swing.JPanel();
jLabelMSG = new javax.swing.JLabel();
jButtonReplay = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jButton1.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jButton2.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jButton3.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jButton4.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jButton5.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jButton6.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jButton7.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jButton8.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jButton9.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jPanel3.setBackground(new java.awt.Color(255, 51, 51));
jLabelMSG.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jLabelMSG.setForeground(new java.awt.Color(255, 255, 255));
jLabelMSG.setText("jLabel1");
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGap(94, 94, 94)
.addComponent(jLabelMSG)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGap(19, 19, 19)
.addComponent(jLabelMSG)
.addContainerGap(19, Short.MAX_VALUE))
);
jButtonReplay.setText("replay");
jButtonReplay.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonReplayActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(0, 80, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jPanel3, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addComponent(jButtonReplay, javax.swing.GroupLayout.PREFERRED_SIZE, 250, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jButton1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton7, javax.swing.GroupLayout.DEFAULT_SIZE, 78, Short.MAX_VALUE)
.addComponent(jButton4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, 78, Short.MAX_VALUE)
.addComponent(jButton8, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jButton9, javax.swing.GroupLayout.PREFERRED_SIZE, 74, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jButton6, javax.swing.GroupLayout.PREFERRED_SIZE, 74, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 74, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(94, 94, 94))))))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 74, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 74, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 74, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton6, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton5, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jButton8, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton7, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton9, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 30, Short.MAX_VALUE)
.addComponent(jButtonReplay)
.addGap(24, 24, 24))
);
pack();
}// </editor-fold>
}
private void jButtonReplayActionPerformed(java.awt.event.ActionEvent evt) {
win =false;
Component[]comps= jPanel3.getComponents();
for(Component comp :comps){
if(comp instanceof JButton){
JButton button = (JButton)comp;
button.setText("");
button.setBackground(Color.WHITE);
jLabelMSG.setText("play");
}
}
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(TicTacToe.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
`enter code here`java.util.logging.Logger.getLogger(TicTacToe.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
`enter code here`java.util.logging.Logger.getLogger(TicTacToe.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) { `enter code here`java.util.logging.Logger.getLogger(TicTacToe.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new TicTacToe().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JButton jButton4;
private javax.swing.JButton jButton5;
private javax.swing.JButton jButton6;
private javax.swing.JButton jButton7;
private javax.swing.JButton jButton8;
private javax.swing.JButton jButton9;
private javax.swing.JButton jButtonReplay;
private javax.swing.JLabel jLabelMSG;
private javax.swing.JPanel jPanel3;
// End of variables declaration
}
`
After your initComponents method, you have 2 closing } (after pack()).remove 1 of the brackets and add it after your addAction() method. this will solve your issue
Code with replaced class name:
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import java.awt.Component;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author matt
*/
public class Test extends javax.swing.JFrame {
/**
* Creates new form TicTacToe
*/
public Test() {
initComponents();
addAction();
}
public void winEffect(JButton b1, JButton b2, JButton b3) {
b1.setBackground(Color.black);
b2.setBackground(Color.black);
b3.setBackground(Color.BLACK);
b1.setForeground(Color.WHITE);
b2.setForeground(Color.WHITE);
b3.setForeground(Color.WHITE);
String msg = b1.getText() + " Is the winner";
jLabelMSG.setText(msg);
}
boolean win = false;
public void getthewinner() {
if (jButton1.getText().equals("") && jButton1.getText().equals(jButton2.getText())
&& jButton1.getText().equals(jButton3.getText())) {
winEffect(jButton1, jButton2, jButton3);
win = true;
}
if (jButton4.getText().equals("") && jButton4.getText().equals(jButton5.getText())
&& jButton4.getText().equals(jButton6.getText())) {
winEffect(jButton4, jButton5, jButton6);
win = true;
}
if (jButton7.getText().equals("") && jButton7.getText().equals(jButton8.getText())
&& jButton7.getText().equals(jButton9.getText())) {
winEffect(jButton7, jButton8, jButton9);
win = true;
}
if (jButton1.getText().equals("") && jButton1.getText().equals(jButton4.getText())
&& jButton1.getText().equals(jButton7.getText())) {
winEffect(jButton1, jButton4, jButton7);
win = true;
}
if (jButton2.getText().equals("") && jButton2.getText().equals(jButton5.getText())
&& jButton2.getText().equals(jButton9.getText())) {
winEffect(jButton2, jButton5, jButton8);
win = true;
}
if (jButton3.getText().equals("") && jButton3.getText().equals(jButton6.getText())
&& jButton3.getText().equals(jButton9.getText())) {
winEffect(jButton3, jButton6, jButton9);
win = true;
}
if (jButton1.getText().equals("") && jButton1.getText().equals(jButton5.getText())
&& jButton1.getText().equals(jButton9.getText())) {
winEffect(jButton1, jButton5, jButton9);
win = true;
}
if (jButton3.getText().equals("") && jButton3.getText().equals(jButton5.getText())
&& jButton3.getText().equals(jButton7.getText())) {
winEffect(jButton3, jButton5, jButton7);
win = true;
}
else if (allButtonTextLegnth() == 9 && win == false) {
jLabelMSG.setText("no one wins");
}
}
public int allButtonTextLegnth() {
String txt = "";
Component[] comps = jPanel3.getComponents();
for (Component comp : comps) {
if (comp instanceof JButton) {
JButton button = (JButton) comp;
txt = txt + button.getText();
}
}
return txt.length();
}
int x_or_o = 0;
public ActionListener createAction(JButton button) {
ActionListener al = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (button.getText().equals("")) {
if ((x_or_o % 2) == 0) {
button.setText("x");
button.setForeground(Color.BLUE);
jLabelMSG.setText("o turn now");
getthewinner();
} else {
button.setText("o");
button.setForeground(Color.red);
jLabelMSG.setText("x turn now");
getthewinner();
}
x_or_o++;
}
}
};
return al;
}
// function to add action to the buttons
public void addAction() {
Component[] comps = jPanel3.getComponents();
for (Component comp : comps) {
if (comp instanceof JButton) {
JButton button = (JButton) comp;
button.addActionListener(createAction(button));
}
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
jButton4 = new javax.swing.JButton();
jButton5 = new javax.swing.JButton();
jButton6 = new javax.swing.JButton();
jButton7 = new javax.swing.JButton();
jButton8 = new javax.swing.JButton();
jButton9 = new javax.swing.JButton();
jPanel3 = new javax.swing.JPanel();
jLabelMSG = new javax.swing.JLabel();
jButtonReplay = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jButton1.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jButton2.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jButton3.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jButton4.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jButton5.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jButton6.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jButton7.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jButton8.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jButton9.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jPanel3.setBackground(new java.awt.Color(255, 51, 51));
jLabelMSG.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jLabelMSG.setForeground(new java.awt.Color(255, 255, 255));
jLabelMSG.setText("jLabel1");
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup().addGap(94, 94, 94).addComponent(jLabelMSG)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)));
jPanel3Layout.setVerticalGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup().addGap(19, 19, 19).addComponent(jLabelMSG)
.addContainerGap(19, Short.MAX_VALUE)));
jButtonReplay.setText("replay");
jButtonReplay.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonReplayActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(layout
.createSequentialGroup().addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(layout
.createSequentialGroup().addGap(0, 80, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jPanel3, javax.swing.GroupLayout.Alignment.LEADING,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addComponent(jButtonReplay, javax.swing.GroupLayout.PREFERRED_SIZE, 250,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())))
.addGroup(layout.createSequentialGroup().addGroup(layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jButton1, javax.swing.GroupLayout.Alignment.LEADING,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE)
.addComponent(jButton7, javax.swing.GroupLayout.DEFAULT_SIZE, 78, Short.MAX_VALUE)
.addComponent(jButton4, javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, 78,
Short.MAX_VALUE)
.addComponent(jButton8, javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton5, javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jButton9, javax.swing.GroupLayout.PREFERRED_SIZE, 74,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
layout.createSequentialGroup().addGroup(layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING,
false)
.addComponent(jButton6, javax.swing.GroupLayout.PREFERRED_SIZE,
74, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE,
74, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(94, 94, 94)))))));
layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 74,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 74,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 74,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 63,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton6, javax.swing.GroupLayout.PREFERRED_SIZE, 63,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton5, javax.swing.GroupLayout.PREFERRED_SIZE, 63,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jButton8, javax.swing.GroupLayout.PREFERRED_SIZE, 64,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton7, javax.swing.GroupLayout.PREFERRED_SIZE, 64,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton9, javax.swing.GroupLayout.PREFERRED_SIZE, 64,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 30, Short.MAX_VALUE)
.addComponent(jButtonReplay).addGap(24, 24, 24)));
pack();
}
private void jButtonReplayActionPerformed(java.awt.event.ActionEvent evt) {
win = false;
Component[] comps = jPanel3.getComponents();
for (Component comp : comps) {
if (comp instanceof JButton) {
JButton button = (JButton) comp;
button.setText("");
button.setBackground(Color.WHITE);
jLabelMSG.setText("play");
}
}
}
/**
* #param args
* the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
// <editor-fold defaultstate="collapsed" desc=" Look and feel setting code
// (optional) ">
/*
* If Nimbus (introduced in Java SE 6) is not available, stay with the default
* look and feel. For details see
* http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Test.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Test.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Test.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Test.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
// </editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Test().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JButton jButton4;
private javax.swing.JButton jButton5;
private javax.swing.JButton jButton6;
private javax.swing.JButton jButton7;
private javax.swing.JButton jButton8;
private javax.swing.JButton jButton9;
private javax.swing.JButton jButtonReplay;
private javax.swing.JLabel jLabelMSG;
private javax.swing.JPanel jPanel3;
// End of variables declaration
}
If I click a row(JTABLE), it must display the specific values back to the textfields/combobox/radiobutton/spinner. But in my case, it's just hard to retrieve the values back to the RADIO BUTTON and SPINNER.
package coffeeshop;
import java.awt.HeadlessException;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import javax.swing.ListSelectionModel;
import javax.swing.table.DefaultTableModel;
public class coffeeframe extends javax.swing.JFrame {
public coffeeframe() {
initComponents();
ArrayList coffeeArray = new ArrayList();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jButton1 = new javax.swing.JButton();
buttonGroup1 = new javax.swing.ButtonGroup();
jScrollPane1 = new javax.swing.JScrollPane();
table = new javax.swing.JTable();
btnAdd = new javax.swing.JButton();
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
name = new javax.swing.JTextField();
coffeeType = new javax.swing.JComboBox<>();
jLabel3 = new javax.swing.JLabel();
coffeeName = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
coffeePrice = new javax.swing.JTextField();
quanOrder = new javax.swing.JSpinner();
jLabel5 = new javax.swing.JLabel();
dinein = new javax.swing.JRadioButton();
togo = new javax.swing.JRadioButton();
jButton2 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
jPanel2 = new javax.swing.JPanel();
jButton1.setText("jButton1");
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setBackground(new java.awt.Color(255, 255, 51));
table.setFont(new java.awt.Font("Arial", 1, 11)); // NOI18N
table.setForeground(new java.awt.Color(204, 0, 51));
table.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Customer", "Coffee Type", "Coffee Name", "Price", "Order Mode", "Quantity", "Total"
}
) {
boolean[] canEdit = new boolean [] {
false, false, false, false, false, false, false
};
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
table.setGridColor(new java.awt.Color(0, 102, 102));
table.getTableHeader().setReorderingAllowed(false);
table.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
tableMouseClicked(evt);
}
});
jScrollPane1.setViewportView(table);
btnAdd.setBackground(new java.awt.Color(204, 255, 204));
btnAdd.setFont(new java.awt.Font("Arial", 1, 11)); // NOI18N
btnAdd.setForeground(new java.awt.Color(102, 102, 102));
btnAdd.setIcon(new javax.swing.ImageIcon(getClass().getResource("/coffeeshop/Add-icon (1).png"))); // NOI18N
btnAdd.setText("ADD ORDER");
btnAdd.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnAddActionPerformed(evt);
}
});
jPanel1.setBackground(java.awt.Color.gray);
jPanel1.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
jLabel1.setFont(new java.awt.Font("Arial", 1, 11)); // NOI18N
jLabel1.setForeground(new java.awt.Color(255, 255, 255));
jLabel1.setText("Customer");
name.setFont(new java.awt.Font("Arial", 3, 11)); // NOI18N
name.setForeground(new java.awt.Color(51, 51, 51));
name.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
nameActionPerformed(evt);
}
});
coffeeType.setFont(new java.awt.Font("Arial", 1, 11)); // NOI18N
coffeeType.setForeground(new java.awt.Color(102, 102, 102));
coffeeType.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Choose", "Esprezo $20", "Green Tea Frappe $75", "Barako $22", "Black Coffee $28" }));
coffeeType.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
coffeeTypeItemStateChanged(evt);
}
});
coffeeType.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
coffeeTypeActionPerformed(evt);
}
});
jLabel3.setFont(new java.awt.Font("Arial", 1, 11)); // NOI18N
jLabel3.setForeground(new java.awt.Color(255, 255, 255));
jLabel3.setText("Coffee name");
coffeeName.setEditable(false);
coffeeName.setFont(new java.awt.Font("Arial", 3, 11)); // NOI18N
coffeeName.setForeground(new java.awt.Color(102, 102, 102));
coffeeName.setText(" ");
coffeeName.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
coffeeNameActionPerformed(evt);
}
});
jLabel2.setFont(new java.awt.Font("Arial", 1, 11)); // NOI18N
jLabel2.setForeground(new java.awt.Color(255, 255, 255));
jLabel2.setText("Coffee Type");
jLabel4.setFont(new java.awt.Font("Arial", 1, 11)); // NOI18N
jLabel4.setForeground(new java.awt.Color(255, 255, 255));
jLabel4.setText("Coffee price");
coffeePrice.setEditable(false);
coffeePrice.setFont(new java.awt.Font("Arial", 3, 11)); // NOI18N
coffeePrice.setForeground(new java.awt.Color(102, 102, 102));
coffeePrice.setText(" ");
quanOrder.setFont(new java.awt.Font("Arial", 3, 11)); // NOI18N
quanOrder.setModel(new javax.swing.SpinnerNumberModel(1, 1, 100, 1));
jLabel5.setFont(new java.awt.Font("Arial", 1, 11)); // NOI18N
jLabel5.setForeground(new java.awt.Color(255, 255, 255));
jLabel5.setText("Quantity");
buttonGroup1.add(dinein);
dinein.setFont(new java.awt.Font("Arial", 1, 11)); // NOI18N
dinein.setForeground(new java.awt.Color(255, 255, 255));
dinein.setSelected(true);
dinein.setText("Dine-In");
dinein.setBorder(null);
dinein.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
dineinActionPerformed(evt);
}
});
buttonGroup1.add(togo);
togo.setFont(new java.awt.Font("Arial", 1, 11)); // NOI18N
togo.setForeground(new java.awt.Color(255, 255, 255));
togo.setText("To-Go");
togo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
togoActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(coffeeName, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel4))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel2)
.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 70, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(name)
.addComponent(coffeeType, 0, 163, Short.MAX_VALUE))
.addGap(112, 112, 112))))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(85, 85, 85)
.addComponent(dinein, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(togo)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel5)))
.addGap(10, 10, 10)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(coffeePrice, javax.swing.GroupLayout.PREFERRED_SIZE, 74, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(quanOrder, javax.swing.GroupLayout.PREFERRED_SIZE, 74, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(25, 25, 25))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(17, 17, 17)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(name, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(coffeeType, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 30, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(coffeePrice, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(coffeeName, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3)
.addComponent(jLabel4)))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(togo, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(dinein, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel5)
.addComponent(quanOrder, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap())
);
jButton2.setBackground(new java.awt.Color(255, 204, 204));
jButton2.setFont(new java.awt.Font("Arial", 1, 11)); // NOI18N
jButton2.setForeground(new java.awt.Color(102, 102, 102));
jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/coffeeshop/edit-icon.png"))); // NOI18N
jButton2.setText("EDIT ORDER");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jButton3.setBackground(new java.awt.Color(255, 51, 51));
jButton3.setFont(new java.awt.Font("Arial", 1, 11)); // NOI18N
jButton3.setForeground(new java.awt.Color(239, 234, 234));
jButton3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/coffeeshop/trash-icon.png"))); // NOI18N
jButton3.setText(" ");
jPanel2.setBackground(new java.awt.Color(255, 255, 255));
jPanel2.setBorder(javax.swing.BorderFactory.createEmptyBorder(5, 5, 5, 5));
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 201, Short.MAX_VALUE)
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 0, Short.MAX_VALUE)
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jScrollPane1)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnAdd, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 115, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(btnAdd, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
pack();
}// </editor-fold>
private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {
try{
int total = Integer.parseInt(coffeePrice.getText()) * (Integer)quanOrder.getValue();
DefaultTableModel model = (DefaultTableModel)table.getModel();
Coffee coffee = new Coffee(name.getText(),coffeeType.getSelectedItem().toString(),coffeeName.getText(),Integer.parseInt(coffeePrice.getText()),buttonGroup1.getSelection().getActionCommand(),(Integer)quanOrder.getValue(),total);
coffeeArray.add(coffee);
if(name.getText().trim().isEmpty()){
JOptionPane.showMessageDialog(null,"Complete the order details!");
}else if(buttonGroup1.getSelection().getActionCommand()== null){
JOptionPane.showMessageDialog(null,"Complete the order details!");
}else{
String customerName = name.getText();
String cofType = coffeeType.getSelectedItem().toString();
String cofName = coffeeName.getText();
int price = Integer.parseInt(coffeePrice.getText());
String OrderMode= buttonGroup1.getSelection().getActionCommand();
int quantity = (Integer)quanOrder.getValue();
Object[] rowCoffee = {customerName,cofType,cofName,price,OrderMode,quantity,total};
model.addRow(rowCoffee);
}
}catch(NumberFormatException | HeadlessException e){
JOptionPane.showMessageDialog(null,"Complete the order details!");
}
}
private void coffeeTypeActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String str_coffee_name = (String)coffeeType.getSelectedItem();
String input_coffee_name = str_coffee_name.replaceAll("[^a-zA-Z]","");
coffeeName.setText(input_coffee_name);
String str_coffee_price = (String)coffeeType.getSelectedItem();
String input_coffee_price = str_coffee_price.replaceAll("[^0-9]","");
coffeePrice.setText(input_coffee_price);
}
private void coffeeNameActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void togoActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
togo.setActionCommand("TO-GO");
}
private void dineinActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
dinein.setActionCommand("DINE-IN");
}
private void nameActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void coffeeTypeItemStateChanged(java.awt.event.ItemEvent evt) {
// TODO add your handling code here:
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
DefaultTableModel model = (DefaultTableModel)table.getModel();
int i = table.getSelectedRow();
int total = Integer.parseInt(coffeePrice.getText()) * (Integer)quanOrder.getValue();
if(i >= 0)
{
model.setValueAt(name.getText(), i, 0);
model.setValueAt(coffeeType.getSelectedItem(), i, 1);
model.setValueAt(coffeeName.getText(), i, 2);
model.setValueAt(Integer.parseInt(coffeePrice.getText()), i, 3);
model.setValueAt(buttonGroup1.getSelection().getActionCommand(), i, 4);
model.setValueAt((Integer)quanOrder.getValue(), i, 5);
model.setValueAt(total, i, 6);
}
else{
System.out.println("Update Error");
}
}
private void tableMouseClicked(java.awt.event.MouseEvent evt) {
try{
DefaultTableModel model = (DefaultTableModel)table.getModel();
int row = table.getSelectedRow();
name.setText(model.getValueAt(row, 0).toString());
coffeeType.setSelectedItem(table.getValueAt(row, 1).toString());
coffeeName.setText(model.getValueAt(row, 2).toString());
coffeePrice.setText(model.getValueAt(row, 3).toString());
quanOrder.setValue(model.getValueAt(row, 5).toString());
}catch(Exception e){
}
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(coffeeframe.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(coffeeframe.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(coffeeframe.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(coffeeframe.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new coffeeframe().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton btnAdd;
private javax.swing.ButtonGroup buttonGroup1;
private javax.swing.JTextField coffeeName;
private javax.swing.JTextField coffeePrice;
private javax.swing.JComboBox<String> coffeeType;
private javax.swing.JRadioButton dinein;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextField name;
private javax.swing.JSpinner quanOrder;
private javax.swing.JTable table;
private javax.swing.JRadioButton togo;
// End of variables declaration
ArrayList<Coffee> coffeeArray = new ArrayList<>();
int length = 0;
}
How to change the values of spinner and radio button
The spinner should be easily settable by calling its setValue(...) method, and passing in the number from the selected table row item.
For the JRadioButtons, probably the easiest solution is to use a Map that maps the selection to its radio button, and then using this map to get a reference to the proper JRadioButton, and calling setSelected(true) on it.
For an example, and for an example of a Minimal, Complete, and Verifiable example, please have a look at:
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.util.EnumMap;
import java.util.Map;
import java.util.Vector;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
#SuppressWarnings("serial")
public class CoffeeMcve extends JPanel {
private CoffeeTableModel tableModel = new CoffeeTableModel();
private JTable table = new JTable(tableModel);
private Map<OrderMode, ButtonModel> modeButtonMap = new EnumMap<>(OrderMode.class);
private JSpinner quantSpinner = new JSpinner(new SpinnerNumberModel(1, 0, 20, 1));
private JTextField nameTField = new JTextField(10);
private ButtonGroup modeBtnGroup = new ButtonGroup();
public CoffeeMcve() {
JPanel modePanel = new JPanel();
modePanel.setBorder(BorderFactory.createTitledBorder("Order Mode"));
for (OrderMode mode : OrderMode.values()) {
JRadioButton rBtn = new JRadioButton(mode.getText());
rBtn.setActionCommand(mode.toString());
modeBtnGroup.add(rBtn);
modePanel.add(rBtn);
modeButtonMap.put(mode, rBtn.getModel());
}
JPanel orderPanel = new JPanel();
orderPanel.add(new JLabel("Name:"));
orderPanel.add(nameTField);
orderPanel.add(new JLabel("Quantity:"));
orderPanel.add(quantSpinner);
orderPanel.add(modePanel);
orderPanel.add(new JButton(new AddAction("Add", KeyEvent.VK_A)));
table.getColumnModel().getColumn(2).setCellRenderer(new OrderModeColumnRenderer());
JScrollPane scrollPane = new JScrollPane(table);
setLayout(new BorderLayout());
add(scrollPane, BorderLayout.CENTER);
add(orderPanel, BorderLayout.PAGE_END);
table.getSelectionModel().addListSelectionListener(new MyTableListener());
}
public void setOrderData(CoffeeOrder2 order) {
nameTField.setText(order.getName());
quantSpinner.setValue(order.getQuant());
ButtonModel btnModel = modeButtonMap.get(order.getOrderMode());
modeBtnGroup.setSelected(btnModel, true);
}
private class MyTableListener implements ListSelectionListener {
#Override
public void valueChanged(ListSelectionEvent e) {
if (!e.getValueIsAdjusting()) {
int index = table.getSelectedRow();
CoffeeOrder2 order = tableModel.getRow(index);
setOrderData(order);
}
}
}
private class OrderModeColumnRenderer extends DefaultTableCellRenderer {
#Override
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
if (value != null && value instanceof OrderMode) {
value = ((OrderMode) value).getText();
}
return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
}
}
private class AddAction extends AbstractAction {
public AddAction(String name, int mnemonic) {
super(name);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
String name = nameTField.getText();
int quant = (int) quantSpinner.getValue();
ButtonModel model = modeBtnGroup.getSelection();
if (model != null) {
String actionCommand = model.getActionCommand();
OrderMode orderMode = OrderMode.valueOf(actionCommand);
CoffeeOrder2 coffeeOrder2 = new CoffeeOrder2(name, quant, orderMode);
tableModel.addRow(coffeeOrder2);
}
}
}
private static void createAndShowGui() {
CoffeeMcve mainPanel = new CoffeeMcve();
JFrame frame = new JFrame("CoffeeMcve");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
#SuppressWarnings("serial")
class CoffeeTableModel extends DefaultTableModel {
public static final String[] TITLES = {"Name", "Quantity", "Order Mode"};
public CoffeeTableModel() {
super(TITLES, 0);
}
public void addRow(CoffeeOrder2 coffee2) {
Vector<Object> rowData = new Vector<>();
rowData.add(coffee2.getName());
rowData.add(coffee2.getQuant());
rowData.add(coffee2.getOrderMode());
super.addRow(rowData);
}
#Override
public Class<?> getColumnClass(int columnIndex) {
Object value = getValueAt(0, columnIndex);
if (value == null) {
return super.getColumnClass(columnIndex);
} else {
return value.getClass();
}
}
public CoffeeOrder2 getRow(int rowIndex) {
if (rowIndex < 0 || rowIndex >= getRowCount()) {
String text = "For rowIndex: " + rowIndex;
throw new IllegalArgumentException(text);
}
String name = getValueAt(rowIndex, 0).toString();
int quant = (int) getValueAt(rowIndex, 1);
OrderMode orderMode = (OrderMode) getValueAt(rowIndex, 2);
return new CoffeeOrder2(name, quant, orderMode);
}
}
class CoffeeOrder2 {
private String name;
private int quant;
private OrderMode orderMode;
public CoffeeOrder2(String name, int quant, OrderMode orderMode) {
this.name = name;
this.quant = quant;
this.orderMode = orderMode;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getQuant() {
return quant;
}
public void setQuant(int quant) {
this.quant = quant;
}
public OrderMode getOrderMode() {
return orderMode;
}
public void setOrderMode(OrderMode orderMode) {
this.orderMode = orderMode;
}
}
enum OrderMode {
HERE("Here"), TO_GO("To Go");
private String text;
private OrderMode(String text) {
this.text = text;
}
public String getText() {
return text;
}
}
This is what the textfield looks like before clicking the check button:
This is what happens after clicking check. This only happens with a string that is longer than the textfield.
This is the code from netbeans:
package filevalidator;
import java.awt.Color;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
/**
*
* #author Kosar
*/
public class Validator extends javax.swing.JFrame {
static String path1 = null;
static String path2 = null;
/**
* Creates new form Validator
*/
public Validator() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
file1path = new javax.swing.JTextField();
select1 = new javax.swing.JButton();
jLabel2 = new javax.swing.JLabel();
file2path = new javax.swing.JTextField();
select2 = new javax.swing.JButton();
hash1 = new javax.swing.JLabel();
hash2 = new javax.swing.JLabel();
result = new javax.swing.JLabel();
checkBtn = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setResizable(false);
jLabel1.setFont(new java.awt.Font("Trebuchet MS", 0, 18)); // NOI18N
jLabel1.setText("Original File:");
file1path.setFont(new java.awt.Font("Trebuchet MS", 0, 14)); // NOI18N
file1path.setAutoscrolls(false);
select1.setText("Select");
select1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
select1ActionPerformed(evt);
}
});
jLabel2.setFont(new java.awt.Font("Trebuchet MS", 0, 18)); // NOI18N
jLabel2.setText("Second File:");
file2path.setFont(new java.awt.Font("Trebuchet MS", 0, 14)); // NOI18N
file2path.setAutoscrolls(false);
file2path.setCursor(new java.awt.Cursor(java.awt.Cursor.TEXT_CURSOR));
select2.setText("Select");
select2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
select2ActionPerformed(evt);
}
});
hash1.setFont(new java.awt.Font("Trebuchet MS", 1, 20)); // NOI18N
hash1.setForeground(java.awt.Color.blue);
hash1.setText(" ");
hash2.setFont(new java.awt.Font("Trebuchet MS", 1, 20)); // NOI18N
hash2.setForeground(java.awt.Color.blue);
hash2.setText(" ");
result.setFont(new java.awt.Font("Trebuchet MS", 1, 20)); // NOI18N
result.setText(" ");
checkBtn.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N
checkBtn.setText("Check");
checkBtn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
checkBtnActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addComponent(jLabel2))
.addGap(32, 32, 32)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(result, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(151, 151, 151)
.addComponent(hash2, javax.swing.GroupLayout.DEFAULT_SIZE, 340, Short.MAX_VALUE))
.addComponent(hash1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(30, 30, 30))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(file1path, javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(file2path))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(select1, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(select2, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(checkBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(331, 331, 331))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(59, 59, 59)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(file1path, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(select1))
.addGap(27, 27, 27)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(file2path, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(select2))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 21, Short.MAX_VALUE)
.addComponent(hash1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(hash2)
.addGap(13, 13, 13)
.addComponent(result)
.addGap(5, 5, 5)
.addComponent(checkBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(27, 27, 27)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(27, 27, 27))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(34, 34, 34)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
setLocationRelativeTo(null);
}// </editor-fold>
private void select1ActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser chooser = new JFileChooser();
chooser.setDialogTitle("Select file");
if (chooser.showOpenDialog(select1) == JFileChooser.APPROVE_OPTION) {
path1 = chooser.getSelectedFile().getAbsolutePath();
}
file1path.setText(path1);
file1path.setBackground(Color.white);
}
private void select2ActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser chooser = new JFileChooser();
chooser.setDialogTitle("Select file");
if (chooser.showOpenDialog(select2) == JFileChooser.APPROVE_OPTION) {
path2 = chooser.getSelectedFile().getAbsolutePath();
}
file2path.setText(path2);
file2path.setBackground(Color.white);
}
private void checkBtnActionPerformed(java.awt.event.ActionEvent evt) {
try {
HashMD5 hasher = new HashMD5();
try {
hash1.setText(hasher.hash(path1));
hash2.setText(hasher.hash(path2));
} catch (NoSuchAlgorithmException | IOException ex) {
}
if ( hash1.getText().equals(hash2.getText())) {
result.setForeground(Color.GREEN);
result.setText("Hashes are the same. File has not been modified.");
}
else {
result.setForeground(Color.RED);
result.setText("Hashes are not the same. File has been modified.");
}
} catch (NullPointerException e) {
if (file1path.getText() == null) {
file1path.setBackground(Color.red);
}
else if (file2path.getText() == null) {
file2path.setBackground(Color.red);
}
else {
file1path.setBackground(Color.red);
file2path.setBackground(Color.red);
}
}
}
/**
* #param args the command line arguments
*/
// Variables declaration - do not modify
private javax.swing.JButton checkBtn;
private javax.swing.JTextField file1path;
private javax.swing.JTextField file2path;
private javax.swing.JLabel hash1;
private javax.swing.JLabel hash2;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JPanel jPanel1;
private javax.swing.JLabel result;
private javax.swing.JButton select1;
private javax.swing.JButton select2;
// End of variables declaration
}
You can handle it by using TextField and its method to set columns i.e. "setColumns(int numOfCols)"
import java.awt.FlowLayout;
import java.awt.Container;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class TextFieldExample extends JFrame {
JFrame frame = new JFrame();
public TextFieldExample()
{
frame = new JFrame("Test");
Container container = frame.getContentPane();
JTextField fld1 = new JTextField("Java C++ C");
JTextField fld2 = new JTextField("");
JTextField fld3 = new JTextField("");
fld1.setColumns(5); //Now, it will not be resized.
fld2.setColumns(7); //Now, it will not be resized.
fld3.setColumns(9); //Now, it will not be resized.
container.setLayout(new FlowLayout());
container.add(fld1);
container.add(fld2);
container.add(fld3);
frame.setVisible(true);
frame.setSize(150,150);
}
public static void main(String[] args) {
TextFieldExample obj = new TextFieldExample();
}
}