Refreshing counter in jLabel - java

Is there any way to refresh the counter in jLabel when a button
is on click? I tried with repaint(), revalidate() methods already but all does not work.
When like button is on click :
jButton_like.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
int count = 1;
eForumLikeCounter likeAmount = new eForumLikeCounter(
userName, topicId, count);
if (likeAmount.checkLikeAmount() == true) {
JOptionPane
.showMessageDialog(null,
"Unable to perform like on the same thread by the same user");
} else if (likeAmount.checkDislikeExists() == true) {
JOptionPane
.showMessageDialog(null,
"You can only either like or dislike this thread");
} else {
likeAmount.likeCounter();
}
}
});
}
Set up for database :
public void SetUpLikeDislikeAmount() {
int likes = 0;
int dislike = 0;
// Set Up Database Source
db.setUp("IT Innovation Project");
String sql = "Select likeDislike_likes,likeDislike_dislike from forumLikeDislike WHERE likeDislike_topics = "
+ topicId + "";
ResultSet resultSet = null;
// Call readRequest to get the result
resultSet = db.readRequest(sql);
try {
while (resultSet.next()) {
likes += resultSet.getInt("likeDislike_likes");
dislike += resultSet.getInt("likeDislike_dislike");
}
resultSet.close();
} catch (Exception e) {
System.out.println(e);
}
jLabel_like.setText(Integer.toString(likes));
jLabel_dislike.setText(Integer.toString(dislike));
}
Thanks in advance.

Just use the setText() method of the JLabel. Probably something like:
counter.setText("");
or
counter.setText("0");

Related

How to populate TableView which in it i can have radiobutton in javafx

Good day, I am trying to have a javafx tableView whereby i can also have radio button represented by the image below
NOTE: the radio button will be selected by the user while the other data will be fetched from the database.
The below image is what i have been able to achieve so far
with the aid of the below function.
private ObservableList<ObservableList> data;
Connection conn = null;
ResultSet rs = null;
PreparedStatement pst = null;
public void buildData() {
data = FXCollections.observableArrayList();
try {
conn = javaconnect.ConnectDb();
String SQL = "select id, questions from the_questions";
ResultSet rs = conn.createStatement().executeQuery(SQL);
for (int i = 0; i < rs.getMetaData().getColumnCount(); i++) {
//We are using non property style for making dynamic table
final int j = i;
TableColumn col = new TableColumn(rs.getMetaData().getColumnName(i + 1));
col.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<ObservableList, String>, ObservableValue<String>>() {
public ObservableValue<String> call(TableColumn.CellDataFeatures<ObservableList, String> param) {
return new SimpleStringProperty(param.getValue().get(j).toString());
}
});
questions.getColumns().addAll(col);
System.out.println("Column [" + i + "] ");
}
while (rs.next()) {
ObservableList<String> row = FXCollections.observableArrayList();
for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) {
row.add(rs.getString(i));
}
System.out.println("Row [1] added " + row);
data.add(row);
}
questions.setItems(data);
} catch (Exception e) {
e.printStackTrace();
System.out.println("Error on Building Data");
}
}
Will so much appreciate any illustration or assistance on how to get this done.
Thanks
Why not use gridpane instead? And it helps use CheckBoxTreeCell class https://docs.oracle.com/javafx/2/ui_controls/tree-view.htm
Anyway you can create your own TreeCellFactory for radiobutton. This will display a checkbox or a radiobutton as needed.
public class TreeCellFactory implements Callback<TreeView<Object>,TreeCell<Object>>
{
#Override
public TreeCell call( TreeView param )
{
return new TreeCell<Object>()
{
private final CheckBox check = new CheckBox();
private final RadioButton radio = new RadioButton();
private Property<Boolean> prevRadioProp;
{
setContentDisplay( ContentDisplay.GRAPHIC_ONLY );
}
#Override
public void updateItem( Object item, boolean empty )
{
if ( prevRadioProp != null )
{
radio.selectedProperty().unbindBidirectional( prevRadioProp );
prevRadioProp = null;
}
check.selectedProperty().unbind();
if ( ! empty && item != null )
{
Property<Boolean> selectedProp = ....;
if ( getTreeItem().isLeaf() ) // display radio button
{
radio.setText( ... );
radio.selectedProperty().bindBidirectional( selectedProp );
prevRadioProp = selectedProp;
setGraphic( radio );
}
else // display checkbox
{
check.setText( ... );
check.selectedProperty().bind( selectedProp );
setGraphic( check );
}
}
else
{
setGraphic( null );
setText( null );
}
}
};
}
}
Resources:
JavaFX: Making a Tree View with Radio Buttons
JavaFX: Radio Button + CheckBox TreeView

