executable jar file does not show text or panel when opened - java

I don't know why but when I export my project into an executable jar file, there are somethings that don't turn out as if you would run the program from eclipse. One frame doesn't open up, which just contains text in it. I have another internal frame which is a split pane and contains questions on the right hand side and information on the left hand side panel. But in the executable jar file it doesn't show the information on the left hand side. I don't know why this is happening, I also have tried many options when exporting the project (making a jar file) but nothing seems to work. Any help would be appreciated.
Here is my code for the frame that doesn't open up:
public class About implements ActionListener, InternalFrameListener{
private int openFrameCount;
private JDesktopPane desk;
private JTextArea Tarea;
private JScrollPane scroll;
private BufferedReader in ;
private MyInternalFrame frame;
public About(JDesktopPane desktop) {
// TODO Auto-generated constructor stub
desk = desktop;
}
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
if(frame == null || frame.getParent() == null && !frame.isIconifiable()){
frame = new MyInternalFrame("SAD Imaging");
try {
in = new BufferedReader(new FileReader("SADInfo.txt"));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String line;
String file = "";
try {
while((line = in.readLine()) != null)
{
System.out.println(line);
file += line;
file +="\n";
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
in.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Tarea = new JTextArea();
//System.out.println(file);
Tarea.setText(file);
Font f = new Font("TimesNewRoman", Font.ROMAN_BASELINE, 16);
Tarea.setFont(f);
Tarea.setBackground(Color.white);
Tarea.setAlignmentX(SwingConstants.CENTER);
Tarea.setEditable(false);
JPanel panel = new JPanel();
panel.add(Tarea);
panel.setBackground(Color.white);
//scroll = new JScrollPane(Tarea);
scroll = new JScrollPane(panel,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
//open the frame in the middle of the desktop.
Dimension desktopSize = desk.getSize();
Dimension jInternalFrameSize = frame.getSize();
frame.setLocation((desktopSize.width - jInternalFrameSize.width)/2, (desktopSize.height- jInternalFrameSize.height)/2);
frame.add(scroll);
frame.setVisible(true);
desk.add(frame);
try {
frame.setSelected(true);
} catch (java.beans.PropertyVetoException e) {
}
frame.addInternalFrameListener(this);
}
else {
try {
//frame.setIcon(true);
frame.setMaximizable(true);
frame.setIconifiable(false);
frame.setSelected(true);
frame.moveToFront();
frame.toFront();
} catch (PropertyVetoException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private class MyInternalFrame extends JInternalFrame {
static final int xPosition = 30, yPosition = 30;
public MyInternalFrame(String title) {
super(title, true,true, true, true);
setSize(600,500);
// Set the window's location.
setLocation(xPosition * openFrameCount, yPosition * openFrameCount);
}
}
This file just contains text information.
Same problem with the split pane. Here is the code for it.
public class FrequentQuestions implements ActionListener, InternalFrameListener{
private int openFrameCount;
private JDesktopPane desk;
private JTextArea Tarea;
private JScrollPane scroll;
private BufferedReader in ;
JPanel panelQuestions = new JPanel();
JPanel panelAnswers = new JPanel();
JTextArea text = new JTextArea();
JTextPane tPane = new JTextPane();
String file ="";
//private FrequentQuestions quest;
JSplitPane pane ;
MyInternalFrame frame;
public FrequentQuestions(JDesktopPane desktop) {
// TODO Auto-generated constructor stub
desk = desktop;
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(frame == null || frame.getParent() == null){
frame = new MyInternalFrame("Frequently Asked Questions");
String [] options = {"How to open/save images", "What formats can SAD Imaging open", "How to show information about an image",
"Compute FFT/Inverse", "Graphs"};
JList list = new JList(options);
//list.setBorder(BorderFactory.createLineBorder(Color.black));
//panelQuestions.add(list);
list.addListSelectionListener(new ListSelectionListener(){
#Override
public void valueChanged(ListSelectionEvent e) {
// TODO Auto-generated method stub
if(e.getValueIsAdjusting() == false)
return;
JList list = (JList) e.getSource();
if (list.isSelectionEmpty()) {
System.out.println("list selection is empty!");
}
int index = ((JList)e.getSource()).getSelectedIndex();
if(index == 0){
//panelAnswers.removeAll();
file = "";
try {
in = new BufferedReader(new FileReader("openSave.txt"));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String line;
try {
while((line = in.readLine()) != null)
{
System.out.println(line);
file += line;
file +="\n";
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
in.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
tPane.setText(file);
System.out.println("I am outputting!");
}
else if(index == 1){
//panelAnswers.removeAll();
file = "";
try {
in = new BufferedReader(new FileReader("format.txt"));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String line;
//String file = "";
try {
while((line = in.readLine()) != null)
{
System.out.println(line);
file += line;
file +="\n";
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
in.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
tPane.setText(file);
System.out.println("2nd item selected");
}
else{
//panelAnswers.removeAll();
file = "";
try {
in = new BufferedReader(new FileReader("showInfo.txt"));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String line;
try {
while((line = in.readLine()) != null)
{
System.out.println(line);
file += line;
file +="\n";
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
in.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
tPane.setText(file);
System.out.println("3rd item selected");
}
}
});
JScrollPane scroll1 = new JScrollPane(list,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scroll = new JScrollPane(tPane,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
pane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, scroll1, scroll);
pane.setAutoscrolls(true);
pane.setOpaque(true);
panelQuestions.setMinimumSize(new Dimension(259,50));
panelQuestions.setBackground(new Color(0,0,0,0));
panelAnswers.setMinimumSize(new Dimension(600,30));
pane.setOneTouchExpandable(true);
pane.setDividerLocation(290);
scroll1.setBackground(new Color(0,0,0,0));
//Border border = new Border();
//scroll1.setBorder(BorderFactory.createLineBorder(Color.black));
//open the frame in the middle of the desktop.
Dimension desktopSize = desk.getSize();
Dimension jInternalFrameSize = frame.getSize();
frame.setLocation((desktopSize.width - jInternalFrameSize.width)/2, (desktopSize.height- jInternalFrameSize.height)/2);
frame.add(pane);
frame.setVisible(true);
desk.add(frame);
try {
frame.setSelected(true);
} catch (java.beans.PropertyVetoException e1) {
}
}
else{
try {
//frame.setIcon(true);
//frame.setMaximizable(true);
frame.setSelected(true);
frame.moveToFront();
//frame.toFront();
} catch (PropertyVetoException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
private class MyInternalFrame extends JInternalFrame {
static final int xPosition = 30, yPosition = 30;
public MyInternalFrame(String title) {
super(title, true,true, true, true);
setSize(800,500);
// Set the window's location.
setLocation(xPosition * openFrameCount, yPosition * openFrameCount);
}
}

You are trying to load the file from the filesystem. Instead, you need to load it via a classloader.
Getting Resources from a jar: classloader vs class resourceasstream
Edit: I'm assuming that the executable jar contains this text file. Is that the case?

Related

Socket blocking client when sending image

So I'm making a simple chat where I'm sending content in the form of objects, in this case my problem is that when I'm sending and Image it just blocking my Client!, here's my shortened code.
I've isolated it mostly to the code below, as I've tested the rest and worked fine, I've also tried debugging this but I just can't seem to find the problem
Image
package com.example.mtc.Packets;
import java.io.Serializable;
public class Image extends Message implements Serializable {
/**
*
*/
private static final long serialVersionUID = -3188407715959746920L;
private byte[] content;
private String type;
public Image(byte[] content,String type, int sourceID,int destinationID,String sourceUsername) {
super(destinationID,sourceID,sourceUsername);
this.content = content;
this.type = "." + type;
}
public byte[] getContent() {
return content;
}
public String getType() {
return type;
}
}
ClientReaderThread:
while (true) {
try {
inputData = in.readObject();
if (inputData.getClass().getName().equals("com.example.mtc.Packets.Image")) {
Image imagePacket = (Image) inputData;
byte[] imageContent = imagePacket.getContent();
ImageIcon imageIcon = new ImageIcon(imageContent);
imageIcon.setImage(imageIcon.getImage().getScaledInstance(300, 300, java.awt.Image.SCALE_DEFAULT));
if (imagePacket.getDestinationID() == 0) {
if (Cliente.selectedChat == 0) {
Style style = chatCard.doc.addStyle("StyleName", null);
StyleConstants.setIcon(style, imageIcon);
chatCard.doc.insertString(chatCard.doc.getLength(), "ignored text\n", style);
chatCard.textPane.setCaretPosition(chatCard.textPane.getDocument().getLength());
Cliente.gui.revalidate();
}
} else if (imagePacket.getSourceID() == Cliente.selectedChat
|| imagePacket.getSourceID() == Cliente.getUserID()) {
Style style = chatCard.doc.addStyle("StyleName", null);
StyleConstants.setIcon(style, imageIcon);
chatCard.doc.insertString(chatCard.doc.getLength(), "ignored text\n", style);
chatCard.textPane.setCaretPosition(chatCard.textPane.getDocument().getLength());
Cliente.gui.revalidate();
}
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(Cliente.gui, "Couldn't connect to Server!", "Error",
JOptionPane.ERROR_MESSAGE);
System.exit(1);
} catch (BadLocationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Server Listener
private void Listener() {
// TODO Auto-generated method stub
while (connected) {
inputData = readObject();
if (inputData != null) {
if (inputData.getClass().getName().equals("com.example.mtc.Packets.Image")) {
Image imagePacket = (Image) inputData;
byte[] imageContent = imagePacket.getContent();
ImageIcon imageIcon = new ImageIcon(imageContent);
imageIcon.setImage(imageIcon.getImage().getScaledInstance(300, 300,
java.awt.Image.SCALE_DEFAULT));
imageIcon.getImage().flush();
BufferedImage bi = new BufferedImage(
imageIcon.getIconWidth(),
imageIcon.getIconHeight(),
BufferedImage.TYPE_INT_RGB);
Graphics g = bi.createGraphics();
// paint the Icon to the BufferedImage.
imageIcon.paintIcon(null, g, 0,0);
g.dispose();
try {
File imageFile = File.createTempFile("image", imagePacket.getType(),
new File("./serverImages/"));
insertLog(imageFile.getAbsolutePath(), imagePacket.getDestinationID(), true);
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
try {
Files.write(imageFile.toPath(), imageContent);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (imagePacket.getDestinationID() == 0) {
synchronized (Server.Threads) {
for (ClientHandler t : Server.Threads) {
if (!idExistsInBlockedList(t.getUserID(), userID)) {
t.sendObject(imagePacket);
}
}
}
} else {
synchronized (Server.Threads) {
for (ClientHandler t : Server.Threads) {
if (!idExistsInBlockedList(t.getUserID(), userID)) {
if (t.getUserID() == imagePacket.getDestinationID()) {
t.sendObject(imagePacket);
}
}
}
sendObject(imagePacket);
}
}
}
}
}
}
Managed to solve it by using SwingUtilities.invokeLater(), as advised by R.L.M

Adding java variable to batch file

Here's my updated code. This is the button being clicked in the class I made separate form the java class you provided. I know it says Ping (disregard that, I'm using the button for testing purposes) I don't see how they would reference each other with the Process P line of code you provided. What do you think?
JButton btnPingComputer = new JButton("PING");
btnPingComputer.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String line;
BufferedWriter bw = null;
BufferedWriter writer =null;
try {
writer = new BufferedWriter(new FileWriter(tempFile));
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String lineToRemove = "OU=Workstations";
String s = null;
Process p = null;
try {
p = Runtime.getRuntime().exec("cmd /c start c:\\computerQuery.bat computerName");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
p = Runtime.getRuntime().exec("c:\\computerQuery.bat");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
StringBuffer sbuffer = new StringBuffer(); // new trial
BufferedReader in = new BufferedReader(new InputStreamReader(p
.getInputStream()));
try {
while ((line = in.readLine()) != null) {
System.out.println(line);
textArea.append(line);
textArea.append(String.format(" %s%n", line));
String dn = "CN=FDCD111304,OU=Workstations,OU=SIM,OU=Accounts,DC=FL,DC=NET";
LdapName ldapName = new LdapName(dn);
String commonName = (String) ldapName.getRdn(ldapName.size() - 1).getValue();
System.out.println(commonName);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidNameException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally
{
try {
fw.close();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
Add the parameter to your java program like this :
Process p = Runtime.getRuntime().exec("cmd /c start c:\\batFile.bat computerName");
This will pass parameter_to_pass to the batch file.
For your situation this code should work well:
/*
This java program copies the value from a jTextField, adds it to a predifined value
and send it to command-line as a parameter. All these happens if you click the jButton
*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class cmdJavaTest extends JFrame {
JTextField jTextField1 = new JTextField(20);
JButton jButton1 = new JButton("Click");
JLabel jLabel1 = new JLabel();
public cmdJavaTest() {
super("CmdJavaParameterPass");
getContentPane().setLayout(new FlowLayout());
getContentPane().add(jTextField1);
getContentPane().add(jButton1);
getContentPane().add(jLabel1);
jButton1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
sendParam();
}
});
setSize(300, 170);
setVisible(true);
}
public void sendParam(){
try{
String val = "Computer"+jTextField1.getText(); //Put whatever you want to pass as a prefix in place of "Computer"
jLabel1.setText(val);
Process p ;
p = Runtime.getRuntime().exec("cmd /c start c:\\batFile.bat "+val+"");
}
catch(Exception e){
e.printStackTrace();
}
}
public static void main(String argv[]) {
new cmdJavaTest();
}
}
Use this as you test batch file content
#dsquery computer -name %1
pause
But you must also see how to use a ProcessBuilder.
Thanks, hope it helps

using Button and Timer Simultaneously in java

I have two buttons and and Timer. When I run the code it gets connected to the Socket. For every 1000 milliseconds timer should send the command(message) to the Socket and simultaneously when I click a button it should send other message as in the code. But problem is that when I click a button either the messages which are sent are delayed or messages are not sent properly through dat is the receiving end is not receiving properly.
How to handle this issue?
Here is my code
public static void main(String[] args)
{
// TODO Auto-generated method stub
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
configure config=new configure();
config.run();
config.setVisible(true);
}
});
}
protected void run()
{
// TODO Auto-generated method stub
try {
connection.setText("Connected to < NONE >");
socket=new Socket("192.168.1.3",3000);
// System.out.println("Connection Established") ;
connection.setText("CONNECTION ESTABLISHED WITH : " + "< " +
socket.getInetAddress() + " >" + "\n");
} catch (UnknownHostException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
// System.out.println("connection failed");
connection.setText("CONNECTION FAILED");
}
}
public configure()
{
setResizable(false);
setBounds(300,80,800,600);
contentPane=new JPanel();
contentPane.setBorder(new EmptyBorder(5,5,5,5));
setContentPane(contentPane);
contentPane.setLayout(null);
configlabel=new JLabel("CONFIGURE YOUR MODEL");
configlabel.setBounds(210,20,500,40);
configlabel.setFont(new Font("arial",Font.BOLD,28));
contentPane.add(configlabel);
connection=new JLabel();
connection.setBounds(12,80,500,40);
connection.setFont(new Font("arial",Font.BOLD,16));
contentPane.add(connection);
channel1=new JLabel("Channel 1");
channel1.setBounds(80, 140, 80, 30);
channel1.setFont(new Font("arial",Font.BOLD,15));
contentPane.add(channel1);
channel1Field=new JTextField();
channel1Field.setBounds(55, 200, 120, 30);
channel1Field.setEnabled(true);
contentPane.add(channel1Field);
channel1send=new JButton("Send 1");
channel1send.setBounds(65, 270, 100, 30);
channel1send.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e)
{
if(!(channel1Field.getText().equals("")))
{
// TODO Auto-generated method stub
if(channel1send.isEnabled())
{
new Thread(new Channel1()).start();
}
}
else
{
JOptionPane optionPane = new JOptionPane("Field cannot be
empty", JOptionPane.ERROR_MESSAGE);
JDialog dialog = optionPane.createDialog("FAILURE");
dialog.setAlwaysOnTop(true);
dialog.setVisible(true);
}
}
});
contentPane.add(channel1send);
channel2=new JLabel("Channel 2");
channel2.setBounds(255, 140, 80, 30);
channel2.setFont(new Font("arial",Font.BOLD,15));
contentPane.add(channel2);
channel2Field=new JTextField();
channel2Field.setBounds(230, 200, 120, 30);
channel2Field.setEnabled(true);
contentPane.add(channel2Field);
channel2send=new JButton("Send 2");
channel2send.setBounds(250, 270, 80, 30);
channel2send.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(!(channel2Field.getText().equals("")))
{
if(channel2send.isEnabled())
{
new Thread(new Channel2()).start();
}
}
else
{
JOptionPane optionPane = new JOptionPane("Field cannot
be empty", JOptionPane.ERROR_MESSAGE);
JDialog dialog = optionPane.createDialog("FAILURE");
dialog.setAlwaysOnTop(true);
dialog.setVisible(true);
}
}
});
contentPane.add(channel2send);
Timer timer = new Timer();
timer.schedule(new SayHello(), 0, 1000);
}
class SayHello extends TimerTask {
public void run() {
try
{
byte[] com=new byte[]{0x01,(byte)0xFE};
socket=new Socket("192.168.1.3",3000);
DataOutputStream dw=new DataOutputStream(socket.getOutputStream());
dw.writeInt(com.length);
dw.write(com);
StringBuilder sb=new StringBuilder();
for(byte b:com)
{
sb.append(String.format("%02X ", b));
}
sentmessage.append("Timer Sent - " + sb.toString() + "\n");
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
class Channel1 implements Runnable
{
#Override
public void run()
{
// TODO Auto-generated method stub
try {
String message1=channel1Field.getText();
int msg1=Integer.parseInt(message1);
command=new byte[]{(byte)0xFE,0x01,0x01,(byte)msg1,0x00,0x00,(byte)0xFD};
DataOutputStream dw=new DataOutputStream(socket.getOutputStream());
// dw.writeInt(command.length);
dw.write(command);
StringBuilder sb=new StringBuilder();
// System.out.println(Arrays.toString(command));
for(byte b:command)
{
sb.append(String.format("%02X ", b));
}
sentmessage.append("Client Sent to Channel 1 - " +
sb.toString() + "\n");
}
catch (IOException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
sentmessage.append("channel 1 failed to send");
}
finally
{
if(socket!=null)
{
try
{
socket.close();
socket=new Socket("192.168.1.3",3000);
}
catch (IOException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
}
}
class Channel2 implements Runnable
{
#Override
public void run()
{
// TODO Auto-generated method stub
try {
String message2=channel2Field.getText();
int msg2=Integer.parseInt(message2);
command=new byte[]{(byte)0xFE,0x01,0x02,(byte)msg2,0x00,0x00(byte)0xFD};
DataOutputStream dw=new DataOutputStream(socket.getOutputStream());
// dw.writeInt(command.length);
dw.write(command);
StringBuilder sb=new StringBuilder();
for(byte b:command)
{
sb.append(String.format("%02X ", b));
}
sentmessage.append("Client Sent to Channel 2 - " +
sb.toString() + "\n");
}
catch (IOException e1)
{
e1.printStackTrace();
sentmessage.append("channel 2 on failed");
}
finally
{
if(socket!=null)
{
try {
socket.close();
socket=new Socket("192.168.1.3",3000);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
}
}

Android : My app crashes when there is a blank editText field

I have a problem with my code.
It keeps on crashing when i have a blank editText field.
This bit of code is in the settings of my app and works the data fine but when there is a blank field it crashes the program.
Here's the code for it.
Please don't be harsh because it is my 1st android app. So if anyone knows how to solves the blank edit text field problem that would be greatly appreciated! (Any other comments on how to improve the app would be a help to).
Cheers
package com.cleanyet.cyv100fp;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class sTasks extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.tasks);
/*Sets Up the Variables*/
Button done = (Button) findViewById(R.id.done1);
EditText t1 = (EditText)findViewById(R.id.tbTask1);
EditText t2 = (EditText)findViewById(R.id.tbTask2);
EditText t3 = (EditText)findViewById(R.id.tbTask3);
EditText t4 = (EditText)findViewById(R.id.tbTask4);
EditText t5 = (EditText)findViewById(R.id.tbTask5);
String FILENAME1 = "stask1";
String FILENAME2 = "stask2";
String FILENAME3 = "stask3";
String FILENAME4 = "stask4";
String FILENAME5 = "stask5";
String task1 = null;
String task2 = null;
String task3 = null;
String task4 = null;
String task5 = null;
String edit = "Edit Task";
/*Fixes the Blank Field bug*/
/*Sets up the file input*/
FileInputStream fis = null;
/*Gets the tasks set previously*/
/*Task 1 set up*/
try {
fis = openFileInput(FILENAME1);
byte[] dataArray = new byte[fis.available()];
while (fis.read(dataArray) != -1){
task1 = new String(dataArray);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (task1.toString().length() < 0) {
task1.toString();
t1.setText(task1);
}
else {
t1.setText(edit);
}
/*Task 2 set up*/
try {
fis = openFileInput(FILENAME2);
byte[] dataArray = new byte[fis.available()];
while (fis.read(dataArray) != -1){
task2 = new String(dataArray);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (task2.toString().length() < 0) {
task2.toString();
t2.setText(task2);
}
else {
t2.setText(edit);
}
/*Task 3 set up*/
try {
fis = openFileInput(FILENAME3);
byte[] dataArray = new byte[fis.available()];
while (fis.read(dataArray) != -1){
task3 = new String(dataArray);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (task3.toString().length() < 0) {
task3.toString();
t3.setText(task3);
}
else {
t3.setText(edit);
}
/*Task 4 set up*/
try {
fis = openFileInput(FILENAME4);
byte[] dataArray = new byte[fis.available()];
while (fis.read(dataArray) != -1){
task4 = new String(dataArray);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (task4.toString().length() < 0) {
task4.toString();
t4.setText(task4);
}
else {
t4.setText(edit);
}
/*Task 5 set up*/
try {
fis = openFileInput(FILENAME5);
byte[] dataArray = new byte[fis.available()];
while (fis.read(dataArray) != -1){
task5 = new String(dataArray);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (task5.toString().length() < 0) {
task5.toString();
t5.setText(task5);
}
else {
t5.setText(edit);
}
/*When changes have been made and done is clicked*/
done.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
/*Sets up the Variables*/
EditText t1 = (EditText)findViewById(R.id.tbTask1);
EditText t2 = (EditText)findViewById(R.id.tbTask2);
EditText t3 = (EditText)findViewById(R.id.tbTask3);
EditText t4 = (EditText)findViewById(R.id.tbTask4);
EditText t5 = (EditText)findViewById(R.id.tbTask5);
String tasks1 = t1.getText().toString();
String tasks2 = t2.getText().toString();
String tasks3 = t3.getText().toString();
String tasks4 = t4.getText().toString();
String tasks5 = t5.getText().toString();
String FILENAME1 = "stask1";
String FILENAME2 = "stask2";
String FILENAME3 = "stask3";
String FILENAME4 = "stask4";
String FILENAME5 = "stask5";
String task1 = tasks1;
String task2 = tasks2;
String task3 = tasks3;
String task4 = tasks4;
String task5 = tasks5;
String edit = "Go to settings to make this task.";
if (t1 != null){
t1.setText(edit);
/*t2.setText(edit);
t3.setText(edit);
t4.setText(edit);
t5.setText(edit);*/
};
/*Put if statement here to catch the empty field*/
/*Makes The Changes to the Tasks*/
try {
FileOutputStream fos1 = openFileOutput(FILENAME1, Context.MODE_PRIVATE);
fos1.write(task1.getBytes());
fos1.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
FileOutputStream fos2 = openFileOutput(FILENAME2, Context.MODE_PRIVATE);
fos2.write(task2.getBytes());
fos2.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
FileOutputStream fos3 = openFileOutput(FILENAME3, Context.MODE_PRIVATE);
fos3.write(task3.getBytes());
fos3.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
FileOutputStream fos4 = openFileOutput(FILENAME4, Context.MODE_PRIVATE);
fos4.write(task4.getBytes());
fos4.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
FileOutputStream fos5 = openFileOutput(FILENAME5, Context.MODE_PRIVATE);
fos5.write(task5.getBytes());
fos5.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
startActivity(new Intent("com.checkin.cyv100fp.settings"));
}
});
}
}
if (task1.toString().length() < 0) {
task1.toString();
t1.setText(task1);
}
else {
t1.setText(edit);
}
The above makes no sense at all.
Firstly task1 IS a string so there's no need to call toString() to convert it to one.
Secondly, your conditional statement (if) is checking to see if task1 has a length less than zero....think about it.
Thirdly, if it does have an impossible length less than zero you then call toString() on it again (with no variable to receive the impossible less than zero result) and you then try to set the text of your t1 EditText.
The chances are that your file reading is failing (probably because you only save the strings later in the onClick(...) method). Because your task strings will be null if the file reading fails then you need to test for null before trying to use them.
In other words you're doing this in your code...
String task1 = null;
To fix the bit of code I enclosed at the beginning, use...
if (task1 != null) {
t1.setText(task1);
}
else {
t1.setText(edit);
}
...but most importantly, make sure your files have the strings in them that you need to read.

Force paint a jframe?

I have been trying to work this out by myself these past few days but I just can't seem to be able to get to a solution...... how do I force paint a JFrame and everything inside it? I have a Chat programme (client/server approach), the server class and the client one are identical code-wise? But I just can't seem to make the client one show!
import java.awt.event.ActionEvent;
public class Chat extends JFrame implements Runnable, ActionListener, WindowListener{
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private JTextField line;
// TCP Components
private Socket channel = null;
private JScrollPane scrollPane;
private String toBeSent="";
private final String END_CHAT_SESSION = new Character((char)0).toString();
private PrintWriter out;
private boolean channelIsStillOpen = true;
private Socket channel;
private static JTextArea chatText;
public Chat(Socket channel) {
this.channel=channel;
addWindowListener(this);
setTitle("Remote Administrator");
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
line = new JTextField();
line.setBounds(17, 207, 289, 40);
line.setColumns(10);
JButton send = new JButton("Send");
send.addActionListener(this);
send.setBounds(312, 214, 105, 25);
contentPane.setLayout(null);
scrollPane = new JScrollPane();
scrollPane.setBounds(17, 5, 399, 196);
scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
contentPane.add(scrollPane);
chatText = new JTextArea();
chatText.setLineWrap(true);
chatText.setEditable(false);
chatText.setEnabled(false);
scrollPane.setViewportView(chatText);
contentPane.add(line);
contentPane.add(send);
}
#Override
public void run() {
try {
channel=new Socket(address, port);
System.out.println("Chat Connection accepted");
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(channel.getInputStream()));
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
out = null;
try {
out = new PrintWriter(channel.getOutputStream(),true);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String s="";
do {
// Send data
if (toBeSent.length()!= 0) {
out.println(toBeSent);
toBeSent="";
}
// Receive data
try {
if (in.ready()) {
s = in.readLine();
if ((s != null) && (s.length() != 0) && !s.equals(END_CHAT_SESSION)) {
chatText.append("INCOMING: " + s + "\n");
}
if(s.equals(END_CHAT_SESSION)){
chatText.append("Client disconnected.");
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} while(!s.equals(END_CHAT_SESSION));
channelIsStillOpen=false;
line.setEditable(false);
line.setEnabled(false);
if(channel!=null){
try {
channel.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
channel=null;
}
}
#Override
public void windowActivated(WindowEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void windowClosed(WindowEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void windowClosing(WindowEvent arg0) {
if(channelIsStillOpen){
out.println(END_CHAT_SESSION);
}
dispose();
}
#Override
public void windowDeactivated(WindowEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void windowDeiconified(WindowEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void windowIconified(WindowEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void windowOpened(WindowEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void actionPerformed(ActionEvent arg0) {
String s = line.getText();
if (!s.equals("")) {
chatText.append("OUTGOING: " + s + "\n");
// Send the string
toBeSent=s;
}
line.setText("");
}
}
edit: I have even edited the code so that the class being used is always the same! Nothing!
I think you are missing this at the end of your constructor:
this.setVisible(true);
also, why don't you set? setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);, why do you want to keep the application opened?

Categories