error with DataOutputStream - java

I keep getting an NullPointerException, and I dont know why. what the class is supposed to do, is to send whatever I write in my jtextfield as writeUTF, but I keep getting a NullPointerException at
dos = new DataOutputStream(socket.getOutputStream());
The GUI code:
public class GUI {
private JFrame frame = new JFrame("Dryck & Ingrediens"); // GUI
private JTextField jtf = new JTextField();// GUI
private JTextArea jl1 = new JTextArea();// GUI
private JList jl = new JList();// GUI
private JScrollPane js = new JScrollPane(jl);// GUI
private DataOutputStream dos;// ServerHandler
private JLabel lab = new JLabel("Ange dryck");//GUI
private JLabel lab1 = new JLabel("Walid Shams");
private JLabel lab2 = new JLabel("Kushtrim Brahimi");
private HashMap<String, ArrayList<String>> drinkar = null;//Controller
private DataInputStream dis;
private Socket socket;
private ServerHandler serverH;
public GUI() {
frame.getContentPane().setLayout(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBounds(50, 300, 420, 400);
frame.setResizable(false);
frame.setVisible(true);
js.add(jl);
js.add(jl1);
jl1.setEditable(false);
lab.setBounds(170, 20, 130, 20);
lab1.setBounds(300, 310, 130, 20);
lab2.setBounds(300, 330, 130,20);
jtf.setBounds(130, 40, 150, 40);
jl.setBounds(50, 90, 150, 200);
jl1.setBounds(210, 90, 150, 200);
Container con = frame.getContentPane();
con.setBackground(Color.cyan);
This is where the error accures and where i get the nullpointerexception everytime i type something in my jtextfield.
jtf.addKeyListener(new KeyListener() {
public void keyTyped(KeyEvent e) {
}
public void keyPressed(KeyEvent e) {
}
public void keyReleased(KeyEvent e) {
if (dos == null) {
if (jtf.getText().length() > 0) {
try {
dos = new DataOutputStream(socket.getOutputStream());
dos.writeUTF(jtf.getText());
} catch (IOException ex) {
Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex);
}
} else {
String[] empty = new String[]{""};
jl.setListData(empty);
}
}
}
}
);
jl.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
if (jl.getSelectedIndex() != -1) {
String item = (String) jl.getSelectedValue();
jl1.setText("");
for (String ingrediens : drinkar.get(item)) {
jl1.append(ingrediens + "\n");
}
}else{
jl1.setText("");
}
}
});
frame.add(jtf);
frame.add(jl);
frame.add(jl1);
frame.add(lab);
frame.add(lab1);
frame.add(lab2);
frame.add(js);
}
// tar emot arrayen, lagrar i ny array och visar i JList
public void getArrayList() {
String[] arr = null;
for(int i = 0; i < arr.length; i++){
arr = serverH.setList();
}
jl.setListData(arr);
}
public static void main(String[] args) {
GUI g = new GUI();
}
}

Regarding:
dos = new DataOutputStream(socket.getOutputStream());
The only variable that can throw an NPE on this line is socket which begs the question: where do you initialize socket?
Answer: you don't.
Solution: fix this.
Please always check the variables on the line that throws the NPE as that will show you the cause for the error 99% of the time. You haven't appeared to have tried to do this yet.

You define an instance variable »serverH«
private ServerHandler serverH;
but don't assign any object to it. Therefore you should be facing the NullPointerException. You should assign an object to it, e.g.
serverH = new ServerHandler();
This should solve your problem regarding the NullPointerException.

Related

JComboBox dropdown stays empty even when I add elements to it

