Connect JProgress Bar to an array to show progress of the tool - java

I've created a tool where I paste some data in a text area and this data is being split per lines by (\n) in an array.
My tool works perfect, I just need to connect this progress of the array to the progress bar so the user may know what's going on.
so if the array will have 10 lines the progress bar shall start from one and count till it reaches ten when the tool moves to the next line.
so I mean when it starts working on the array in position 0, the progress bar shall show 1, and when the array moved to position 1, progress bar shall show 2 .......
Here is an example of my code:
// Run button (start the search)
final JButton btn = new JButton("Run");
btn.addActionListener(new ActionListener() {
#SuppressWarnings("resource")
public void actionPerformed(ActionEvent e) {
try {
String getTextArea;
getTextArea = textArea.getText();
// converting the input to an array
String[] arr = getTextArea.split("\\n");
// clearing the text
textArea_1.setText("");
//line = arr.length;
// looping for the input
// doing something.....
}
// end of for loop
} catch (Exception e2) {
JOptionPane.showMessageDialog(null, "Search was not completed due to bad connection, please try pressing run again or close the tool and reopen it");
}
}
});
// Creating the progress bar
JProgressBar progressBar = new JProgressBar();
progressBar.setStringPainted(true);
progressBar.setValue(0);
for(int z = 0; z <= line; z++) {
progressBar.setValue(z);
z = z + 1;
progressBar.repaint();
}
progressBar.setBounds(364, 11, 139, 22);
contentPane.add(progressBar);
Thank you for your help in advance

I've interpreted your question as how do I get the line number to be displayed instead of the percentage?
If that is the question, then you need to use the JProgressBar's setString(String s) method as well as setValue(int n)
For example:
// Set up of the JProgressBar
final int MIN = 0;
final int MAX = 100;
JProgressBar progressBar = new JProgressBar(MIN, MAX);
progressBar.setStringPainted(true); // show the text on the progress bar
progressBar.setString("Loop no. " + MIN); // initial display
// Code to update the JProgressBar
for (int i=MIN; i<=MAX; i++) {
progressBar.setValue(i);
progressBar.setString("Loop no. " + i);
}
Personally I prefer to use an implementation of BoundedRangeModel when working with progress bars. Swing provides DefaultBoundedRangeModel which is good for most tasks.
Remember to use concurrency correctly in your implementation, otherwise your interface will be unrespsonive if the task is long. SwingWorker can assist you with this https://docs.oracle.com/javase/7/docs/api/javax/swing/SwingWorker.html

Related

Adding a new button after an event

Writing a program to increment a counter when a +1 button is pressed, then when the counter reaches a certain number, remove the +1 button and replace it with a +2 button and so on. I create both buttons at first but just set btnCount1 to setVisible(false). When the certain number passes, I make btnCount invisible and btnCount1 visible and increment by two from there. When it reaches 10 clicks, the btnCount disappears, but btnCount1 does not appear.
I have tried making an if(arg0.equals(btnCount1)), and incrementing by two from there. I tried putting the add(btnCount1) inside the else if statement to create it after the elseif condition is true.
public class AWTCounter extends Frame implements ActionListener
private Label lblCount;
private TextField tfCount;
private Button btnCount;
private Button btnCount1;
private int count = 0;
public AWTCounter() {
setLayout(new FlowLayout());
lblCount = new Label("Counter");
add(lblCount);
tfCount = new TextField(count + "",10);
tfCount.setEditable(false);
add(tfCount);
btnCount = new Button("Add 1");
btnCount1 = new Button("Add 2");
add(btnCount);
add(btnCount1);
btnCount1.setVisible(false);
btnCount.addActionListener(this);
btnCount1.addActionListener(this);
setTitle("AWT Counter");
setSize(500,500);
}
public static void main(String[]args) {
AWTCounter app = new AWTCounter();
}
public void actionPerformed(ActionEvent arg0) {
if(count <= 10) {
++count; //Increase the counter value
tfCount.setText(count + "");
}else if(count > 10) {
btnCount.setVisible(false);
btnCount1.setVisible(true);
count += 2;
tfCount.setText(count + "");
}
}
The better solution here is to just have one button object and a separate variable for the current increment amount. When you hit the required count, increase the increment amount and change the button's label to the new value.
There are also a few other things you could do better here.
Use String.valueOf() instead of int + "" for String representations of integers if you're not adding words before or after the integer.
Don't add obvious comments for code. (e.g. 'increment variable x', 'set textString to the new value')
Use descriptive names for method parameters and variables.
Use Labels instead of TextFields for text that doesn't need to be editable or selectable like counter displays.
I'd personally change the name of lblCount to something like lblTitle as well, since changing your tfCount to a Label would logically take up that name and lblTitle makes more sense.
Here's a better way to implement actionPerformed:
private int increment = 1;
private Label lblCount;
...
public void actionPerformed(ActionEvent ignore) {
if(count == 10) {
btnCount.setLabel("Add " + (++increment));
}
lblCount.setText(String.valueOf(count += increment));
}