When I choose item in jList and use getSelectedIndex() it returns -1

I am trying to make a ToDoList , and I create a jButton to remove a Task from the Database ,when i check the index it always gives (-1)
if (jListTasks.getSelectedIndex() == -1) {
JOptionPane.showMessageDialog(null, "No task selected!!");
} else {
JOptionPane.showConfirmDialog(null, "Are you sure?!", "Remove task", JOptionPane.YES_NO_OPTION);}
update:
// set DefaultListModel
tasksListModel = new DefaultListModel();
jListTasks.setModel(tasksListModel);
Then I create this method
// to clear and fill list every time method invoked
private void fillTaskList() {
tasksListModel.clear();
try {
resultSet = pstmt.executeQuery();
while (resultSet.next()) {
// System.out.println("xxx");
tasksListModel.addElement("\"" + resultSet.getString("task_name") +
"\"" + " starts at " + resultSet.getString("start_time"));
}
} catch (SQLException ex) {
Logger.getLogger(ToDoFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
and this is the ActionListener of the RemoveButton
jbtnRemoveTask.addActionListener((ActionEvent e) -> {
// to fill the list with latest values in database
sqlQuery = "SELECT * FROM tasks";
try {
pstmt = connection.prepareStatement(sqlQuery);
fillTaskList();
} catch (SQLException ex) {
Logger.getLogger(ToDoFrame.class.getName()).log(Level.SEVERE, null, ex);
}
// to restore the Frame to default size as I change size during the using of application
if (ToDoFrame.this.getSize().width > 515 || ToDoFrame.this.getSize().height > 440) {
// implementation for these two methods comes at the end
decreaseHeight();
decreaseWidth();
}
// System.out.println(jListTasks.getLastVisibleIndex());
// System.out.println(jListTasks.getSelectedIndex());
// this code is always executed even there is item selected
if (jListTasks.getSelectedIndex() == -1) {
JOptionPane.showMessageDialog(null, "No task selected!!");
} else {
JOptionPane.showConfirmDialog(null, "Are you sure?!", "Remove task", JOptionPane.YES_NO_OPTION);
try {
// System.out.println(jListTasks.getSelectedValue());
String s = jListTasks.getSelectedValue().toString();
s = s.substring(s.length() - 5);
// System.out.println(s);
// the code for updating database
sqlUpdate = "DELETE FROM tasks WHERE start_time = ?";
pstmt = connection.prepareStatement(sqlUpdate);
pstmt.setString(1, s);
pstmt.executeUpdate();
JOptionPane.showMessageDialog(null, "Task removed successfully!");
sqlQuery = "SELECT * FROM tasks";
pstmt = connection.prepareStatement(sqlQuery);
fillTaskList();
} catch (SQLException ex) {
Logger.getLogger(ToDoFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
// here are the code of decreaseWidth and decreaseHeight methods
private void decreaseWidth() {
for (int i = ToDoFrame.this.getSize().width; i > 510; i -= 10) {
ToDoFrame.this.setSize(i, ToDoFrame.this.getSize().height);
ToDoFrame.this.setLocationRelativeTo(null);
try {
Thread.sleep(20);
} catch (InterruptedException ex) {
Logger.getLogger(ToDoFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
private void decreaseHeight() {
for (int i = ToDoFrame.this.getSize().height; i > 435; i -= 10) {
ToDoFrame.this.setSize(ToDoFrame.this.getSize().width, i);
ToDoFrame.this.setLocationRelativeTo(null);
try {
Thread.sleep(20);
} catch (InterruptedException ex) {
Logger.getLogger(ToDoFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Note: the code was working perfectly before making methods to re-size the Frame , when doing the re-sizing directly inside the ActionListener
Thanks for help
It looks like the action listener of your remove button calls the fillTaskList method before retrieving the selected index. The refill of the todo list will clear the selection in the list and the call to jListTasks.getSelectedIndex() will return -1.
I think you only need to update the todo list after removing the selected item.

am I overloading my actionListener? JFileChooser

I am attempting to load a saved file from JFileChooser using an actionListener. Here is a snippet of code.
class chooserListener implements ActionListener{
public void actionPerformed (ActionEvent e)
{
if (e.getSource() instanceof JFileChooser){
JFileChooser openFile = (JFileChooser)e.getSource();
String command = e.getActionCommand();
if (command.equals(JFileChooser.APPROVE_SELECTION)){
File selectedFile = openFile.getSelectedFile();
loadSavedGame(selectedFile);
System.out.print("clicked open file");
tp.setSelectedIndex(0);
}
else if (command.equals(JFileChooser.CANCEL_SELECTION)) {
System.out.print("tester");
tp.setSelectedIndex(0);
}
}
}
}
chooser.addActionListener(new chooserListener());
public void loadSavedGame(File loadfile) {
int allCells = countCells(loadfile);
setMineGame(allCells);
try {
Scanner loadFile = new Scanner(loadfile);
while (loadFile.hasNextInt()){
for (int i = 0; i < allCells; i++){
mineGame.setCell(i, loadFile.nextInt());
//System.out.print("loading saved game");
}
loadFile.close();
mineGame.repaint();
tp.setSelectedIndex(0);
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
private int countCells(File countCell) {
int cellCount = 0;
try {
Scanner getCells = new Scanner(countCell);
while (getCells.hasNextInt()){
cellCount++;
}
getCells.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.print(cellCount);
return cellCount;
}
public void setMineGame(int cells) {
game.removeAll();
mineGame.setDifficulty(cells);
mineGame = new Board(statusbar, difficulty);
game.add(mineGame, BorderLayout.CENTER);
game.add(statusbar, BorderLayout.SOUTH);
frame.validate();
frame.repaint();
}
public void setDifficulty(int cells){
if(cells == 256){
difficulty = 0;
}
if (cells == 676){
difficulty = 1;
}
else difficulty = 2;
}
I feel like I have too many methods for the action listener to do. It is hanging when I click 'open', and the test print line 'System.out.print("clicked open file");' does not print. the rest of my code is really large and I'm not sure how to to an SSCE(?). I'm wondering if anyone can see why my actionListener is hanging? thanks IA
It seems like loadSavedGame(File file) takes a lot of time to execute. As this method is running in the Event Dispatch Thread you feel like your program is hanging and never reaches System.out.print("clicked open file"); line. I'd start testing the time of response for this method in a separate test case
Anyway I'd suggest you a few tips:
1) Note there's no need to implement an ActionListener to do your code. You can simple make this:
JFileChooser chooser = new JFileChooser();
int returnValue = chooser.showOpenDialog(null);
if(returnValue == JFileChooser.APPROVE_OPTION){
//make stuff if approved
} else if(returnValue == JFileChooser.CANCEL_OPTION){
//make stuff if canceled
}
I think it makes people life easier.
2) On the other hand note you have two I/O operations: getting the cells count through countCells(File countCell) method and getting the cells themselves inside loadSavedGame(File loadfile) method. You can do it better reading the file just once:
public List<Integer> getCells(File file){
List<Integer> list = new ArrayList<>();
try {
Scanner getCells = new Scanner(file);
while (getCells.hasNextInt()){
list.add(Integer.valueOf(getCells.nextInt()));
}
getCells.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
return list;
}
}
And make this change in loadSavedGame method:
public void loadSavedGame(File loadfile) {
List<Integer> allCells = getCells(loadfile);
setMineGame(allCells.size());
int index = 0;
for(Integer value : allCells){
mineGame.setCell(index, value);
index++;
}
mineGame.repaint();
tp.setSelectedIndex(0);
}

Login page using java swing in netbeans

I am making a Login page using java swing in netbeans. When I'm trying to click the "login" button, after entering the credentials, the next page is not visible. I used NextPage().setVisible(true) to do this. Should i use anything else?
have you used actionListener() on the login page. use it to go to next page when login button is clicked and on the next page set it visible(true).
You have to use new Nextpage().setVisible(True);
This is how my login page gets data from the database
try{
Class.forName("java.sql.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost/restman","root","1234");
Statement stmt=con.createStatement();
String pq="select * from employeelogin";
ResultSet rs=stmt.executeQuery(pq);
String user=a1.getText();
String psw=a2.getText();
while(rs.next()){
String uname=rs.getString("username");
String password=rs.getString("password");
if ((user.equals(uname))&&(psw.equals(password))) {
new customerservice().setVisible(true);
this.setVisible(false);
} else {
p1.setVisible(true);
}
}
} catch(Exception x) {
JOptionPane.showMessageDialog(null,x.getMessage());
}
This is my piece of code. For login see from the last:
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
Connection conn=null;
try{
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException ex) {
Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
}
conn =DriverManager.getConnection(DB_URL, USER, PASS);
Statement stmt=conn.createStatement();
String S1 = jTextField1.getText();
String S2 = jPasswordField1.getText().toString();
String S3=jComboBox2.getSelectedItem().toString();
if(S1.isEmpty() || S1 == null){
JOptionPane.showMessageDialog(null, "Please insert a valid user name", "Warning", JOptionPane.WARNING_MESSAGE);
return;
}
// if password is blank, warning message shown
if(S2.isEmpty() || S2 == null){
JOptionPane.showMessageDialog(null, "Password field is empty", "Warning", JOptionPane.WARNING_MESSAGE);
return;
}
int flag=0;
String sql;
sql="SELECT * from member where EMAIL='"+S1+"'";
ResultSet rs=stmt.executeQuery(sql);
//System.out.println(rs.next());
String uname="",pw="",category="";
while(rs.next()){
uname=rs.getString("EMAIL");
pw=rs.getString("PASSWORD");
category=rs.getString("CATEGORY");
if(uname.matches(S1) && pw.equals(S2)==true && category.matches(S3))
{
flag=1;
if(jComboBox2.getSelectedItem()=="VISITOR")
{
setVisible(false);
Newvisitor f1= new Newvisitor(S1);
f1.getContentPane().setBackground(Color.darkGray);
f1.setVisible(true);
// jButton6.setVisible(true);
}
else if(jComboBox2.getSelectedItem()=="ACCOUNTANT")
{
setVisible(false);
inter4 f=new inter4();
f.getContentPane().setBackground(new java.awt.Color(153,153,255));
f.setVisible(true);
}
else if(jComboBox2.getSelectedItem()=="ADMINISTRATOR")
{
setVisible(false);
Admin f2=new Admin();
f2.getContentPane().setBackground(Color.darkGray);
f2.setVisible(true);
}
}
}
if(flag==0)
JOptionPane.showMessageDialog(null,"login failed");
stmt.close();
conn.close();
}
catch(SQLException ss){
ss.printStackTrace();
} `
}

Jtable content is visible through different tab

I have JTabbedPane with 4 tabs. JtabbedPane is situated on a JLayeredPane. 1st and 4th tab contain JTable with custom models. Each of the tables is being refreshed every 5-10 seconds.
When 1st tab is active, and JTable on 4th has just finished refreshing, I can see content of the 4th on the 1st. Look at the screenshot.
When I click on the other tab, or minimize window, that strange effect is gone. Till the next refresh of that table on 4th tab. Refreshing is done using Future<> object.
I used Swing GUI builder in Netbeans, so I have huge amount of code. Would post any piece which could be useful.
I tried to revalidate jTabbedPane, is had no effect. Both tables and jScrollPanes has opaque property set to true. So I tried to use SwingUtilities.invokeLater(). It helped a little bit - now first content update goes well, but later - the same problem.
2nd table model has method to update it's content
public void setData(LinkedList<Object[]> __rows) {
NewDevsTableModel.__rows = __rows;
fireTableDataChanged();
}
It is used here (I added SwingUtilities here)
static class checkNew implements Callable<Boolean> {
#Override
public Boolean call() {
ServiceMessage sm = ServiceMessage.getNewList();
try {
connect();
os.write(sm.serialize());
for (int i=0; i<10; i++) {
try {
Thread.sleep(300);
} catch (InterruptedException e) {}
if (is.available() > 0) {
break;
}
if (i == 9) {
disconnect();
return false;
}
}
byte[] actByte = new byte[is.available()];
is.read(actByte);
try {
sm = ServiceMessage.Deserialize(actByte); //may be there are no new devices
if (sm.getType() == ServiceMessageType.NODATA) {
MainWindow.jTabbedPane1.setEnabledAt(3, false);
if (MainWindow.jTabbedPane1.getSelectedIndex() == 3) {
MainWindow.jTabbedPane1.setSelectedIndex(0);
}
return true;
} else {
return false; //wrong answer type
}
} catch (ClassCastException | StreamCorruptedException e) {
//remember selection and scroll
final int scroll = MainWindow.jScrollPane3.getVerticalScrollBar().getValue();
final int[] rows = MainWindow.newDevsTable.getSelectedRows();
int col = MainWindow.devicesTable.getSelectedColumn();
String[] parts = new String(actByte).split("\n");
final LinkedList<Object[]> l = new LinkedList();
for (int i=0; i<parts.length; i++) {
String[] dev = parts[i].split(";", -1);
String descr = dev[2];
boolean iptype = (!dev[3].equals("-"));
String address = dev[4];
boolean atmtype = (dev[5].equals("+"));
if (MainWindow.newDevsTable.getRowCount() >= (i+1)) {
if ((MainWindow.newDevsTable.getValueAt(i, 4) != null) && !MainWindow.newDevsTable.getValueAt(i, 4).equals("")) {
descr = MainWindow.newDevsTable.getValueAt(i, 4).toString();
}
}
Object[] o = {dev[0], dev[1], MainWindow.language[180], MainWindow.language[4], descr, iptype, address, atmtype};
l.add(o);
}
if (!l.isEmpty()) {
SwingUtilities.invokeLater( new Runnable() {
#Override
public void run() {
MainWindow.newDevsPanel.setVisible(true);
MainWindow.jTabbedPane1.setEnabledAt(3, true);
((NewDevsTableModel)MainWindow.newDevsTable.getModel()).setData(l);
ButtonColumn buttonColumn = new ButtonColumn(MainWindow.newDevsTable, addAction, 2, true);
buttonColumn = new ButtonColumn(MainWindow.newDevsTable, rejAction, 3, false);
//put selection back
for (int i=0; i<rows.length; i++) {
MainWindow.newDevsTable.addRowSelectionInterval(rows[i], rows[i]);
}
MainWindow.jScrollPane3.getVerticalScrollBar().setValue(scroll);
}
});
} else {
MainWindow.jTabbedPane1.setEnabledAt(3, false);
if (MainWindow.jTabbedPane1.getSelectedIndex() == 3) {
MainWindow.jTabbedPane1.setSelectedIndex(0);
}
}
return true;
}
} catch (IOException e) {
disconnect();
return false;
} catch (ClassNotFoundException e) {
return false;
}
}
}
I submit the task this way
public static Future<Boolean> checkNewDevices() {
final Future<Boolean> task;
task = service.submit(new checkNew());
return task;
}
To refresh automatically I use separate thread
public class CheckNewPassThread extends Thread {
int pause = 10000;
#Override
public void run() {
for (;;) {
HostConnection.checkNewDevices();
try {
Thread.sleep(pause);
} catch (InterruptedException e) {}
}
}
}
Which is started when the window is opened
private void formWindowOpened(java.awt.event.WindowEvent evt) {
HostConnection.getData();
HostConnection.getDeviceAddress();
RefreshData refreshThread = new RefreshData();
refreshThread.start();
new CheckNewPassThread().start();
}
OMG, the problem was in calling jTabbedPane.setEnabledAt(3, true) to already enabled tab. Swing is fascinating

Categories