In the BuildGUI method in class ChatFrame, there is a JCombobox named dropdown which I tried to populate with an arraylist from class populate. But whenever I run the class, list successfully fetches the data I want to add to JComboBox but it doesn't add it to the combobox.
The combobox stays empty. I tried to add element to it by dropdown.addItem("String");. It worked but why it is not working when I use araylist from another class or same class using for loop?
Here's the code:
// Class to manage Client chat Box.
public class ChatClient {
/** Chat client access */
static class ChatAccess extends Observable {
private Socket socket;
private OutputStream outputStream;
#Override
public void notifyObservers(Object arg) {
super.setChanged();
super.notifyObservers(arg);
}
/** Create socket, and receiving thread */
public void InitSocket(String server, int port) throws IOException {
socket = new Socket(server, port);
outputStream = socket.getOutputStream();
Thread receivingThread = new Thread() {
#Override
public void run() {
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
String line;
while ((line = reader.readLine()) != null)
notifyObservers(line);
} catch (IOException ex) {
notifyObservers(ex);
}
}
};
receivingThread.start();
}
private static final String CRLF = "\r\n"; // newline
/** Send a line of text */
public void send(String text) {
try {
outputStream.write((text + CRLF).getBytes());
outputStream.flush();
} catch (IOException ex) {
notifyObservers(ex);
}
}
/** Close the socket */
public void close() {
try {
socket.close();
} catch (IOException ex) {
notifyObservers(ex);
}
}
}
/** Chat client UI */
static class ChatFrame extends JFrame implements Observer {
private JTextArea textArea;
private JTextField inputTextField;
private JButton sendButton;
private ChatAccess chatAccess;
private JList<String> list;
public DefaultComboBoxModel<String> mod;
private JScrollPane jscrollpane;
public static JComboBox<String> dropdown;
//clientThread ct=new clientThread();
public static ArrayList<String> usr=new ArrayList<String>();
public static String array[]=new String[usr.size()];
public ChatFrame(ChatAccess chatAccess) {
this.chatAccess = chatAccess;
chatAccess.addObserver(this);
buildGUI();
}
/** Builds the user interface */
private void buildGUI() {
for(int j =0;j<usr.size();j++){
array[j] = usr.get(j);
System.out.print("testing"+array[j]);
}
//usr=clientThread.acces();
//System.out.print("test"+usr);
mod = new DefaultComboBoxModel<String>();
list = new javax.swing.JList<>(mod);
list.setBounds(30, 30, 30, 30);
textArea = new JTextArea(20, 50);
textArea.setEditable(false);
textArea.setLineWrap(true);
add(new JScrollPane(textArea), BorderLayout.WEST);
jscrollpane=new JScrollPane();
jscrollpane.setViewportView(list);
add(new JScrollPane(list), BorderLayout.EAST);
Box box = Box.createHorizontalBox();
add(box, BorderLayout.SOUTH);
inputTextField = new JTextField();
dropdown=new JComboBox(array);
dropdown.setBounds(24, 138, 72, 20);
dropdown.setPrototypeDisplayValue("XXXXXXXXXXXXXXXXXXXX");
sendButton = new JButton("Send");
box.add(inputTextField);
box.add(sendButton);
box.add(dropdown);
box.add(populate.dl);
ActionListener sendListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
String str = inputTextField.getText();
if (str != null && str.trim().length() > 0)
chatAccess.send(str);
inputTextField.selectAll();
inputTextField.requestFocus();
inputTextField.setText("");
}
};
inputTextField.addActionListener(sendListener);
sendButton.addActionListener(sendListener);
this.addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
chatAccess.close();
}
});
}
/** Updates the UI depending on the Object argument */
public void update(Observable o, Object arg) {
final Object finalArg = arg;
SwingUtilities.invokeLater(new Runnable() {
public void run() {
textArea.append(finalArg.toString());
textArea.append("\n");
}
});
}
}
static class populate{
public static ArrayList<String> naam=new ArrayList<String>();
public static JComboBox<String> dl=new JComboBox<String>();
public void getarr(String name) {
naam.add(name);
System.out.print("populate"+naam);
dl=new JComboBox<String>();
dl.addItem(name);
//ChatFrame.usr.add(name);
//System.out.print("chatframeclass"+ChatFrame.usr);
}
}
public static void main(String[] args) {
String server = args[0];
int port =2222;
ChatAccess access = new ChatAccess();
JFrame frame = new ChatFrame(access);
frame.setTitle("MyChatApp - connected to " + server + ":" + port);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setVisible(true);
try {
access.InitSocket(server,port);
} catch (IOException ex) {
System.out.println("Cannot connect to " + server + ":" + port);
ex.printStackTrace();
System.exit(0);
}
}
}
The problem with your code is that array is empty when you are adding it to dropdown in the following line:
dropdown=new JComboBox(array);
You can verify this by printing array e.g. System.out.println(Arrays.toString(array)); before adding it to dropdown.
Given below is the minimal reproducible example of how adding a String array to JComboBox<String> works:
String[]arr= {"Hello","Hi","Bye"};
dropdown = new JComboBox(arr);
In the GUI, you will see that dropdown has been populated with the elements of arr[]. If you replace the above code as follows
String[]arr= {};
dropdown = new JComboBox(arr);
you will find that dropdown has become empty.

