I have a client and server. Server sends some questions to the Client. In client side I want to display these questions on a SWT application window.
I use one thread to show the window and main thread contacts with the Server. After client receives the questions, NullPointerException is thrown in text widget. (writeQuestions method below). I think "q1Txt" is not null because it is initiated in "createContets" method. Besides the arraylist that have question is not null too because I checked it.
Can you help me about it?
My code is below.
public class Client {
protected static Shell shell;
private static Text q1txt;
private static Text q2txt;
private static Text q3txt;
private static Text q4txt;
private static Text q5txt;
private static Text ans1txt;
private static Text ans2txt;
private static Text ans3txt;
private static Button ans5YesBtn;
private static Button ans4NoBtn;
private static Button ans4YesBtn;
private static Button ans5NoBtn;
private static ArrayList<Integer> ansList = new ArrayList<Integer>();
private static boolean isAnswered = false;
static String name;
static int socketNum;
static Socket socket;
public static int l = 4;
public static void main(String[] args) throws InterruptedException {
new Screen().start();
try {
socket = new Socket("", 9898);
ObjectOutputStream objOut = new ObjectOutputStream(socket.getOutputStream());
ObjectInputStream objIn = new ObjectInputStream(socket.getInputStream());
objOut.writeObject("8080");
ArrayList<String> questions = (ArrayList<String>) objIn.readObject();
writeQuestions(questions);
while(!isAnswered)
Thread.sleep(2000);
socket.close();
} catch (UnknownHostException e) {
System.err.println("There is not like this company!");
} catch (IOException e) {
System.err.println("Company does not answer!");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void writeQuestions(ArrayList<String> questions){
q1txt.setText(questions.get(0)); // The exception point is here
q2txt.setText(questions.get(1));
q3txt.setText(questions.get(2));
q4txt.setText(questions.get(3));
q5txt.setText(questions.get(4));
}
private static class Screen extends Thread {
public void run() {
open();
}
}
public static void open(){
Display display = Display.getDefault();
createContents();
shell.open();
shell.layout();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
}
protected static void createContents() {
shell = new Shell();
shell.setSize(499, 369);
shell.setText("SWT Application");
shell.setLayout(null);
Composite questionsComp = new Composite(shell, SWT.NONE);
questionsComp.setBounds(10, 10, 373, 298);
q1txt = new Text(questionsComp, SWT.BORDER | SWT.READ_ONLY);
q1txt.setBounds(0, 0, 259, 21);
q2txt = new Text(questionsComp, SWT.BORDER | SWT.READ_ONLY);
q2txt.setBounds(0, 51, 259, 21);
q3txt = new Text(questionsComp, SWT.BORDER | SWT.READ_ONLY);
q3txt.setBounds(0, 95, 259, 21);
q4txt = new Text(questionsComp, SWT.BORDER | SWT.READ_ONLY);
q4txt.setBounds(0, 140, 259, 21);
q5txt = new Text(questionsComp, SWT.BORDER | SWT.READ_ONLY);
q5txt.setBounds(0, 189, 259, 21);
ans1txt = new Text(questionsComp, SWT.BORDER);
ans1txt.setBounds(272, 0, 58, 21);
ans2txt = new Text(questionsComp, SWT.BORDER);
ans2txt.setBounds(272, 51, 58, 21);
ans3txt = new Text(questionsComp, SWT.BORDER);
ans3txt.setBounds(272, 95, 58, 21);
Group ans4group = new Group(questionsComp, SWT.NONE);
ans4group.setBounds(265, 121, 97, 47);
ans4group.setLayout(null);
ans4YesBtn = new Button(ans4group, SWT.RADIO);
ans4YesBtn.setBounds(10, 20, 39, 16);
ans4YesBtn.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent e) {
}
});
ans4YesBtn.setText("Yes");
ans4NoBtn = new Button(ans4group, SWT.RADIO);
ans4NoBtn.setBounds(55, 20, 39, 16);
ans4NoBtn.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent e) {
}
});
ans4NoBtn.setText("No");
Group ans5Group = new Group(questionsComp, SWT.NONE);
ans5Group.setBounds(265, 176, 97, 47);
ans5NoBtn = new Button(ans5Group, SWT.RADIO);
ans5NoBtn.setBounds(55, 21, 39, 16);
ans5NoBtn.setText("No");
ans5YesBtn = new Button(ans5Group, SWT.RADIO);
ans5YesBtn.setBounds(10, 21, 39, 16);
ans5YesBtn.setText("Yes");
Button btnGainCalculation = new Button(questionsComp, SWT.NONE);
btnGainCalculation.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent e) {
//controls all answers
if(ans1txt.getText().equals("") || ans2txt.getText().equals("") || ans3txt.getText().equals("")){
MessageDialog.openWarning(shell, "Warning", "Please answer all questions.");
}else if((!ans4NoBtn.getSelection() && !ans4YesBtn.getSelection()) || (!ans5NoBtn.getSelection() && !ans5YesBtn.getSelection())){
MessageDialog.openWarning(shell, "Warning", "Please answer all questions.");
}else if(!isNumeric(ans1txt.getText()) || !isNumeric(ans2txt.getText()) || !isNumeric(ans3txt.getText()) ){
MessageDialog.openWarning(shell, "Warning", "Please answer correctly.");
}else
isAnswered = true;
}
}
);
btnGainCalculation.setBounds(0, 236, 97, 25);
btnGainCalculation.setText("Gain Calculation");
}
public static boolean isNumeric(String str)
{
return str.matches("-?\\d+(\\.\\d+)?"); //match a number with optional '-' and decimal.
}
}
I'm pretty sure the problem is the later execution for the "createContent".
We need to ensure that component will use after it creation
Try this:
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
public class Client{
protected static Shell shell;
private static Text q1txt;
private static Text q2txt;
private static Text q3txt;
private static Text q4txt;
private static Text q5txt;
private static Text ans1txt;
private static Text ans2txt;
private static Text ans3txt;
private static Button ans5YesBtn;
private static Button ans4NoBtn;
private static Button ans4YesBtn;
private static Button ans5NoBtn;
private static ArrayList<Integer> ansList = new ArrayList<Integer>();
private static boolean isAnswered = false;
static String name;
static int socketNum;
static Socket socket;
public static int l = 4;
public static void main(String[] args) throws InterruptedException {
Screen screen = new Screen();
screen.setCreationComplete(new CreationCompleteAction());
}
private static class Screen extends Thread {
Runnable creationCompleteAction;
public void setCreationComplete(Runnable action){
this.creationCompleteAction = action;
}
public void run() {
Display display = Display.getDefault();
createContents();
if(creationCompleteAction != null){
creationCompleteAction.run();
}
shell.open();
shell.layout();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
}
}
public static class CreationCompleteAction implements Runnable {
#Override
public void run() {
try {
socket = new Socket("", 9898);
ObjectOutputStream objOut = new ObjectOutputStream(socket.getOutputStream());
ObjectInputStream objIn = new ObjectInputStream(socket.getInputStream());
objOut.writeObject("8080");
ArrayList<String> questions = (ArrayList<String>) objIn.readObject();
writeQuestions(questions);
while (!isAnswered)
Thread.sleep(2000);
socket.close();
} catch (UnknownHostException e) {
System.err.println("There is not like this company!");
} catch (IOException e) {
System.err.println("Company does not answer!");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void writeQuestions(ArrayList<String> questions) {
q1txt.setText(questions.get(0)); // The exception point is here
q2txt.setText(questions.get(1));
q3txt.setText(questions.get(2));
q4txt.setText(questions.get(3));
q5txt.setText(questions.get(4));
}
private static class Screen extends Thread {
public void run() {
Display display = Display.getDefault();
createContents();
shell.open();
shell.layout();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
}
}
protected static void createContents() {
shell = new Shell();
shell.setSize(499, 369);
shell.setText("SWT Application");
shell.setLayout(null);
Composite questionsComp = new Composite(shell, SWT.NONE);
questionsComp.setBounds(10, 10, 373, 298);
q1txt = new Text(questionsComp, SWT.BORDER | SWT.READ_ONLY);
q1txt.setBounds(0, 0, 259, 21);
q2txt = new Text(questionsComp, SWT.BORDER | SWT.READ_ONLY);
q2txt.setBounds(0, 51, 259, 21);
q3txt = new Text(questionsComp, SWT.BORDER | SWT.READ_ONLY);
q3txt.setBounds(0, 95, 259, 21);
q4txt = new Text(questionsComp, SWT.BORDER | SWT.READ_ONLY);
q4txt.setBounds(0, 140, 259, 21);
q5txt = new Text(questionsComp, SWT.BORDER | SWT.READ_ONLY);
q5txt.setBounds(0, 189, 259, 21);
ans1txt = new Text(questionsComp, SWT.BORDER);
ans1txt.setBounds(272, 0, 58, 21);
ans2txt = new Text(questionsComp, SWT.BORDER);
ans2txt.setBounds(272, 51, 58, 21);
ans3txt = new Text(questionsComp, SWT.BORDER);
ans3txt.setBounds(272, 95, 58, 21);
Group ans4group = new Group(questionsComp, SWT.NONE);
ans4group.setBounds(265, 121, 97, 47);
ans4group.setLayout(null);
ans4YesBtn = new Button(ans4group, SWT.RADIO);
ans4YesBtn.setBounds(10, 20, 39, 16);
ans4YesBtn.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent e) {
}
});
ans4YesBtn.setText("Yes");
ans4NoBtn = new Button(ans4group, SWT.RADIO);
ans4NoBtn.setBounds(55, 20, 39, 16);
ans4NoBtn.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent e) {
}
});
ans4NoBtn.setText("No");
Group ans5Group = new Group(questionsComp, SWT.NONE);
ans5Group.setBounds(265, 176, 97, 47);
ans5NoBtn = new Button(ans5Group, SWT.RADIO);
ans5NoBtn.setBounds(55, 21, 39, 16);
ans5NoBtn.setText("No");
ans5YesBtn = new Button(ans5Group, SWT.RADIO);
ans5YesBtn.setBounds(10, 21, 39, 16);
ans5YesBtn.setText("Yes");
Button btnGainCalculation = new Button(questionsComp, SWT.NONE);
btnGainCalculation.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent e) {
//controls all answers
if (ans1txt.getText().equals("") || ans2txt.getText().equals("") || ans3txt.getText().equals("")) {
MessageDialog.openWarning(shell, "Warning", "Please answer all questions.");
} else if ((!ans4NoBtn.getSelection() && !ans4YesBtn.getSelection()) || (!ans5NoBtn.getSelection() && !ans5YesBtn.getSelection())) {
MessageDialog.openWarning(shell, "Warning", "Please answer all questions.");
} else if (!isNumeric(ans1txt.getText()) || !isNumeric(ans2txt.getText()) || !isNumeric(ans3txt.getText())) {
MessageDialog.openWarning(shell, "Warning", "Please answer correctly.");
} else
isAnswered = true;
}
});
btnGainCalculation.setBounds(0, 236, 97, 25);
btnGainCalculation.setText("Gain Calculation");
}
public static boolean isNumeric(String str) {
return str.matches("-?\\d+(\\.\\d+)?"); //match a number with optional '-' and decimal.
}
}
Related
I have looked around for a while to add a system which delays the GUI text area only but to no avail, so far I have this:
public void msg2(String msg) {
for (int i = 0; i < msg.length(); i++) {
mainTextController.append(Character.toString(msg.charAt(i)));
try {
Thread.sleep(45);
} catch (Exception ex) {
ex.printStackTrace();
}
}
mainTextController.append("\n");
}
the problem here is that whenever i run this method it works and the type-writer effect is there, but, the entire program halts until the sleep method is over.
I have tried BlockingQueue but the same results are shown.
I am not looking to be spoon fed just some insight on how can I overcome this problem.
this is the entire class:
package gui;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.wb.swt.SWTResourceManager;
public class LabyrinthGUI {
protected Shell shell;
private Text mainTextController;
/**
* Launch the application.
*
* #param args
*/
public static void main(String[] args) {
try {
LabyrinthGUI window = new LabyrinthGUI();
window.open();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Open the window.
*/
Display display;
public void open() {
display = Display.getDefault();
createContents();
shell.open();
shell.layout();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
}
/**
* Create contents of the window.
*/
Button btnGoNorth;
protected void createContents() {
shell = new Shell();
shell.setBackground(SWTResourceManager.getColor(SWT.COLOR_BLACK));
shell.setSize(600, 700);
shell.setText("Murat's Labyrinth - v0.1");
mainTextController = new Text(shell, SWT.READ_ONLY | SWT.WRAP);
mainTextController.setDragDetect(false);
mainTextController.setDoubleClickEnabled(false);
mainTextController.setCursor(SWTResourceManager.getCursor(SWT.CURSOR_ARROW));
mainTextController.setEditable(false);
mainTextController.setFont(SWTResourceManager.getFont("System", 9, SWT.NORMAL));
mainTextController.setForeground(SWTResourceManager.getColor(SWT.COLOR_YELLOW));
mainTextController.setBackground(SWTResourceManager.getColor(SWT.COLOR_BLACK));
mainTextController.setBounds(10, 10, 564, 535);
btnGoNorth = new Button(shell, SWT.BORDER);
btnGoNorth.setSelection(true);
btnGoNorth.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent e) {
msg2("You clicked here");
}
});
btnGoNorth.setGrayed(true);
btnGoNorth.setTouchEnabled(true);
btnGoNorth.setFont(SWTResourceManager.getFont("System", 9, SWT.NORMAL));
btnGoNorth.setBounds(227, 551, 75, 25);
btnGoNorth.setText("Go North");
Button btnGoSouth = new Button(shell, SWT.BORDER);
btnGoSouth.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent e) {
}
});
btnGoSouth.setText("Go South");
btnGoSouth.setFont(SWTResourceManager.getFont("System", 9, SWT.NORMAL));
btnGoSouth.setBounds(227, 626, 75, 25);
Button btnGoWest = new Button(shell, SWT.BORDER);
btnGoWest.setText("Go West");
btnGoWest.setFont(SWTResourceManager.getFont("System", 9, SWT.NORMAL));
btnGoWest.setBounds(134, 587, 75, 25);
Button btnGoEast = new Button(shell, SWT.BORDER);
btnGoEast.setText("Go East");
//btnGoEast.setCursor(new Cursor());
btnGoEast.setFont(SWTResourceManager.getFont("System", 9, SWT.NORMAL));
btnGoEast.setBounds(328, 587, 75, 25);
}
public void lock() {
btnGoNorth.setEnabled(false);
}
public void unlock() {
btnGoNorth.setEnabled(true);
}
public void msg2(String msg) {
for (int i = 0; i < msg.length(); i++) {
mainTextController.append(Character.toString(msg.charAt(i)));
try {
Thread.sleep(45);
} catch (Exception ex) {
ex.printStackTrace();
}
}
mainTextController.append("\n");
}
}
the entire program halts until the sleep method is over.
Don't use Thread.sleep().
Instead you should be using a Swing Timer for animation.
Read the section from the Swing tutorial on How to Use Swing Timers for more information and working examples.
I am currently making a very simple Java GUI application, but have run into the problem that my variables are unable to update. The application is a simple basketball scorekeeper and the score integers do not update nor does the text of the labels showing them. There are no errors so I am unsure as of why nothing is updating. The code:
ScoreWindow.java
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.SpringLayout;
import javax.swing.JLabel;
import java.awt.Font;
import java.awt.FlowLayout;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
public class ScoreWindow implements ScoreListener {
private JFrame frmScorewindow;
public volatile JLabel homeScoreLabel;
public JLabel awayScoreLabel;
public volatile int homeScore, awayScore;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ScoreWindow window = new ScoreWindow();
window.frmScorewindow.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public ScoreWindow() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
// Init Scores
homeScore = 0;
awayScore = 0;
frmScorewindow = new JFrame();
frmScorewindow.setResizable(false);
frmScorewindow.setTitle("Score Keeper");
frmScorewindow.setBounds(100, 100, 551, 348);
frmScorewindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmScorewindow.getContentPane().setLayout(null);
JButton homeScore2 = new JButton("+2");
homeScore2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ScoreListener listener = new ScoreWindow();
listener.homeScore(2);
}
});
homeScore2.setBounds(110, 129, 117, 29);
frmScorewindow.getContentPane().add(homeScore2);
JButton homeScore3 = new JButton("+3");
homeScore3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ScoreListener listener = new ScoreWindow();
listener.homeScore(3);
}
});
homeScore3.setBounds(110, 156, 117, 29);
frmScorewindow.getContentPane().add(homeScore3);
JButton awayScore2 = new JButton("+2");
awayScore2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ScoreListener listener = new ScoreWindow();
listener.awayScore(2);
}
});
awayScore2.setBounds(332, 129, 117, 29);
frmScorewindow.getContentPane().add(awayScore2);
JButton awayScore3 = new JButton("+3");
awayScore3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ScoreListener listener = new ScoreWindow();
listener.awayScore(3);
}
});
awayScore3.setBounds(332, 156, 117, 29);
frmScorewindow.getContentPane().add(awayScore3);
JButton resetButton = new JButton("Reset");
resetButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ScoreListener listener = new ScoreWindow();
listener.reset();
}
});
resetButton.setBounds(225, 220, 117, 29);
frmScorewindow.getContentPane().add(resetButton);
homeScoreLabel = new JLabel("000");
homeScoreLabel.setFont(new Font("Lucida Grande", Font.PLAIN, 24));
homeScoreLabel.setHorizontalAlignment(SwingConstants.CENTER);
homeScoreLabel.setBounds(138, 88, 61, 29);
frmScorewindow.getContentPane().add(homeScoreLabel);
awayScoreLabel = new JLabel("000");
awayScoreLabel.setHorizontalAlignment(SwingConstants.CENTER);
awayScoreLabel.setFont(new Font("Lucida Grande", Font.PLAIN, 24));
awayScoreLabel.setBounds(361, 88, 61, 29);
frmScorewindow.getContentPane().add(awayScoreLabel);
JLabel lblHome = new JLabel("Home");
lblHome.setHorizontalAlignment(SwingConstants.CENTER);
lblHome.setBounds(138, 60, 61, 16);
frmScorewindow.getContentPane().add(lblHome);
JLabel lblAway = new JLabel("Away");
lblAway.setHorizontalAlignment(SwingConstants.CENTER);
lblAway.setBounds(361, 60, 61, 16);
frmScorewindow.getContentPane().add(lblAway);
JLabel title = new JLabel("Score Keeper App");
title.setHorizontalAlignment(SwingConstants.CENTER);
title.setBounds(180, 33, 200, 16);
frmScorewindow.getContentPane().add(title);
}
#Override
public void reset() {
print("reset();");
homeScore = 0;
awayScore = 0;
awayScoreLabel.setText("" + awayScore);
homeScoreLabel.setText("" + homeScore);
}
#Override
public void awayScore(int n) {
print("awayScore();");
awayScore+=n;
awayScoreLabel.setText("" + awayScore);
}
#Override
public void homeScore(int n) {
print("homeScore();");
print(homeScoreLabel.getText());
homeScore = homeScore + n;
homeScoreLabel.setText("" + homeScore);
homeScoreLabel.repaint();
homeScoreLabel.revalidate();
}
static void print(Object o) {
System.out.println(o);
}
}
ScoreListener.java
public interface ScoreListener {
public void reset();
public void awayScore(int n);
public void homeScore(int n);
}
Thank you!!
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ScoreWindow window = new ScoreWindow();
window.frmScorewindow.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
You create your window with the above code.
JButton homeScore2 = new JButton("+2");
homeScore2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ScoreListener listener = new ScoreWindow();
listener.homeScore(2);
}
});
But then you create a second instance of the window.
Don't do this. You only need to create once instance of your class. All other code to reference this instance.
Your ActionListner class is defined in the ScoreWindow class you you can just reference the "homeScore()" method directly.
I want to disable button btnCopyFolder when i clicked the btnSearchFile
here is my code:
package org.eclipse.wb.swt;
import java.nio.file.Path;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.DateTime;
import org.eclipse.swt.widgets.DirectoryDialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.ProgressBar;
import org.eclipse.swt.widgets.List;
import org.eclipse.swt.widgets.MessageBox;
public class MainUI {
private Text txtSource;
private static Text txtDestination;
protected Shell shell;
private static Text text1;
static DateTime ddFrom;
static Button btnCopyFolder;
static String text = "" ;
static String text2 = "" ;
/**
* Open the window.
*/
public void open() {
Display display = Display.getDefault();
createContents();
shell.open();
shell.layout();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
}
/**
* Create contents of the window.
*/
protected void createContents() {
shell = new Shell();
shell.setSize(450, 400);
shell.setText("Connection Manager");
final DateTime ddFrom = new DateTime (shell, SWT.DROP_DOWN | SWT.BORDER);
final DateTime ddTo = new DateTime (shell, SWT.DROP_DOWN | SWT.BORDER);
text = String.format("%02d/%02d/%04d",ddFrom.getDay(),ddFrom.getMonth() + 1,ddFrom.getYear());
text2 = String.format("%04d%02d%02d",ddTo.getYear(), ddTo.getMonth() + 1, ddTo.getDay());
// final DateTime time = new DateTime (shell,SWT.TIME | SWT.SHORT);
Label lblNewLabel = new Label(shell, SWT.NONE);
lblNewLabel.setFont(SWTResourceManager.getFont("Segoe UI", 12, SWT.NORMAL));
lblNewLabel.setBounds(10, 0, 107, 25);
lblNewLabel.setText("Source File ");
Button btnSearchFile = new Button(shell, SWT.NONE);
btnSearchFile.setBounds(103, 30, 107, 25);
btnSearchFile.setText("Search File");
btnSearchFile.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
FileDialog fd = new FileDialog(shell, SWT.MULTI);
String firstFile = fd.open();
btnCopyFolder.setVisible(false);
if (firstFile != null) {
String[] selectedFiles = fd.getFileNames();
File file = new File(firstFile);
for (int ii = 0; ii < selectedFiles.length; ii++ )
{
if (file.isFile())
{
displayFiles(new String[] { file.toString()});
}
else
displayFiles(file.list());
}
}
}
});
txtSource = new Text(shell, SWT.BORDER | SWT.MULTI | SWT.V_SCROLL );
txtSource.setBounds(10, 61, 414, 34);
Label lblNewLabel_1 = new Label(shell, SWT.NONE);
lblNewLabel_1.setFont(SWTResourceManager.getFont("Segoe UI", 11, SWT.NORMAL));
lblNewLabel_1.setBounds(10, 96, 107, 18);
lblNewLabel_1.setText("Destination File");
final Button btnSearchDirectory = new Button(shell, SWT.NONE);
btnSearchDirectory.setText("Search Directory");
btnSearchDirectory.setBounds(216, 31, 107, 25);
btnSearchDirectory.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
DirectoryDialog dlg = new DirectoryDialog(shell);
dlg.setFilterPath(txtSource.getText());
dlg.setMessage("Select a source file to transfer");
String dir = dlg.open();
if (dir != null) {
txtSource.setText(dir);
}
}
});
Button btnSearchDestination = new Button(shell, SWT.NONE);
btnSearchDestination.setBounds(10, 120, 75, 25);
btnSearchDestination.setText("Search");
btnSearchDestination.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
DirectoryDialog dialog = new DirectoryDialog(shell, SWT.SAVE);
dialog.setFilterPath(txtDestination.getText());
String dir = dialog.open();
if(dir != null){
txtDestination.setText(dir);
}
}
});
txtDestination = new Text(shell, SWT.BORDER);
txtDestination.setBounds(10, 151, 414, 25);
txtDestination.setText("");
Label lblNewLabel_2 = new Label(shell, SWT.NONE);
lblNewLabel_2.setBounds(10, 182, 81, 15);
lblNewLabel_2.setText("Date Range:");
Button btnCopyFile = new Button(shell, SWT.NONE);
btnCopyFile.setBounds(86, 253, 75, 25);
btnCopyFile.setText("Copy File");
btnCopyFile.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
File srcFolder = new File(txtSource.getText());
File destFolder = new File(txtDestination.getText());
if(!srcFolder.exists()){
MessageBox msgBox = new MessageBox(shell, SWT.ICON_INFORMATION | SWT.OK);
msgBox.setText("Information");
msgBox.setMessage("Directory does not exist.");
msgBox.open();
txtSource.setText("");
txtDestination.setText("");
}else{
if(txtDestination.getText().isEmpty())
{
MessageBox msgBox = new MessageBox(shell, SWT.ICON_WARNING | SWT.OK);
msgBox.setText("Warning");
msgBox.setMessage("Invalid Path..");
msgBox.open();
txtSource.setText("");
txtDestination.setText("");
}
else
{
try {
copyFolder1(srcFolder,destFolder);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
text1.append("Finished Copying.....\n");
MessageBox msgBox = new MessageBox(shell, SWT.ICON_INFORMATION | SWT.OK);
msgBox.setText("Information");
msgBox.setMessage("Done Copying...");
msgBox.open();
}
text1.append("");
}
}
});
Button btnCancel = new Button(shell, SWT.NONE);
btnCancel.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent arg0)
{
text = String.format("%02d/%02d/%04d",ddFrom.getDay(),ddFrom.getMonth() + 1,ddFrom.getYear());
text2 = String.format("%04d%02d%02d",ddTo.getYear(), ddTo.getMonth() + 1, ddTo.getDay());
String txt = ("Date Range is: " + " From "+ text + " : " + " To " + text2 + "\n");
text1.append(txt);
txtSource.setText("");
txtDestination.setText("");
}
});
btnCancel.setBounds(167, 253, 75, 25);
btnCancel.setText("Cancel");
Label label = new Label(shell, SWT.SEPARATOR | SWT.HORIZONTAL);
label.setBounds(0, 288, 434, 13);
Label lblFrom = new Label(shell, SWT.NONE);
lblFrom.setBounds(50, 203, 55, 15);
lblFrom.setText("From");
//DateTime ddFrom = new DateTime(shell, SWT.DROP_DOWN);
ddFrom.setBounds(50, 224, 119, 23);
Label label_1 = new Label(shell, SWT.NONE);
label_1.setFont(SWTResourceManager.getFont("Segoe UI", 13, SWT.NORMAL));
label_1.setBounds(199, 222, 22, 25);
label_1.setText(":");
//DateTime ddTo = new DateTime(shell, SWT.NONE);
ddTo.setBounds(233, 224, 119, 23);
Label lblTo = new Label(shell, SWT.NONE);
lblTo.setText("To");
lblTo.setBounds(233, 203, 55, 15);
text1 = new Text(shell, SWT.BORDER | SWT.READ_ONLY | SWT.H_SCROLL | SWT.V_SCROLL | SWT.MULTI);
text1.setText("Progress\n");
text1.setEnabled(true);
text1.setBounds(0, 302, 434, 59);
Button btnCopyFolder = new Button(shell, SWT.NONE);
btnCopyFolder.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent arg0) {
File srcFolder = new File(txtSource.getText());
File destFolder = new File(txtDestination.getText());
if(!srcFolder.exists()){
MessageBox msgBox = new MessageBox(shell, SWT.ICON_INFORMATION | SWT.OK);
msgBox.setText("Information");
msgBox.setMessage("Directory does not exist.");
msgBox.open();
txtSource.setText("");
txtDestination.setText("");
}else{
if(txtDestination.getText().isEmpty())
{
MessageBox msgBox = new MessageBox(shell, SWT.ICON_WARNING | SWT.OK);
msgBox.setText("WARNING");
msgBox.setMessage("Invalid Path...");
msgBox.open();
txtSource.setText("");
txtDestination.setText("");
}
else
{
try {
copyFolder(srcFolder,destFolder);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
text1.append("Finished Copying.....\n");
MessageBox msgBox = new MessageBox(shell, SWT.ICON_INFORMATION | SWT.OK);
msgBox.setText("Information");
msgBox.setMessage("Done Copying...");
msgBox.open();
}
}
}
});
btnCopyFolder.setText("Copy Folder");
btnCopyFolder.setBounds(248, 253, 75, 25);
}
public void displayFiles(String[] files) {
for (int i = 0; files != null && i < files.length; i++) {
txtSource.setText(files[i]);
txtSource.setEditable(true);
}
}
public static void copyFolder(File src, File dest)
throws IOException{
if(src.isDirectory()){
if (!dest.exists())
{
dest.mkdir();
text1.append("Directory created : " + dest + "\n");
}
final String files[] = src.list();
for (String file : files)
{
File srcFile = new File(src, file);
File destFile = new File(dest, file);
//Recursive function call
copyFolder(srcFile, destFile);
}
}
else{
text1.append("");
Files.copy(src.toPath(), dest.toPath(), StandardCopyOption.REPLACE_EXISTING);
text1.append(text + " Copying " + src.getAbsolutePath() + "\n");
//
}
}
public static void copyFolder1(File src, File dest)
throws IOException{
// String fileName = new SimpleDateFormat("yyyyMMddHHmm'.txt'").format(new DateTime(ddFrom, 0));
if(src.isDirectory()){
if (!dest.exists())
{
dest.mkdir();
text1.append("Directory created : " + dest + "\n");
}
String files[] = src.list();
for (String file : files)
{
File srcFile = new File(src, file);
File destFile = new File(dest, file);
//Recursive function call
copyFolder1(srcFile, destFile);
}
}
else{
if(dest.isDirectory())
{
copyFile(src, new File (dest, src.getName()));
text1.append(text + " Copying " + src.getAbsolutePath() + "\n");
}
else
{
copyFile(src, dest);
}
// }
}
}
public static void copyFile(File src, File dest) throws IOException
{
InputStream oInStream = new FileInputStream(src);
OutputStream oOutStream = new FileOutputStream(dest);
// Transfer bytes from in to out
byte[] oBytes = new byte[1024];
int nLength;
BufferedInputStream oBuffInputStream = new BufferedInputStream( oInStream );
while ((nLength = oBuffInputStream.read(oBytes)) > 0)
{
oOutStream.write(oBytes, 0, nLength);
}
oInStream.close();
oOutStream.close();
}
/**
* Launch the application.
* #param args
*/
public static void main(String[] args) {
try {
MainUI window = new MainUI();
window.open();
} catch (Exception e) {
e.printStackTrace();
}
}
}
and this is the error
java.lang.NullPointerException
at org.eclipse.wb.swt.MainUI$1.widgetSelected(MainUI.java:87)
at org.eclipse.swt.widgets.TypedListener.handleEvent(Unknown Source)
at org.eclipse.swt.widgets.EventTable.sendEvent(Unknown Source)
at org.eclipse.swt.widgets.Widget.sendEvent(Unknown Source)
at org.eclipse.swt.widgets.Display.runDeferredEvents(Unknown Source)
at org.eclipse.swt.widgets.Display.readAndDispatch(Unknown Source)
at org.eclipse.wb.swt.MainUI.open(MainUI.java:56)
at org.eclipse.wb.swt.MainUI.main(MainUI.java:370)
this is the line where the error came from
btnCopyFolder.setVisible(false); //line 100
You are shadowing the field btnCopyFolder with this code
Button btnCopyFolder = new Button(shell, SWT.NONE);
change to
btnCopyFolder = new Button(shell, SWT.NONE);
I'm starting with Socket Server in Java. I've written already simple app where I can send text between hosts. I'm sending with my message name of the host which is sending and here is my problem, how can I get host message?
Can someone just change my code to show host name instead of message?
Here is the code:
public class FMain extends JFrame {
private JPanel contentPane = null;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
FMain frame = new FMain();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public FMain() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 508, 321);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
PReceiver receiver = new PReceiver();
receiver.setBorder(new LineBorder(new Color(0, 0, 0)));
receiver.setBounds(35, 13, 423, 106);
contentPane.add(receiver);
PSender sender = new PSender((String) null, 0);
sender.setBorder(new LineBorder(new Color(0, 0, 0)));
sender.setBounds(35, 132, 423, 129);
contentPane.add(sender);
}
}
And the class which is receiving:
interface MyListener {
void messageReceived(String theLine);
}
class Receiver {
private List < MyListener > ml = new ArrayList < MyListener > ();
private Thread t = null;
private int port = 0;
private ServerSocket s = null;
private boolean end = false;
public void stop() {
t.interrupt();
try {
s.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void start() {
end = false;
t = new Thread(new Runnable() {
#Override
public void run() {
try {
s = new ServerSocket(port);
while (true) {
Socket sc = s.accept();
InputStream is = sc.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String theLine = br.readLine();
ml.forEach((item) - > item.messageReceived(theLine));
sc.close();
}
} catch (SocketException e) {} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
t.start();
}
public void addMyListener(MyListener m) {
ml.add(m);
}
public void removeMyListener(MyListener m) {
ml.remove(m);
}
Receiver(int port) {
this.port = port;
}
}
public class PReceiver extends JPanel implements MyListener {
private JTextField txtPort;
private Receiver r = null;
private JTextField txtMessage;
/**
* Create the panel.
*/
public PReceiver() {
setLayout(null);
txtPort = new JTextField();
txtPort.setBounds(282, 13, 62, 22);
add(txtPort);
// txtPort.setColumns(10);
JLabel lblPort = new JLabel("port:");
lblPort.setBounds(241, 16, 35, 16);
add(lblPort);
JToggleButton btnListen = new JToggleButton("Listen");
btnListen.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
if (btnListen.isSelected()) {
r = new Receiver(Integer.parseInt(txtPort.getText()));
r.addMyListener(PReceiver.this);
r.start();
} else {
r.stop();
}
}
});
btnListen.setBounds(265, 70, 79, 25);
add(btnListen);
JLabel lblMessage = new JLabel("message");
lblMessage.setBounds(12, 51, 56, 16);
add(lblMessage);
txtMessage = new JTextField();
txtMessage.setBounds(12, 71, 220, 22);
add(txtMessage);
//txtMessage.setColumns(10);
}
#Override
public void messageReceived(String theLine) {
txtMessage.setText(theLine);
}
}
And the sender class:
class Sender {
public void send(String message, String host, int port) {
Socket s;
try {
s = new Socket(host, port);
OutputStream out = s.getOutputStream();
PrintWriter pw = new PrintWriter(out, false);
pw.println(message);
pw.flush();
pw.close();
s.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public class PSender extends JPanel {
private JTextField txtMessage;
private JTextField txtHost;
private JTextField txtPort;
private JLabel lblMessage;
/**
* Create the panel.
*/
public PSender(String host, int port) {
setLayout(null);
txtMessage = new JTextField();
txtMessage.setBounds(12, 77, 216, 22);
add(txtMessage);
//txtMessage.setColumns(10);
JButton btnSend = new JButton("Send");
btnSend.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
new Sender().send(txtMessage.getText(), txtHost.getText(), Integer.parseInt(txtPort.getText()));
} catch (NumberFormatException e) {
e.printStackTrace();
}
}
});
btnSend.setBounds(268, 76, 78, 25);
add(btnSend);
txtHost = new JTextField();
txtHost.setBounds(51, 13, 149, 22);
add(txtHost);
//txtHost.setColumns(10);
txtPort = new JTextField();
txtPort.setBounds(268, 13, 78, 22);
add(txtPort);
//txtPort.setColumns(10);
JLabel lblHost = new JLabel("host:");
lblHost.setBounds(12, 16, 35, 16);
add(lblHost);
JLabel lblPort = new JLabel("port:");
lblPort.setBounds(231, 16, 35, 16);
add(lblPort);
lblMessage = new JLabel("message");
lblMessage.setBounds(12, 58, 56, 16);
add(lblMessage);
}
}
I am creating a program that will take the data from several textboxes store in an array and when a next and previous button are pressed display the next or last position in the array, currently the next button gets stuck in a while loop without displaying and I'm not sure how to fix it, I am an amateur and I need help with this.
package major;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JLabel;
import java.awt.List;
import java.awt.Label;
import javax.swing.JScrollPane;
import javax.swing.JList;
import javax.swing.JButton;
import javax.swing.JScrollBar;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
public class gui {
private JFrame frame;
private JTextField websitetxt;
private JTextField usernametxt;
private JTextField passwordtxt;
private encryptedData[] dataArray;
private int dataArrayMaxIndex;
private int dataArrayMax;
private int dataArrayCurrentIndex;
private JButton btnadd;
private JButton btnnew;
private JButton btndelete;
private JTextField notestxt;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
gui window = new gui();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public gui() {
initialize();
dataArrayMax = 20;
dataArray = new encryptedData[dataArrayMax];
dataArrayMaxIndex = 0;
while (dataArrayMaxIndex < dataArrayMax) {
dataArray[dataArrayMaxIndex] = new encryptedData();
dataArrayMaxIndex++;
}
dataArrayMaxIndex = -1;
dataArrayCurrentIndex = -1;
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 569, 427);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
websitetxt = new JTextField();
websitetxt.setBounds(315, 56, 191, 38);
frame.getContentPane().add(websitetxt);
websitetxt.setColumns(10);
usernametxt = new JTextField();
usernametxt.setColumns(10);
usernametxt.setBounds(315, 105, 191, 38);
frame.getContentPane().add(usernametxt);
passwordtxt = new JTextField();
passwordtxt.setColumns(10);
passwordtxt.setBounds(315, 154, 191, 38);
frame.getContentPane().add(passwordtxt);
JLabel lblWebsite = new JLabel("Website:");
lblWebsite.setBounds(227, 68, 78, 14);
frame.getContentPane().add(lblWebsite);
JLabel lblUsername = new JLabel("Username:");
lblUsername.setBounds(227, 117, 78, 14);
frame.getContentPane().add(lblUsername);
JLabel lblPassword = new JLabel("Password:");
lblPassword.setBounds(227, 166, 78, 14);
frame.getContentPane().add(lblPassword);
final JButton btnadd = new JButton("Add to Database");
btnadd.setEnabled(false);
btnadd.setBounds(10, 105, 191, 38);
frame.getContentPane().add(btnadd);
JLabel lblPasswordManagerHsc = new JLabel("Password manager hsc 2014");
lblPasswordManagerHsc.setBounds(191, 11, 168, 14);
frame.getContentPane().add(lblPasswordManagerHsc);
final JButton btnnew = new JButton("New Record");
btnnew.setBounds(10, 56, 191, 38);
frame.getContentPane().add(btnnew);
JButton btndelete = new JButton("Delete Record");
btndelete.setBounds(10, 154, 191, 38);
frame.getContentPane().add(btndelete);
JButton btnprev = new JButton("Prev");
btnprev.setBounds(315, 316, 89, 23);
frame.getContentPane().add(btnprev);
JButton btnnext = new JButton("Next");
btnnext.setBounds(417, 316, 89, 23);
frame.getContentPane().add(btnnext);
notestxt = new JTextField();
notestxt.setBounds(315, 203, 191, 102);
frame.getContentPane().add(notestxt);
notestxt.setColumns(10);
JLabel lblnotes = new JLabel("Notes");
lblnotes.setBounds(227, 215, 46, 14);
frame.getContentPane().add(lblnotes);
JButton btngenerate = new JButton("Generate Password");
btngenerate.setBounds(10, 203, 191, 38);
frame.getContentPane().add(btngenerate);
JMenuBar menuBar = new JMenuBar();
frame.setJMenuBar(menuBar);
JMenu File = new JMenu("File");
menuBar.add(File);
JMenuItem save = new JMenuItem("Save");
File.add(save);
JMenuItem load = new JMenuItem("Load");
File.add(load);
JMenuItem mntmHelp = new JMenuItem("About");
File.add(mntmHelp);
websitetxt.setEnabled(false);
usernametxt.setEnabled(false);
passwordtxt.setEnabled(false);
notestxt.setEnabled(false);
btnadd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
btnadd.setEnabled(false);
dataArrayCurrentIndex++;
dataArrayMaxIndex++;
dataArray[dataArrayCurrentIndex].username = usernametxt.getText();
dataArray[dataArrayCurrentIndex].password = passwordtxt.getText();
dataArray[dataArrayCurrentIndex].notes = notestxt.getText();
dataArray[dataArrayCurrentIndex].website = websitetxt.getText();
}
});
btnnew.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnnew) {
websitetxt.setEnabled(true);
usernametxt.setEnabled(true);
passwordtxt.setEnabled(true);
notestxt.setEnabled(true);
btnadd.setEnabled(true);
websitetxt.setText("");
usernametxt.setText("");
passwordtxt.setText("");
notestxt.setText("");
}
}
});
btndelete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnprev.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnnext.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = 0;
while (i < dataArrayMaxIndex) {
dataArrayCurrentIndex = i;
websitetxt.setText(dataArray[i].getWebsitename());
usernametxt.setText(dataArray[i].getUsername());
passwordtxt.setText(dataArray[i].getPassword());
notestxt.setText(dataArray[i].getNotes());
}
i++;
}
});
}
}
package major;
public class encryptedData {
public String website;
public String username;
public String password;
public String notes;
public encryptedData() {
try {
website = "";
username = "";
password = "";
notes = "";
} catch (Exception e) {
}
}
public encryptedData(String w, String u, String p, String n) {
try {
website = w;
username = u;
password = p;
notes = n;
} catch (Exception e) {
}
}
//Access methods
public String getWebsitename() {
return website;
}
public void setWebsiteName(String w) {
website = w;
}
public String getUsername() {
return username;
}
public void setUsername(String u) {
username = u;
}
public String getPassword() {
return password + "";
}
public void setPassword(String p) {
password = p;
}
public String getNotes() {
return notes + "";
}
public void setNotes(String n) {
notes = n;
}
}
You are incrementing i after the while loop in actionPerformed()!
If you had formatted your code better, this would have been obvious:
btnnext.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = 0;
while (i<dataArrayMaxIndex) {
dataArrayCurrentIndex = i;
websitetxt.setText(dataArray[i].getWebsitename());
usernametxt.setText(dataArray[i].getUsername());
passwordtxt.setText(dataArray[i].getPassword());
notestxt.setText(dataArray[i].getNotes());
}
i++;
}
});
And this would have been even better:
btnnext.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
for (int i = 0; i<dataArrayMaxIndex; i++) {
dataArrayCurrentIndex = i;
websitetxt.setText(dataArray[i].getWebsitename());
usernametxt.setText(dataArray[i].getUsername());
passwordtxt.setText(dataArray[i].getPassword());
notestxt.setText(dataArray[i].getNotes());
}
}
});