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.
Related
I am trying to make a login picture for my application using Timer. The idea is, when the user opens the application, he will see a picture for 5 seconds, then the application will start.
I tried, as you can see in the method shoutoff():
/*
* 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;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;
/**
*
* #author isslam
*/
public class login extends javax.swing.JFrame {
Timer time;
/**
* Creates new form login
*/
public login() {
initComponents();
setLocation(350, 200);
time = new Timer(5000,new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
dispose();
}
});
time.setRepeats(false);
}
public void shoutoff(){
if (!time.isRunning()) {
time.start();
}
}
/**
* 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() {
jLabel1 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setAlwaysOnTop(true);
setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
setLocationByPlatform(true);
setUndecorated(true);
setResizable(false);
jLabel1.setIcon(new javax.swing.ImageIcon("C:\\Users\\isslam\\Desktop\\one_piece_marble_play_by_iviarker-d511vb0.jpg")); // NOI18N
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
);
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(login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(login.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().setVisible(true);
new login().shoutoff();
}
});
}
// Variables declaration - do not modify
private javax.swing.JLabel jLabel1;
// End of variables declaration
}
Start by creating the Timer once in the constructor. The Timer should, also, only make the CURRENT instance of login close
public login() {
//...
time = new Timer(5000,new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
dispose();
}
});
timer.setRepeats(false);
}
In the shoutoff method, you start timer...
public void shoutoff(){
if (!time.isRunning()) {
timer.start();
}
}
Take a closer look at How to use Swing Timers for more details.
You might like to have a read through Code Conventions for the Java TM Programming Language, it will make it easier for people to read your code and for you to read others
The idea is, when the user opens the application, he will see a picture for 5 seconds, then the application will start.
You should use a Splash Screen. The advantage of the splash screen is the image is displayed immediately as the whole Swing app doesn't need to be loaded.
Check out the section from the Swing tutorial on How to Create a Splash Screen for more information and a working example.
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.
I am working on a login system that checks if the user is in a spesific usergroup.
If the user is in the usergroup "Access" then i want to show them the next form. If they are in the usergroup "registered user" it will display "Sorry, you dont have access"
This is my code so far: This will log in with 2 textboxes shown on a form.
I know i should not call "gettext();" on password field but i dont know how to code it so the htmlunit understands the characters and not puts in chars of array if i write "getpassword()"
/*
* 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 testmysql.gui;
import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.NicelyResynchronizingAjaxController;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.WebWindow;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlInput;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlPasswordInput;
import com.gargoylesoftware.htmlunit.html.HtmlSubmitInput;
/**
*
* #author Kjetil
*/
public class Login extends javax.swing.JFrame {
public String setuser;
public String setpass;
public char[] input;
/**
* Creates new form Login
*/
public Login() {
initComponents();
setLocationRelativeTo(null);
}
/**
* 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();
txtboxPass = new javax.swing.JPasswordField();
txtboxUser = new javax.swing.JTextField();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jButton1.setText("jButton1");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
getContentPane().add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 70, -1, -1));
txtboxPass.setText("jPasswordField1");
getContentPane().add(txtboxPass, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 40, -1, -1));
txtboxUser.setText("jTextField1");
getContentPane().add(txtboxUser, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 10, 110, -1));
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
setuser = txtboxUser.getText();
setpass = txtboxPass.getText();
Login();
}
/**
* #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.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Login.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().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JPasswordField txtboxPass;
private javax.swing.JTextField txtboxUser;
// End of variables declaration
private void Login()
{
try {
WebClient webClient = new WebClient(BrowserVersion.FIREFOX_24);
webClient.getOptions().setJavaScriptEnabled(true);
webClient.getOptions().setCssEnabled(false); // I think this speeds the thing up
webClient.getOptions().setRedirectEnabled(true);
webClient.setAjaxController(new NicelyResynchronizingAjaxController());
webClient.getCookieManager().setCookiesEnabled(true);
String url = "http://svergja.com/forum";
String name = setuser;
String pass = setpass;
HtmlPage page = webClient.getPage(url);
System.out.println(
"1st page : " + page.asText());
HtmlForm form = (HtmlForm) page.getElementById("navbar_loginform");
HtmlInput uName = (HtmlInput) form.getByXPath("//*[#id=\"navbar_username\"]").get(0);
uName.setValueAttribute(name);
HtmlPasswordInput password = (HtmlPasswordInput) form.getByXPath("//*[#id=\"navbar_password\"]").get(0);
password.setValueAttribute(setpass);
HtmlSubmitInput button = form.getInputByValue("Log in");
//(HtmlSubmitInput) form.getByXPath("//*[#id=\"loginbutton\"]").get(0);
WebWindow window = page.getEnclosingWindow();
button.click();
while (window.getEnclosedPage() == page) {
// The page hasn't changed.
Thread.sleep(500);
}
// This loop above will wait until the page changes.
page = (HtmlPage) window.getEnclosedPage();
System.out.println(
"2nd Page : " + page.asText());
webClient.closeAllWindows();
} catch (Exception ex) {
}
}
}
If the login is successful i want to start checking for the usergroup ID of the user. If i log in, my usergroup is Administrator. I will add a test user so you can log in and see for yourself.
(log in with this "you will be in the usergroup ("Registered Users")")
Forum url: http://svergja.com/forum
Username: stackoverflow
Password: stackit123
(test user information)
After the successfull login, use anchor to click profile link and then use span to get the usergroup.
The change in code will be:
private void Login() throws FailingHttpStatusCodeException, MalformedURLException, IOException
{
WebClient client = new WebClient();
client.setJavaScriptEnabled(false);
HtmlPage page = client.getPage("http://svergja.com/forum/");
HtmlForm form = (HtmlForm) page.getElementById("navbar_loginform");
HtmlTextInput username = (HtmlTextInput) page.getElementById("navbar_username");
username.setValueAttribute("stackoverflow");
HtmlPasswordInput password = (HtmlPasswordInput) page.getElementById("navbar_password");
password.setValueAttribute("stackit123");
HtmlSubmitInput button = form.getInputByValue("Log in");
page = button.click();
List<HtmlAnchor> anchorList = page.getAnchors();
for (HtmlAnchor htmlAnchor : anchorList) {
if(htmlAnchor.getAttribute("href").contains("member.php?"))
{
page = htmlAnchor.click();
}
}
HtmlSpan span = (HtmlSpan) page.getElementById("userinfo");
DomNodeList<DomNode> nodeList = span.getChildNodes();
for (DomNode domNode : nodeList) {
NamedNodeMap map = domNode.getAttributes();
Node node = map.getNamedItem("class");
if(node != null && node.getNodeValue() != null && node.getNodeValue().equals("usertitle"))
{
System.out.println("The usergroup is "+domNode.getTextContent());
}
}
}
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?
javax.swing.JTable has a bug,
if we sort the table while a null valued cell is editing,
and whose column class does not have a constructor with "new Object[] { new String() }" parameter, eg. Long.class,
the JTable will throw an exception.
I think that because javax.swing.JTable tries to remove the cell editor twice;
So I plan to override the JTable.columnMoved method as:
#Override
public void columnMoved(TableColumnModelEvent e) {
if (isEditing() && !getCellEditor().stopCellEditing()) {
if(getCellEditor() != null) { // In javax.swing.JTable, no this check point
getCellEditor().cancelCellEditing();
}
}
repaint();
}
I felt that's not good enough, since it's not friendly for code readers, they may know JTable well, and do not like my sub classes like this.
Is there a better solution?
Thanks a lot.
When running the following codes, double click one cell (do not input anything) and then click the header, the exception will show up.
public class NewJFrame extends javax.swing.JFrame {
public NewJFrame() {
initComponents();
}
#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, null},
{null, null},
{null, null},
{null, null}
},
new String [] {
"Title 1", "Title 2"
}
) {
Class[] types = new Class [] {
java.lang.Long.class, java.lang.Long.class
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
});
jScrollPane1.setViewportView(jTable1);
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(15, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 275, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(14, 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(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.JScrollPane jScrollPane1;
private javax.swing.JTable jTable1;
// End of variables declaration
}
I can reproduce the issue with the code you provided. I blame the JTable#stopCellEditing implementation
public boolean stopCellEditing() {
String s = (String)super.getCellEditorValue();
// Here we are dealing with the case where a user
// has deleted the string value in a cell, possibly
// after a failed validation. Return null, so that
// they have the option to replace the value with
// null or use escape to restore the original.
// For Strings, return "" for backward compatibility.
if ("".equals(s)) {
if (constructor.getDeclaringClass() == String.class) {
value = s;
}
super.stopCellEditing();
}
try {
value = constructor.newInstance(new Object[]{s});
}
catch (Exception e) {
((JComponent)getComponent()).setBorder(new LineBorder(Color.red));
return false;
}
return super.stopCellEditing();
}
You enter the first if, where super.stopCellEditing is called. The return value of this call is ignored. Then the newInstance call throws an exception, which is catched but then false is returned, no matter what the return value was of super.stopCellEditing. This sounds incorrect to me. I would log the bug with Oracle with the code you provided
I can't see any issue, any bug, TableCellEditor is canceled properly on sorting and column reordering,
import java.awt.*;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
public class TableWithTimer {
private static final long serialVersionUID = 1L;
private JFrame frame = new JFrame();
private JScrollPane scroll = new JScrollPane();
private JTable myTable;
private String[] head = {"One", "Two", "Three", "Four", "Five", "Six"};
private Object[][] data = {{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null}};
private DefaultTableModel model;
public TableWithTimer() {
model = new DefaultTableModel(data, head) {
private static final long serialVersionUID = 1L;
#Override
public Class<?> getColumnClass(int colNum) {
switch (colNum) {
case 0:
return Integer.class;
case 1:
return Double.class;
case 2:
return Long.class;
case 3:
return Boolean.class;
default:
return String.class;
}
}
};
myTable = new JTable(model);
myTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
myTable.setGridColor(Color.gray);
myTable.setFillsViewportHeight(true);
myTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
myTable.setAutoCreateRowSorter(true);
scroll.setViewportView(myTable);
frame.add(scroll, BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocation(100, 100);
frame.pack();
frame.setVisible(true);
}
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
TableWithTimer tableWithTimer = new TableWithTimer();
}
});
}
}
The issue - analyzed correctly by #Robin - has several aspects:
stopCellEditing incorrectly firing an editingStopped even when returning false
stopCellEditing firing twice if an empty value is accepted by the constructor
While the second is "just" violating its contract, the first has severe consequences:
as noted in the OP's question: throwing an NPE if client code tries to really terminate the edit, that is first stop and on failure cancel. Ironically, the most visible appearance is in jdk7 table.columnMoved - where the formerly (up to jdk6) incorrect removeEditor is replaced by the Right-Thing.
might lead to data corruption if the edit started with a valid value which is deleted while editing: the editingStopped event triggers the table to replace the valid value in the tableModel with null ...
Enough reason to fix in JXTable by different logic in GenericEditor (the fix can be used in a custom GenericEditor as well, no coupling to swingx: simply c&p core GenericEditor and replace its stopCellEditing with the following):
#Override
public boolean stopCellEditing() {
String s = (String) super.getCellEditorValue();
// JW: changed logic to hack around (core!) Issue #1535-swingx
// don't special case empty, but string contructor:
// if so, by-pass reflection altogether
if (constructor.getDeclaringClass() == String.class) {
value = s;
} else { // try instantiating a new Object with the string
try {
value = constructor.newInstance(new Object[] { s });
} catch (Exception e) {
((JComponent) getComponent()).setBorder(new LineBorder(
Color.red));
return false;
}
}
return super.stopCellEditing();
}