Not so new anymore more with Java but as it gets more advanced (for me that at least) the tricks evade me. I would like to output sorted values into my GUI but two things are not happening.
1. Cannot get values to print in GUI but prints on screen OK.
(note line 26)
2. Cannot get sorted random values but sorts manual inputs OK.
(note line 23)
import java.awt.*; // Supplies layout manager
import java.awt.event.*; // Supplies event classes
import javax.swing.*; // Supplies class JApplet
import java.util.*; // Supplies class Scanner
import java.applet.*; // Supplies class Applet
public class RandomIntegers extends JApplet implements ActionListener {
public void actionPerformed(ActionEvent event) {
// Event handler
int value;
value = Integer.parseInt(inputField.getText());
inputField.setText("");
//outLabel.setText("List size = " + value + "\n values sorted are: ");
// Generate random integers and apply sort method
Random randomGenerator = new Random();
for (int i = 1; i <= 10; ++i) {
int randomInt = randomGenerator.nextInt(value);
// Assign random list to array
int listItems[] = { randomInt };
// Manual value assignment sorts as expected
//int listItems[] = {23,27,74,2,99,69,94,18,83,10};
sorting(listItems, listItems.length);
for (int index = 0; index < listItems.length; index++)
System.out.print(listItems[index] + " "); // need these results in GUI
outLabel.setText("List size = " + value);
outLabel2.setText("The values sorted are: ");
}
}
// The sorting method process
public static void sorting( int array[], int length ) {
int index = 0; // Index through array
int counter = 0; // Smaller value
int temp = 0; // Temp position
// Loop through each element of the array
for(index = 0; index < length; index++) {
// Once for each element minus the counter
for(counter = 1; counter < (length-index); counter++) {
// Test if need to swap or not
if(array[counter-1] > array[counter]) {
// Next three lines just swap the two elements
temp = array[counter-1];
array[counter-1] = array[counter];
array[counter] = temp;
}
}
}
}
// Set up a button, label, and input field
private JTextField inputField;
private JLabel label;
private JLabel outLabel;
private JLabel outLabel2;
private JButton button;
public void init() {
// Instantiate the GUI components
JLabel label;
label = new JLabel ("Enter value:");
outLabel = new JLabel ("List size");
outLabel2 = new JLabel ("Sorted values");
inputField = new JTextField("0");
JButton button;
button = new JButton("Enter");
button.addActionListener(this);
add(label);
add(inputField);
add(button);
add(outLabel);
add(outLabel2);
// Specify layout manager
setLayout(new GridLayout(0,1));
}
}