Java Socket not allowing swing frame to show up

Hey all I am at a loss as to why its doing this. If I just run the server and standalone client it works just fine. However, once I use my code for the client it seems to get stuck...
static JTextField textField = null;
static JTextArea messageArea = null;
static String serverAddress = "localhost";
static UFTtrack window = null;
public static JFrame frame;
public ImageIcon[] images;
static JTable table;
Date lastUpdate;
static Timer timer;
static Scanner in;
static PrintWriter out;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#SuppressWarnings({ "static-access" })
public void run() {
try {
UIManager.setLookAndFeel(new MaterialLookAndFeel());
} catch (UnsupportedLookAndFeelException e1) {
e1.printStackTrace();
}
try {
window = new UFTtrack();
placeChatOnScreen();
createTable();
SystemTrayz.createTray();
centreWindow(frame);
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public UFTtrack() {
initialize();
}
private void initialize() {
frame = new JFrame("UFTtrack");
frame.setTitle("UFT Tracker");
frame.setResizable(false);
frame.setLocationByPlatform(true);
frame.setSize(1308, 900);
frame.setBounds(100, 100, 450, 300);
frame.setMinimumSize(new Dimension(1308, 900));
frame.setPreferredSize(new Dimension(1308, 900));
frame.setLayout(null);
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
}
#SuppressWarnings({ "resource", "unused" })
private static void placeChatOnScreen() {
try {
textField = new JTextField();
textField.setFont(new Font("Segoe UI", Font.PLAIN, 13));
textField.setDragEnabled(true);
textField.setBorder(new MatteBorder(1, 1, 1, 1, (Color) new Color(0, 0, 0)));
textField.setBounds(338, 838, 954, 22);
frame.getContentPane().add(textField);
messageArea = new JTextArea();
messageArea.setEditable(false);
messageArea.setFont(new Font("Segoe UI", Font.PLAIN, 13));
messageArea.setBorder(new MatteBorder(1, 1, 1, 1, (Color) new Color(0, 0, 0)));
messageArea.setDragEnabled(true);
messageArea.setName("chatArea");
messageArea.setWrapStyleWord(true);
messageArea.setBounds(338, 648, 954, 181);
frame.getContentPane().add(messageArea);
textField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
out.println(textField.getText());
textField.setText("");
}
});
Socket socket = new Socket("localhost", 8877);
in = new Scanner(socket.getInputStream());
out = new PrintWriter(socket.getOutputStream(), true);
while (in.hasNextLine()) {
String line = in.nextLine();
if (line.startsWith("SUBMITNAME")) {
out.println(getName());
} else if (line.startsWith("NAMEACCEPTED")) {
textField.setEditable(true);
} else if (line.startsWith("MESSAGE")) {
messageArea.append(line.substring(8) + "\n");
}
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
It does fine until it gets to the "NAMEACCEPTED" else if condition and it just steps out of the while loop and then nothing happens. No error of any kind. It just doesn't how the swing frame!
If I comment out:
/*while (in.hasNextLine()) {
String line = in.nextLine();
if (line.startsWith("SUBMITNAME")) {
out.println(getName());
} else if (line.startsWith("NAMEACCEPTED")) {
textField.setEditable(true);
} else if (line.startsWith("MESSAGE")) {
messageArea.append(line.substring(8) + "\n");
}
}*/
and run it the swing frame loads up just fine. But my Socket (which I am wanting in my swing app) keeps it for some reason passing.
window = new UFTtrack();
placeChatOnScreen();
createTable();
SystemTrayz.createTray();
centreWindow(frame);
window.frame.setVisible(true);
To sum all this up - the above code hits the window = new UFTtrack(); and placeChatOnScreen() but after it exits the While loop in the placeChatOnScreen() it never continues to createTable(); What's the deal???
Also posted here:
http://www.javaprogrammingforums.com/whats-wrong-my-code/41820-java-socket-not-allowing-swing-frame-show-up.html#post165295
https://coderanch.com/t/708072/java/Java-Socket-allowing-swing-frame
https://www.dreamincode.net/forums/topic/415549-java-socket-not-allowing-swing-frame-to-show-up/
Java Socket not allowing swing frame to show up
As mentioned in the comments read and accept operations typically block on a Socket.
You could create an own Thread which is waiting for Message from your Socket and then modify the GUI. Keep in mind that Swing is not Thread safe.
If I need to create an own Thread, I use the Runnable interface. You could achieve it like this:
public class MySocketListener implements Runnable {
private final GUIClass guiClass;
private final ServerSocket serverSocket;
private Socket clientSocket;
public MySocketListener(GUIClass guiClass, ServerSocket serverSocket) {
this.guiClass = guiClass;
this.serverSocket = serverSocket;
}
/* Everything that happens in this method, is done on another Thread. */
#Override
public void run() {
try{
this.clientSocket = this.serverSocket.accept();
Scanner sc = new Scanner(this.clientSocket.getInputStream());
while(true) {
/* Blocking operations */
this.guiClass.doSomething();
}
} catch(IOException ex) {
ex.printStackTrace();
}
}
}
The Thread can then be started easily:
Thread socketListenerThread = new Thread(new MySocketListener(this, serverSocket));
socketListenerThread.start();
For more information have a look at the Thread and Socket documentation.

Swing TextArea function setLineWrap making execution slow

I am making a GUI app in which on click of button we read a binary file and display the data in a TextArea (Data is 327680 bytes).
Now if I use textArea.setLine(true) then it slows down the execution and it takes about 1 minute to execute and dislpays value.
But if I dont use textArea.setLine(true) then code executes in less than 1 sec.
UPDATED CODE.
public class App{
private static final String INPUT_FILE = "E:\\arun\\files\\Capture_Mod1.BIN";
private static final String OUTPUT_FILE = "E:\\arun\\files\\ISO_Write.BIN";
private static final String IMAGE_FILE = "E:\\arun\\files\\Image.jpg";
private JFrame frame;
private JTextArea textArea;
private JButton btnNewButton;
private ISOImageDataWorker worker;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
App window = new App();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public App() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GridBagLayout gridBagLayout = new GridBagLayout();
gridBagLayout.columnWidths = new int[]{0, 0};
gridBagLayout.rowHeights = new int[]{0, 0, 0, 0};
gridBagLayout.columnWeights = new double[]{1.0, Double.MIN_VALUE};
gridBagLayout.rowWeights = new double[]{0.0, 1.0, 0.0, Double.MIN_VALUE};
frame.getContentPane().setLayout(gridBagLayout);
textArea = new JTextArea(5, 20); // **HERE IS THE PROBLEM**
textArea.setLineWrap(true);
textArea.setWrapStyleWord( true );
JScrollPane scrollPane = new JScrollPane(textArea, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
GridBagConstraints gbc_textArea = new GridBagConstraints();
gbc_textArea.insets = new Insets(0, 0, 5, 0);
gbc_textArea.gridx = 0;
gbc_textArea.gridy = 1;
frame.getContentPane().add(scrollPane, gbc_textArea);
btnNewButton = new JButton("ISO 19794 Data");
GridBagConstraints gbc_btnNewButton = new GridBagConstraints();
gbc_btnNewButton.gridx = 0;
gbc_btnNewButton.gridy = 2;
frame.getContentPane().add(btnNewButton, gbc_btnNewButton);
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
worker = new ISOImageDataWorker();
worker.execute();
}
});
}
private class ISOImageDataWorker extends SwingWorker<String , Object>{
#Override
protected String doInBackground() throws Exception {
String str = processData();
return str;
}
#Override
protected void done(){
try {
System.out.println("cm1");
textArea.setText(get());
System.out.println("cm2");
} catch (Exception e) {
e.printStackTrace();
}
}
}
public String processData(){
DataReadWrite data = new DataReadWrite();
//Read data
byte[] imageData = data.readData(INPUT_FILE);
System.out.println("Image data length is : "+ imageData.length);
// Generate Finger Image Data General Header
FingerImageDataGeneralHeader generateHeader = new FingerImageDataGeneralHeader();
byte[] resultData = generateHeader.createGeneralHeader(imageData);
// Write data to binary file
data.writeData(resultData, OUTPUT_FILE);
// Create Image from binary data
CreateTiff createTiff = new CreateTiff();
createTiff.create(resultData, IMAGE_FILE);
String str = bytesToHex(resultData);
return str;
}
public static String bytesToHex(byte[] bytes) {
StringBuilder sb = new StringBuilder();
for (byte b : bytes) {
sb.append(String.format("%02X ", b));
}
return sb.toString();
}
}
I don't know what I am doin wrong. Please Help.
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
>> processData(); <<
textArea.setText(str);
}
});
Don't execute time-consuming code on the GUI-thread (EDT). Use SwingWorker.
See How SwingWorker works.