Java Listener for looped combo in Eclipse SWT

I have a Java SWT GUI that I've built using Eclipse. I'm using a while loop to reference a text file. The while loop iterates through each line of the text file and builds a series of combo or text boxes for specific items on each line. Each line represents one visual column in the GUI and, depending on how many items I have in the text file, the GUI builds to the right. For simplicity's sake I am including just the code that I am trying to figure out.
For instance, assume I have three lines that create six combo boxes in the GUI (three columns by two rows). I would like a change on the top row in the second column to execute a Listener on the bottom row, also in the second column. However, right now the Listener loops through all of the combo's and makes a change to all three, not just the one I want. I can't figure out how to make this work. See the code below. I appreciate the help.
private void buildMultipleSatPulldowns() {
try {
FileReader fr = new FileReader("MultipleSatellites.txt");
BufferedReader br = new BufferedReader(fr);
String line = null;
String[] tempS;
String constellation = null;
String satellite = null;
while ((line = br.readLine()) != null) {
tempS = line.split("~");
constellation = tempS[4];
satellite = tempS[6];
constNameCombo = new Combo(satellitesComposite2, SWT.NONE);
constNameCombo.setToolTipText("Pulldown constellation name");
constNameCombo.setBounds(startX + x2, 71, 125, 28);
constNameCombo.setItems(constNameArray);
constNameCombo.setText(constellation);
constNameCombos.add(constNameCombo);
constNameCombo.addModifyListener(new ModifyListener() { // captures changed combo values
public void modifyText(ModifyEvent arg0) {
setConstellationPD();
}
});
sPullDown(constellation); // builds the satellite array for the constellation and populates each pulldown
satNameCombo = new Combo(satellitesComposite2, SWT.NONE);
satNameCombo.setToolTipText("Pulldown satellite name");
satNameCombo.setBounds(startX + x2, 106, 125, 28);
satNameCombo.setItems(satNameArray);
satNameCombo.setText(satellite);
satNameCombos.add(satNameCombo);
startX = startX + nextX;
}
br.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
private void setConstellationPD() {
int constellations = 0;
for (Combo constNameCombo : constNameCombos) {
// What do I do here so that only the desired satNameCombo changes to reflect the desired pull down?
setSatellitesPD(constellations, constNameCombo)
constellations++;
}
}
private void setSatellitesPD(int c, String cN) {
int satellites = 0;
for (Combo satNameCombo : satNameCombos) {
if (c == satellites) {
satNameCombo.setText(satNameCombos.get(satellites).toString());
satNameCombo.removeAll();
sPullDown(cN);
satNameCombo.setText("select Satellite");
}
satellites++;
}
}
private void sPullDown(String cName) {
// sPullDown takes the constellation name and returns a String Array of all objects in the constellation. This code works correctly when called.
}
If I understood correctly, you need a way to know which combo fired the event in order to affect some other components.
SWT events like ModifyEvent have the method getSource() which will return the object on which the event occurred.
Having that you just need to properly identify it; for example you could simply use constNameCombos.indexOf(eventCombo) to retrieve its index.
Or, more efficiently, you could attach some data to your combos with the method setData and retrieve it inside the event with getData, for example inside the loop:
// "i" would be the index of the combo
constNameCombo.setData("index", i);
i++;
and in the event:
Combo eventCombo = (Combo) arg0.getSource();
int index = eventCombo.getData("index");
With these information you should be able to identify the other components that you want to change.

Clear button only makes counter JLabel blank but does not reset it.

I have made this application:
For example when I click on the clear button when the counter JLabel (pointsAvailable) is 19 then the counter JLabel goes blank as expected, however when I start adding points again it starts from 19 not 40 as set on the start. I would like to make it to reset back to 40 instead of just making it blank
Code for the clear button
private void JButtonActionPerformed(java.awt.event.ActionEvent evt) {
speedPoints.setText("");
attackPoints.setText("");
defencePoints.setText("");
powerPoints.setText("");
agilityPoints.setText("");
focusPoints.setText("");
availablePoints.setText("");
}
Code for Jlabel counter
public class addingPointsUI extends javax.swing.JFrame {
int pointsAvailable=40;
int speed=0;
int power=0;
int focus=0;
int agility=0;
int defence=0;
int attack=0;
Code for buttons +/-: to allow me to add or decrease value "example power - button"
private void powerMinusActionPerformed(java.awt.event.ActionEvent evt) {
if (power > 0 ){
if (pointsAvailable <= 0) {
JOptionPane.showMessageDialog(null, "You are out of available points");
return;
}
power = power - 1;
pointsAvailable = pointsAvailable +1;
availablePoints.setText(String.valueOf(pointsAvailable));
powerPoints.setText(String.valueOf(power));
}else {
JOptionPane.showMessageDialog(null,"You cannot take anymore points from Power");
}
}
Thank your for your kind replies.
Use a JSpinner with SpinnerNumberModel. Change the value of the model. The component will update and further changes will act on the current value of the model.
I can quickly think of two solutions:
1. In the event handler of your clear button include the following:
private void JButtonActionPerformed(ActionEvent evt){
...
pointsAvailable=40;
speed=0;
power=0;
focus=0;
agility=0;
defence=0;
attack=0;
}
This will reset all of your stats.
2. Or you can add an if statement to the listeners of every button that adds or subtracts a stat that will check if the specific statistic is empty. For example, for the speed buttons the code would look like so:
if (speedPoints.getText() == ""){
pointsAvailable += speed;
speed = 0;
}
Found my own solution on google:
private void ClearActionPerformed(java.awt.event.ActionEvent evt) {
speedPoints.setText(String.valueOf(0));
powerPoints.setText(String.valueOf(0));
agilityPoints.setText(String.valueOf(0));
defencePoints.setText(String.valueOf(0));
focusPoints.setText(String.valueOf(0));
attackPoints.setText(String.valueOf(0));
availablePoints.setText(String.valueOf(40));
}
Works perfectly

How to update a ProgressBar and stop It when I want?

In first, I'm using Eclipse IDE. So my question is: I create a progress bar, but I want to make it load according to the place where the program is. I have a refresh button, and when I click it my entire program update. What I want is a progress bar that accompanying the process of updating and ends when it ends.
Sorry if my English isn't the best, but I'm a young Portuguese developer.
my btn code
JButton btnActualizar = new JButton("\u21BB");
btnActualizar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
TxtIpExternoLoja.setText(" ");
TxtSSIDLoja.setText(" ");
TxtFirewallLoja.setText(" ");
TxtIpLojaEtho.setText(" ");
TxtMaskLojaEtho.setText(" ");
TxtGWLojaEtho.setText(" ");
TxtDns1LojaEtho.setText(" ");
TxtDns2LojaEtho.setText(" ");
TxtIpLojaWlan.setText(" ");
TxtMaskLojaWlan.setText(" ");
TxtGwLojaWlan.setText(" ");
TxtDns1LojaWlan.setText(" ");
TxtDns2LojaWlan.setText(" ");
TxtIpLojaVpn.setText(" ");
TxtMaskLojaVpn.setText(" ");
TxtGwLojaVpn.setText(" ");
TxtDns1LojaVpn.setText(" ");
TxtDns2LojaVpn.setText(" ");
// DefaultTableModel model = (DefaultTableModel)
// tablePing.getModel();
// model.setRowCount(0);
TxtTime.setText(" ");
i = 0;
t.start();
btnActualizar.setEnabled(false);
update();
}
});
my progressbar code:
JProgressBar progressBar = new JProgressBar(0, 15);
GridBagConstraints gbc_progressBar = new GridBagConstraints();
gbc_progressBar.insets = new Insets(0, 0, 0, 5);
gbc_progressBar.gridx = 3;
gbc_progressBar.gridy = 0;
PanelBotoes.add(progressBar, gbc_progressBar);
GridBagConstraints gbc_btnImprimir = new GridBagConstraints();
gbc_btnImprimir.insets = new Insets(0, 0, 0, 5);
gbc_btnImprimir.gridx = 5;
gbc_btnImprimir.gridy = 0;
PanelBotoes.add(btnImprimir, gbc_btnImprimir);
progressBar.setStringPainted(true);
progressBar.setValue(0);
t = new Timer(interval, new ActionListener() {
public void actionPerformed(ActionEvent ae) {
if (i == 15) {
t.stop();
btnActualizar.setEnabled(true);
} else {
i++;
progressBar.setValue(i);
}
}
});
Take a look at this page: https://docs.oracle.com/javase/tutorial/uiswing/components/progress.html.
Specifically, the section on "Using Determinate Progress Bars" should be what you are looking for. The example code is a little complex, but probably about as simple as it can get with this stuff.
Take note: the example uses a SwingWorker (more on those here) to update the progress value. This is because the progress bar is drawn in the Swing thread and won't be updated if the process is running on that thread too.
You will need to update your program on a thread which is not the Swing thread.
Edit 1 - For your question update with code
So it looks like you've got the idea with the progress bar code. I've not run it, but what you've got looks like it should work. Your next step is to replace the timer with the update() methods process.
To do this you'll need to do the following:
Make sure your update() method is running in a thread separate from the swing thread (something like a SwingWorker could be used here).
From within the update thread you need to call progressBar.setValue(x) when you want to update the bar, where x = how far your process has got.
Add some more calls to progressBar.setValue(x) in the update thread. You can put these wherever you like, but it's probably best to put them before and after long processes.
Note: you have to use threads for progress bars. This means you could run into things like deadlock and race conditions. Be careful!

Issues with JtextArea. JAVA

I have a GUI setup with with buttons on them and a JTextArea.
I also have an array of Strings with say size of 3.
What I want to do is use an action listener in a way that when the button called "next" is pressed, the JTextArea will then show the next cell in the array. The only problem is it displays the array at the same time. I need it to display the next cell when the button is hit
Can anyone help me with the code? Please and thank you.
final ActionListener m2 = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e)
{
arr = new String[3];
arr[0]= "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
arr[1]= "sssssssssssssssssssssss";
arr[2]= "xxxxxxxxxxxxxxxxxxxxx";
for (int i = 0; i<arr.length; i++){
text.append(arr[i]);
}
}
};
next.addActionListener(m2);
So the basic concept is. You need a index value to maintain the current index of the array that is being displayed.
From there, each time the user clicks next, you would increment the index and display the next value in the String
public void actionPerformed(ActionEvent e) {
currentIndex++;
// You need to decide what to do when we reach the end of the array...
String value = myStrings[currentIndex];
textArea.setText(value);
}
To create the button, use the JButton class. To respond to events, use the JButton#addActionListener() method. If you are having trouble, post what you have tried. Good luck!

Categories