First of all i apologize for my english neglect that i will explain all my problem.
First i want JCheckBox in the JTable i have.
I am retrieving student id and student name from database in column index 0 and 1. I want third column should be Absent/Present which will initially take whether student is present or absent by JCheckbox Value.
Here my code for JTable values :
Attendance.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package shreesai;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Vector;
/**
*
* #author Admin
*/
public class Attendance{
Connection con = Connectdatabase.ConnecrDb();
public Vector getEmployee()throws Exception
{
Vector<Vector<String>> employeeVector = new Vector<Vector<String>>();
PreparedStatement pre = con.prepareStatement("select studentid,name from student");
ResultSet rs = pre.executeQuery();
while(rs.next())
{
Vector<String> employee = new Vector<String>();
employee.add(rs.getString(1)); //Empid
employee.add(rs.getString(2));//name
employeeVector.add(employee);
}
if(con!=null)
con.close();
rs.close();
pre.close();
return employeeVector;
}
}
THIS CODE FOR TAKING VALUES FROM DATABASE SAVING IT INTO VECTOR
AttendanceGUI.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package shreesai;
import static java.awt.Frame.MAXIMIZED_BOTH;
import java.util.Vector;
import javax.swing.JOptionPane;
/**
*
* #author Admin
*/
public class AttendanceGUI extends javax.swing.JFrame {
/**
* Creates new form AttendanceGUI
*/
private Vector<Vector<String>> data;
private Vector<String> header;
public AttendanceGUI() throws Exception {
this.setLocationRelativeTo(null);
setExtendedState(MAXIMIZED_BOTH);
Attendance att = new Attendance();
data = att.getEmployee();
header = new Vector<String>();
header.add("Student ID");
header.add("Student Name");
header.add("Absent/Present");
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() {
jScrollPane1 = new javax.swing.JScrollPane();
AttendanceT = new javax.swing.JTable();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
AttendanceT.setModel(new javax.swing.table.DefaultTableModel(
data,header
));
jScrollPane1.setViewportView(AttendanceT);
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()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(397, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(89, Short.MAX_VALUE))
);
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(AttendanceGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(AttendanceGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(AttendanceGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(AttendanceGUI.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() {
try{
new AttendanceGUI().setVisible(true);
}
catch(Exception e){
JOptionPane.showMessageDialog(null,e);
}
}
});
}
// Variables declaration - do not modify
private javax.swing.JTable AttendanceT;
private javax.swing.JScrollPane jScrollPane1;
// End of variables declaration
}
My problemis that I can't add a JCheckBox in front of every student I have seen JTabel model, renderer and all but I don't get anything. I want something like this...
I've search for this stuff for a couple of weeks but did bot get anything suitable for this
Start with How to use tables.
Your table model needs several things.
It needs to return Boolean.class from the getColumnClass method for the appropriate column. You will need to override this method.
The method isCellEditable will need to return true for the table column you want to make editable (so the user can change the value of the column)
You're table model will need to be capable of holding the value for the column
Make sure you pass a valid value for the boolean column for the row, otherwise it will be null
Updated with simple example
import java.awt.EventQueue;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.DefaultTableModel;
public class TableTest {
public static void main(String[] args) {
new TableTest();
}
public TableTest() {
startUI();
}
public void startUI() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
MyTableModel model = new MyTableModel();
model.addRow(new Object[]{0, "Brian", false});
model.addRow(new Object[]{1, "Ned", false});
model.addRow(new Object[]{2, "John", false});
model.addRow(new Object[]{3, "Drogo", false});
JTable table = new JTable(model);
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new JScrollPane(table));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class MyTableModel extends DefaultTableModel {
public MyTableModel() {
super(new String[]{"ID", "Name", "Present"}, 0);
}
#Override
public Class<?> getColumnClass(int columnIndex) {
Class clazz = String.class;
switch (columnIndex) {
case 0:
clazz = Integer.class;
break;
case 2:
clazz = Boolean.class;
break;
}
return clazz;
}
#Override
public boolean isCellEditable(int row, int column) {
return column == 2;
}
#Override
public void setValueAt(Object aValue, int row, int column) {
if (aValue instanceof Boolean && column == 2) {
System.out.println(aValue);
Vector rowData = (Vector)getDataVector().get(row);
rowData.set(2, (boolean)aValue);
fireTableCellUpdated(row, column);
}
}
}
}
Ps- I would HIGHLY recommend you avoid form editors until you have a better understanding of how Swing works - IMHO
Well if you add Boolean value as data into the table model, DefaultCellRendered will render it as checbox by itself, so where is the problem?
Related
I am creating a netbeans java project that retrieves data from a microsoft access database.
I need to display an editable checkbox for one of my columns but for some reason it comes up as true/false instead. The jTable in the Design view shows checkboxes but when I run the program true/false is displayed.
I really don't understand editors and renders though I have tried, a solution without this would be preferable but if it is the only way, please explain how to do it.
Here is my GUI code:
/*
* 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 timetable;
/**
*
* #author Lenovo
*/
public class TaskFrame extends javax.swing.JFrame {
/**
* Creates new form Main
*/
public TaskFrame() {
initComponents();
this.setLocationRelativeTo(null);
taskList t = new taskList()
jtblTodayTasks.setModel(t.filljtblTodayTasks());
}
/**
* 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() {
jScrollPane1 = new javax.swing.JScrollPane();
jtblTodayTasks = new javax.swing.JTable();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setBackground(new java.awt.Color(255, 255, 255));
setMinimumSize(new java.awt.Dimension(1100, 619));
setResizable(false);
setSize(new java.awt.Dimension(1100, 619));
getContentPane().setLayout(null);
jtblTodayTasks.setFont(new java.awt.Font("Roboto", 0, 14)); // NOI18N
jtblTodayTasks.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null, null},
{null, null, null, null, null},
{null, null, null, null, null},
{null, null, null, null, null}
},
new String [] {
"ID", "Task", "Subject", "Due Date", "Completed"
}
) {
Class[] types = new Class [] {
java.lang.Integer.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Boolean.class
};
boolean[] canEdit = new boolean [] {
false, false, false, false, true
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
jScrollPane1.setViewportView(jtblTodayTasks);
if (jtblTodayTasks.getColumnModel().getColumnCount() > 0) {
jtblTodayTasks.getColumnModel().getColumn(4).setPreferredWidth(0);
}
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(TaskFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(TaskFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(TaskFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(TaskFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new TaskFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jtblTodayTasks;
private javax.swing.JTabbedPane tabbedPane;
// End of variables declaration
}
Here is my taskList class:
/*
* 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 timetable;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
/**
*
* #author Lenovo
*/
public class taskList {
ArrayList<Task> taskArray = new ArrayList<>();
public taskList(){
ConnectDB db = new ConnectDB();
ResultSet rs = db.getResults("SELECT * FROM tblTasks WHERE userID = " + Login.currentUserID + " ORDER BY dueDate;");
try{
while (rs.next()){
Task task = new Task(rs.getInt("taskID"), rs.getInt("userID"), rs.getString("taskName"), rs.getString("Subject"), rs.getString("taskDetails"), rs.getString("dueDate"), rs.getBoolean("Completed"));
taskArray.add(task);
}
rs.close();
}catch (SQLException ex) {
JOptionPane.showMessageDialog(null, "Database error. Please contact the system Administrator");
}
}
public DefaultTableModel filljtblTodayTasks(){
Object[] columnNames = {"ID", "Task", "Subject", "Due Date", "Completed"};
DefaultTableModel model = new DefaultTableModel(columnNames, 0);
for (int i = 0; i < taskArray.size(); i++) {
model.addRow(new Object[]{taskArray.get(i).getTaskID(), taskArray.get(i).getTaskName(), taskArray.get(i).getSubject(), taskArray.get(i).getDueDate(), taskArray.get(i).isCompleted()});
}
return model;
}
Thank you so much!
The jTable in the Design view shows checkboxes but when I run the program true/false is displayed.
The getColumnClass(...) method determines which renderer is used for each column
The code in your TaskFrame already creates a custom model and overrides the getColumnClass(...) method.
But then you create another table model but are not overriding the getColumnClass(...) method:
Object[] columnNames = {"ID", "Task", "Subject", "Due Date", "Completed"};
DefaultTableModel model = new DefaultTableModel(columnNames, 0);
Don't create a new DefaultTableModel.
Instead you can just use:
DefaultTableModel model = (DefaultTableModel)jtblTodayTasks.getModel();
model.setRowCount( 0 );
The above code will remove the data from the existing model, so you can add new data.
I am building a JTable that displays some little info from my database, about 18000 rows. Everything is displayed well in the table, except for the vertical scrollbar. It just disappears when the table is high populated. I have another JTable with about 500 rows and I the problem gets solved increasing the height of the JTable, but 1) that's not the solution and 2) does not work for the biggest JTable.
My question is: is there any way to force the scrollbar to be there?
I've tried setting the JScrollPane vertical scrollbar policy to ALWAYS but it is not working.
Here is the SSCCE:
import javax.swing.table.DefaultTableModel;
/**
*
*
*/
public class NewJFrame extends javax.swing.JFrame {
/**
* Creates new form NewJFrame
*/
public NewJFrame() {
initComponents();
final DefaultTableModel tabla = (DefaultTableModel) jTable1.getModel();
//Adds 1000 rows for testing the error
for(int i = 0; i < 1000; i++){
tabla.addRow(new Object[]{""+i});
}
}
/**
* 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() {
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null}
},
new String [] {
"Title 1"
}
) {
Class[] types = new Class [] {
java.lang.String.class
};
#Override
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
});
jScrollPane1.setViewportView(jTable1);
final 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()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 375, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(13, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 323, Short.MAX_VALUE)
.addContainerGap())
);
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 (final javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (final ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (final InstantiationException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (final IllegalAccessException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (final javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new NewJFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTable1;
// End of variables declaration
}
Hope you can help!
After deep search I found a question that explained my problem.
Putting this code after setting the Nimbus L&F solved the problem:
LookAndFeel lookAndFeel = UIManager.getLookAndFeel();
UIDefaults defaults = lookAndFeel.getDefaults();
defaults.put("ScrollBar.minimumThumbSize", new Dimension(30, 30));
in the textPaneKeyTyped(java.awt.event.keyEvent evt) method I wrote some code to automatically close brackets when the opening one is typed. I added some code for remove the closing bracket when the user type it in textPane, but it doesn't do anything
This is a working example:
package test;
import java.awt.event.ActionEvent;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JTextPane;
import javax.swing.KeyStroke;
import javax.swing.text.BadLocationException;
public class NewJFrame extends javax.swing.JFrame {
/** Creates new form NewJFrame */
public NewJFrame() {
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();
jScrollPane1 = new javax.swing.JScrollPane();
textPanel = new javax.swing.JTextPane();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
textPanel.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
textPanelKeyTyped(evt);
}
});
jScrollPane1.setViewportView(textPanel);
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()
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 380, Short.MAX_VALUE)
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(19, 19, 19)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 254, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(27, Short.MAX_VALUE))
);
getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER);
pack();
}// </editor-fold>
private void textPanelKeyTyped(java.awt.event.KeyEvent evt) {
// TODO add your handling code here:
Action action1 = new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
textModel = (JTextPane) e.getSource();
try {
int position2 = textModel.getCaretPosition();
textModel.getDocument().remove(position2, 1);
textModel.getDocument().insertString(position2, ")", null);
} catch (Exception e1) {}
}
};
Action action = new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
int position = textModel.getCaretPosition();
textModel.replaceSelection("()");
textModel.setCaretPosition(position+1);
}
};
String key = "typed (";
String key1 = "typed )";
textPanel.getInputMap().put(KeyStroke.getKeyStroke(key), key);
textPanel.getInputMap().put(KeyStroke.getKeyStroke(key1), key1);
textPanel.getActionMap().put(key, action);
textPanel.getActionMap().put(key1, action1);
}
/**
* #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(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(NewJFrame.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 NewJFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextPane textPanel;
// End of variables declaration
}
The code for the automatic closure of the brackets works..
The problem is for the replace of the closing bracket: it prints ')' just when before there's a '('. If I would be able to print the ')' at any time, how should I edit my code?
Thank you.
It is never a good idea to block the usage of a KeyStroke. You never know when the ")" might need to be entered manually. Who cares if the user enters the ")". If it is not syntactically correct then they will eventually get a compile error. The smart user will realize that all then need to do is type "(" and the ")" will be entered for them.
However, if there is a situation when you do want to prevent the typing of a given character you would use Key Bindings NOT a KeyListener.
For example:
KeyStroke ignore = KeyStroke.getKeyStroke(')');
textPane.getInputMap().put(ignore, "none");
For more information on Key Bindings read the Swig tutorial. I gave you a link in one of your previous questions. Keep the tutorial link handy for the basics. You will find a section on How to Use Key Bindings when you look at the table of contents ("trail") for the tutorial.
Also for your "(" Action you can just use:
textPane.replaceSelection("()");
So I am trying to get my text input box for my fish sandwich next to the text for it. It keeps pushing down next to the hamburger input box. I cannot seem to get it next to it. Here is the code.
here is a screenshot
/*
* 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 foodproject2;
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
/**
*
* #author Travis
*/
public class Menu1 extends javax.swing.JFrame {
private Container contents;
private JLabel name, courseNum, welcome, prompt, chickP, fishP, burgerP;
private JLabel chargeSand, chargeService, totalBill;
private JTextField numChick, numFish, numBurger;
private JButton compute;
public Menu1()
{
super("Travis' Menu");
contents = getContentPane();
contents.setLayout(new FlowLayout());
name=new JLabel("Programmer: Travis Easton");
courseNum=new JLabel("ITSD424");
welcome=new JLabel("Welcome To Travis' Sandwich Shop");
prompt=new JLabel("Enter number of Sandwiches for each; 0 if none");
chickP=new JLabel("Chicken Sandwiches # $4.99 each");
chickP.setForeground(Color.BLACK);
numChick=new JTextField(3);
fishP=new JLabel("Salmon Sandwiches # $4.99 each ");
fishP.setForeground(Color.BLACK);
numFish=new JTextField(3);
burgerP=new JLabel("Hamburger # $4.99 each");
burgerP.setForeground(Color.BLACK);
numBurger=new JTextField(3);
chargeSand = new JLabel("Charge for Sandwiches = $");
chargeService = new JLabel("Charge for Service = $");
totalBill= new JLabel("Total Bill = $");
chargeSand = new JLabel("Sandwich cost");
chargeService = new JLabel("Tax");
totalBill = new JLabel("Total");
compute = new JButton("Bill Total");
contents.add(name);
contents.add(courseNum);
contents.add(welcome);
contents.add(prompt);
contents.add(chickP);
contents.add(numChick);
contents.add(fishP);
contents.add(burgerP);
contents.add(numFish);
contents.add(numBurger);
contents.add(chargeSand);
contents.add(chargeService);
contents.add(totalBill);
contents.add(chargeSand);
contents.add(chargeService);
contents.add(totalBill);
contents.add(compute);
ButtonHandler bh = new ButtonHandler();
compute.addActionListener(bh);
setSize(400,400);
setVisible(true);
}
private class ButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e) {
try
{
double one = Double.parseDouble(numChick.getText());
double two = Double.parseDouble(numFish.getText());
double three = Double.parseDouble(numBurger.getText());
// Calculations for determining total price of bill
double orderAmount = (one*4.99)+(two*4.99)+(three*4.99);
double serviceAmount = (orderAmount)*.15;
double totalAmount = (orderAmount+serviceAmount);
// Now to display the charges
chargeSand.setText(new Double(orderAmount).toString());
chargeService.setText(new Double(serviceAmount).toString());
totalBill.setText(new Double(totalAmount).toString());
}
catch(NumberFormatException ex)
{
numChick.setText("0");
numFish.setText("0");
numBurger.setText("0");
totalBill.setText("0");
}
}
}
/**
* Creates new form Menu
*/
{
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">//GEN-BEGIN:initComponents
private void initComponents() {
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 300, Short.MAX_VALUE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
/**
* #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(Menu1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Menu1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Menu1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Menu1.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 Menu1().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
// End of variables declaration//GEN-END:variables
}
In you code, the string that you have passed into the fishP JLabel contains spaces at the end.
I think it should be:
fishP=new JLabel("Salmon Sandwiches # $4.99 each");
One more change:
contents.add(chickP);
contents.add(numChick);
contents.add(fishP);
contents.add(numFish);
contents.add(burgerP);
contents.add(numBurger);
When you add the content you are doing it in the wrong order:
contents.add(chickP);
contents.add(numChick);
contents.add(fishP);
contents.add(burgerP);
contents.add(numFish);
contents.add(numBurger);
Move numFish up.
First of all sorry for my poor English. I'll try my best to understand you my problem.
All I want is to save the new data whichever user has entered in the JTable whenever Save button will clicked.
I am retrieving Student ID, Name in first two columns from database and also i have added current date in third column and Absent/Present as fourth column which is editable. I have following code to retrieve data from database.
**Attendance.java** :
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package shreesai;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.Vector;
/**
*
* #author Admin
*/
public class Attendance{
Connection con = Connectdatabase.ConnecrDb();
java.sql.Date sqlDate = new java.sql.Date(new java.util.Date().getTime());
SimpleDateFormat fromUser = new SimpleDateFormat("dd/MM/yyyy");
String d1 = fromUser.format(sqlDate);
String d = d1.toString();
public Vector getEmployee()throws Exception
{
Vector<Vector<String>> employeeVector = new Vector<Vector<String>>();
PreparedStatement pre = con.prepareStatement("select studentid,name from student");
ResultSet rs = pre.executeQuery();
while(rs.next())
{
Vector<String> employee = new Vector<String>();
employee.add(rs.getString(1)); //Empid
employee.add(rs.getString(2));//name
employee.add(d);
employeeVector.add(employee);
}
if(con!=null)
con.close();
rs.close();
pre.close();
return employeeVector;
}
}
**AttendanceGUI.java : **
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package shreesai;
import static java.awt.Frame.MAXIMIZED_BOTH;
import java.sql.Connection;
import java.util.Vector;
import javax.swing.JOptionPane;
/**
*
* #author Admin
*/
public class AttendanceGUI extends javax.swing.JFrame {
/**
* Creates new form AttendanceGUI
*/
Connection con = Connectdatabase.ConnecrDb();
private Vector<Vector<String>> data;
private Vector<String> header;
public AttendanceGUI() throws Exception {
this.setLocationRelativeTo(null);
setExtendedState(MAXIMIZED_BOTH);
Attendance att = new Attendance();
data = att.getEmployee();
header = new Vector<String>();
header.add("Student ID");
header.add("Student Name");
header.add("Date");
header.add("Absent/Present");
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() {
jScrollPane1 = new javax.swing.JScrollPane();
AttendanceT = new javax.swing.JTable();
SaveAtt = new javax.swing.JButton();
Exit = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
AttendanceT.setModel(new javax.swing.table.DefaultTableModel(
data,header
)
{public boolean isCellEditable(int row, int column){return true;}}
);
AttendanceT.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
TableColumnAdjuster tca = new TableColumnAdjuster(AttendanceT);
tca.adjustColumns();
AttendanceT.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
jScrollPane1.setViewportView(AttendanceT);
SaveAtt.setIcon(new javax.swing.ImageIcon(getClass().getResource("/save.png"))); // NOI18N
SaveAtt.setText("Save Attendance");
SaveAtt.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
SaveAttActionPerformed(evt);
}
});
Exit.setIcon(new javax.swing.ImageIcon(getClass().getResource("/exit.png"))); // NOI18N
Exit.setText("Exit");
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()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(SaveAtt, javax.swing.GroupLayout.PREFERRED_SIZE, 175, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(Exit, javax.swing.GroupLayout.PREFERRED_SIZE, 175, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(176, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(SaveAtt, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(Exit, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jScrollPane1, 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();
}// </editor-fold>
private void SaveAttActionPerformed(java.awt.event.ActionEvent evt) {
}
/**
* #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(AttendanceGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(AttendanceGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(AttendanceGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(AttendanceGUI.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() {
try{
new AttendanceGUI().setVisible(true);
}
catch(Exception e){
JOptionPane.showMessageDialog(null,e);
}
}
});
}
// Variables declaration - do not modify
private javax.swing.JTable AttendanceT;
private javax.swing.JButton Exit;
private javax.swing.JButton SaveAtt;
private javax.swing.JScrollPane jScrollPane1;
// End of variables declaration
}
This output I get when I run JFrame :
Now, What I want actually is whenever user will edit data into JTable just like in the following Image :
****After clicking Save Attendance button the current JTable values should entered into the database. I am using Sqlite database which is addon in Firefox. I have created attendance table in my database which is having studentid integer, name varchar, date DATETIME, and preab VARCHAR(This to store whether particular student was present or absent) ****
I hope that you get what my problem is. Thanks in advance.
As you are using DefaultTableModel you have to register a listener to that model a TableModelListener listening for changes. How to use TableModelListener
Example:
myTable.getModel().addTableModelListener(new TableModelListener(){
#Override
public void tableChanged(TableModelEvent evt){
//code here
}
});
public void happi(String name, String age, String id){
//this method should be located on a class, then you just instantiate the class in the main form
String query=null;
try{
query = "update tbltest set name = '"+name+"',age = '"+age+"' where id = '"+id+"'";
stmt.executeUpdate(query);
}
catch(Exception ex){JOptionPane.showMessageDialog(null,""+ex);}
finally{
super.closeConnection(connect);
super.closeStatement(stmt);
}
}//end of happi
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
//a button with event ActionPerformed (save button)
table.updateUI();
}//end
private void tablePropertyChange(java.beans.PropertyChangeEvent evt) {
// a JTablenamed"table"
try{
int row = table.getSelectedRow();
int column = table.getSelectedColumn();
int c = table.getColumnCount();
DBHandler dbh = new DBHandler();
dbh.happi((table.getModel().getValueAt(row, 0).toString()), (table.getModel().getValueAt(row, 1).toString()), (table.getModel().getValueAt(row, 2).toString()));
}catch(Exception e){}
} '