Stack Oveflow error

I keep getting a stack overflow error when I run this short program I made! please help! Right now all it's supposed to do is take the users input and print their position (in X and Y coordinates). I'm not sure what Stack overflow error is or how to fix it.
import java.awt.*;
import javax.swing.*;
public class ExplorerPanel extends JFrame {
ExplorerEvent prog = new ExplorerEvent(this);
JTextArea dataa = new JTextArea(15, 20);
JTextField datain = new JTextField(20);
JButton submit = new JButton("Submit");
JTextField errors = new JTextField(30);
public ExplorerPanel() {
super("Explorer RPG");
setLookAndFeel();
setSize(400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_…
BorderLayout bord = new BorderLayout();
setLayout(bord);
JPanel toppanel = new JPanel();
toppanel.add(dataa);
add(toppanel, BorderLayout.NORTH);
JPanel middlepanel = new JPanel();
middlepanel.add(datain);
middlepanel.add(submit);
add(middlepanel, BorderLayout.CENTER);
JPanel bottompanel = new JPanel();
bottompanel.add(errors);
add(bottompanel, BorderLayout.SOUTH);
dataa.setEditable(false);
errors.setEditable(false);
submit.addActionListener(prog);
setVisible(true);
}
private void setLookAndFeel() {
try {
UIManager.setLookAndFeel(
"com.sun.java.swing.plaf.nimbus.NimbusLo…
);
} catch (Exception exc) {
// ignore error
}
}
public static void main(String[] args) {
ExplorerPanel frame = new ExplorerPanel();
}
}
public class ExplorerEvent implements ActionListener, Runnable {
ExplorerPanel gui;
Thread playing;
String command;
String gamedata;
ExplorerGame game = new ExplorerGame();
public ExplorerEvent(ExplorerPanel in) {
gui = in;
}
public void actionPerformed(ActionEvent event) {
String command = event.getActionCommand();
if (command.equals("Submit")) {
startPlaying();
}
}
void startPlaying() {
playing = new Thread(this);
playing.start();
}
void stopPlaying() {
playing = (null);
}
void clearAllFields() {
gui.dataa.setText("");
}
public void run() {
Thread thisThread = Thread.currentThread();
while (playing == thisThread) {
// Game code
game.Game();
}
}
}
public class ExplorerGame {
ExplorerPanel gui = new ExplorerPanel();
String command;
int x = 1;
int y = 1;
public void Game() {
command = gui.submit.getText().toLowerCase();
if (command.equals("east")) {x--;}
else if (command.equals("south")) {y--;}
else if (command.equals("west")) {x++;}
else if (command.equals("north")) {y++;}
System.out.println(x + y);
}
}
In ExplorerGame, you have declared: -
ExplorerPanel gui = new ExplorerPanel();
then, in ExplorerPanel: -
ExplorerEvent prog = new ExplorerEvent(this);
and then again, in ExplorerEvent: -
ExplorerGame game = new ExplorerGame();
This will fill the Stack with recursive creation of objects.
ExplorerGame -> ExplorerPanel -> ExplorerEvent --+
^ |
|____________________________________________|
You want to solve the Issue?
I'll Suggest you: -
Throw away the code, and re-design your application. Having a cyclic dependency in your application is a big loop hole, showing a very poor design.

Update JLabel every X seconds from ArrayList<List> - Java

I have a simple Java program that reads in a text file, splits it by " " (spaces), displays the first word, waits 2 seconds, displays the next... etc... I would like to do this in Spring or some other GUI.
Any suggestions on how I can easily update the words with spring? Iterate through my list and somehow use setText();
I am not having any luck. I am using this method to print my words out in the consol and added the JFrame to it... Works great in the consol, but puts out endless jframe. I found most of it online.
private void printWords() {
for (int i = 0; i < words.size(); i++) {
//How many words?
//System.out.print(words.size());
//print each word on a new line...
Word w = words.get(i);
System.out.println(w.name);
//pause between each word.
try{
Thread.sleep(500);
}
catch(InterruptedException e){
e.printStackTrace();
}
JFrame frame = new JFrame("Run Text File");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel textLabel = new JLabel(w.name,SwingConstants.CENTER);
textLabel.setPreferredSize(new Dimension(300, 100));
frame.getContentPane().add(textLabel, BorderLayout.CENTER);
//Display the window. frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
}
}
I have a window that get's created with JFrame and JLable, however, I would like to have the static text be dynamic instead of loading a new spring window. I would like it to flash a word, disappear, flash a word disappear.
Any suggestions on how to update the JLabel? Something with repaint()? I am drawing a blank.
Thanks!
UPDATE:
With the help from the kind folks below, I have gotten it to print correctly to the console. Here is my Print Method:
private void printWords() {
final Timer timer = new Timer(500, null);
ActionListener listener = new ActionListener() {
private Iterator<Word> w = words.iterator();
#Override
public void actionPerformed(ActionEvent e) {
if (w.hasNext()) {
_textField.setText(w.next().getName());
//Prints to Console just Fine...
//System.out.println(w.next().getName());
}
else {
timer.stop();
}
}
};
timer.addActionListener(listener);
timer.start();
}
However, it isn't updating the lable? My contructor looks like:
public TimeThis() {
_textField = new JTextField(5);
_textField.setEditable(false);
_textField.setFont(new Font("sansserif", Font.PLAIN, 30));
JPanel content = new JPanel();
content.setLayout(new FlowLayout());
content.add(_textField);
this.setContentPane(content);
this.setTitle("Swing Timer");
this.pack();
this.setLocationRelativeTo(null);
this.setResizable(false);
//_textField.setText("loading...");
}
Getting there... I'll post the fix once I, or whomever assists me, get's it working. Thanks again!
First, build and display your GUI. Once the GUI is displayed, use a javax.swing.Timer to update the GUI every 500 millis:
final Timer timer = new Timer(500, null);
ActionListener listener = new ActionListsner() {
private Iterator<Word> it = words.iterator();
#Override
public void actionPerformed(ActionEvent e) {
if (it.hasNext()) {
label.setText(it.next().getName());
}
else {
timer.stop();
}
}
};
timer.addActionListener(listener);
timer.start();
Never use Thread.sleep(int) inside Swing Code, because it blocks the EDT; more here,
The result of using Thread.sleep(int) is this:
When Thread.sleep(int) ends
Example code:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.image.BufferedImage;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Random;
import javax.swing.*;
//http://stackoverflow.com/questions/7943584/update-jlabel-every-x-seconds-from-arraylistlist-java
public class ButtonsIcon extends JFrame implements Runnable {
private static final long serialVersionUID = 1L;
private Queue<Icon> iconQueue = new LinkedList<Icon>();
private JLabel label = new JLabel();
private Random random = new Random();
private JPanel buttonPanel = new JPanel();
private JPanel labelPanel = new JPanel();
private Timer backTtimer;
private Timer labelTimer;
private JLabel one = new JLabel("one");
private JLabel two = new JLabel("two");
private JLabel three = new JLabel("three");
private final String[] petStrings = {"Bird", "Cat", "Dog",
"Rabbit", "Pig", "Fish", "Horse", "Cow", "Bee", "Skunk"};
private boolean runProcess = true;
private int index = 1;
private int index1 = 1;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
ButtonsIcon t = new ButtonsIcon();
}
});
}
public ButtonsIcon() {
iconQueue.add(UIManager.getIcon("OptionPane.errorIcon"));
iconQueue.add(UIManager.getIcon("OptionPane.informationIcon"));
iconQueue.add(UIManager.getIcon("OptionPane.warningIcon"));
iconQueue.add(UIManager.getIcon("OptionPane.questionIcon"));
one.setFont(new Font("Dialog", Font.BOLD, 24));
one.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
two.setFont(new Font("Dialog", Font.BOLD, 24));
two.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
three.setFont(new Font("Dialog", Font.BOLD, 10));
three.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
labelPanel.setLayout(new GridLayout(0, 3, 4, 4));
labelPanel.add(one);
labelPanel.add(two);
labelPanel.add(three);
//labelPanel.setBorder(new LineBorder(Color.black, 1));
labelPanel.setOpaque(false);
JButton button0 = createButton();
JButton button1 = createButton();
JButton button2 = createButton();
JButton button3 = createButton();
buttonPanel.setLayout(new GridLayout(0, 4, 4, 4));
buttonPanel.add(button0);
buttonPanel.add(button1);
buttonPanel.add(button2);
buttonPanel.add(button3);
//buttonPanel.setBorder(new LineBorder(Color.black, 1));
buttonPanel.setOpaque(false);
label.setLayout(new BorderLayout());
label.add(labelPanel, BorderLayout.NORTH);
label.add(buttonPanel, BorderLayout.SOUTH);
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
label.setPreferredSize(new Dimension(d.width / 3, d.height / 3));
add(label, BorderLayout.CENTER);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setVisible(true);
startBackground();
startLabel2();
new Thread(this).start();
printWords(); // generating freeze Swing GUI durring EDT
}
private JButton createButton() {
JButton button = new JButton();
button.setBorderPainted(false);
button.setBorder(null);
button.setFocusable(false);
button.setMargin(new Insets(0, 0, 0, 0));
button.setContentAreaFilled(false);
button.setIcon(nextIcon());
button.setRolloverIcon(nextIcon());
button.setPressedIcon(nextIcon());
button.setDisabledIcon(nextIcon());
nextIcon();
return button;
}
private Icon nextIcon() {
Icon icon = iconQueue.peek();
iconQueue.add(iconQueue.remove());
return icon;
}
// Update background at 4/3 Hz
private void startBackground() {
backTtimer = new javax.swing.Timer(750, updateBackground());
backTtimer.start();
backTtimer.setRepeats(true);
}
private Action updateBackground() {
return new AbstractAction("Background action") {
private static final long serialVersionUID = 1L;
#Override
public void actionPerformed(ActionEvent e) {
label.setIcon(new ImageIcon(getImage()));
}
};
}
// Update Label two at 2 Hz
private void startLabel2() {
labelTimer = new javax.swing.Timer(500, updateLabel2());
labelTimer.start();
labelTimer.setRepeats(true);
}
private Action updateLabel2() {
return new AbstractAction("Label action") {
private static final long serialVersionUID = 1L;
#Override
public void actionPerformed(ActionEvent e) {
two.setText(petStrings[index]);
index = (index + 1) % petStrings.length;
}
};
}
// Update lable one at 3 Hz
#Override
public void run() {
while (runProcess) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
one.setText(petStrings[index1]);
index1 = (index1 + 1) % petStrings.length;
}
});
try {
Thread.sleep(300);
} catch (Exception e) {
e.printStackTrace();
}
}
}
// Note: blocks EDT
private void printWords() {
for (int i = 0; i < petStrings.length; i++) {
String word = petStrings[i].toString();
System.out.println(word);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
three.setText(word);
}
three.setText("<html> Concurency Issues in Swing<br>"
+ " never to use Thread.sleep(int) <br>"
+ " durring EDT, simple to freeze GUI </html>");
}
public BufferedImage getImage() {
int w = label.getWidth();
int h = label.getHeight();
GradientPaint gp = new GradientPaint(0f, 0f, new Color(
127 + random.nextInt(128),
127 + random.nextInt(128),
127 + random.nextInt(128)),
w, w,
new Color(random.nextInt(128), random.nextInt(128), random.nextInt(128)));
BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = bi.createGraphics();
g2d.setPaint(gp);
g2d.fillRect(0, 0, w, h);
g2d.setColor(Color.BLACK);
return bi;
}
}
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import javax.swing.*;
class TimeThis extends JFrame {
private static final long serialVersionUID = 1L;
private ArrayList<Word> words;
private JTextField _textField; // set by timer listener
public TimeThis() throws IOException {
_textField = new JTextField(5);
_textField.setEditable(false);
_textField.setFont(new Font("sansserif", Font.PLAIN, 30));
JPanel content = new JPanel();
content.setLayout(new FlowLayout());
content.add(_textField);
this.setContentPane(content);
this.setTitle("Swing Timer");
this.pack();
this.setLocationRelativeTo(null);
this.setResizable(false);
_textField.setText("loading...");
readFile(); // read file
printWords(); // print results
}
public void readFile(){
try {
BufferedReader in = new BufferedReader(new FileReader("adameve.txt"));
words = new ArrayList<Word>();
int lineNum = 1; // we read first line in start
// delimeters of line in this example only "space"
char [] parse = {' '};
String delims = new String(parse);
String line = in.readLine();
String [] lineWords = line.split(delims);
// split the words and create word object
//System.out.println(lineWords.length);
for (int i = 0; i < lineWords.length; i++) {
Word w = new Word(lineWords[i]);
words.add(w);
}
lineNum++; // pass the next line
line = in.readLine();
in.close();
} catch (IOException e) {
}
}
private void printWords() {
final Timer timer = new Timer(100, null);
ActionListener listener = new ActionListener() {
private Iterator<Word> w = words.iterator();
#Override
public void actionPerformed(ActionEvent e) {
if (w.hasNext()) {
_textField.setText(w.next().getName());
//Prints to Console just Fine...
//System.out.println(w.next().getName());
}
else {
timer.stop();
}
}
};
timer.addActionListener(listener);
timer.start();
}
class Word{
private String name;
public Word(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
public static void main(String[] args) throws IOException {
JFrame ani = new TimeThis();
ani.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ani.setVisible(true);
}
}
I got it working with this code... Hope it can help someone else expand on their Java knowledge. Also, if anyone has any recommendations on cleaning this up. Please do so!
You're on the right track, but you're creating the frame's inside the loop, not outside. Here's what it should be like:
private void printWords() {
JFrame frame = new JFrame("Run Text File");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel textLabel = new JLabel("", SwingConstants.CENTER);
textLabel.setPreferredSize(new Dimension(300, 100));
frame.getContentPane().add(textLabel, BorderLayout.CENTER);
//Display the window. frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
for (int i = 0; i < words.size(); i++) {
//How many words?
//System.out.print(words.size());
//print each word on a new line...
Word w = words.get(i);
System.out.println(w.name);
//pause between each word.
try{
Thread.sleep(500);
}
catch(InterruptedException e){
e.printStackTrace();
}
textLabel.setTest(w.name);
}
}

Categories