In my code i have made my JtextArea public and in my code i have called the jtextare and setTextArea however when i press that button because its a thread it doesnt allow me to change the JTextArea whenever my scanner works
public void scan() throws InterruptedException {
try {
//This is the part i called it but doesnt change the jtextfield into getUid
Login login = new Login();
login.jTextField_username.setText(getUid);
TerminalFactory factory = TerminalFactory.getDefault();
List<CardTerminal> terminals = factory.terminals().list();
System.out.println("Terminals: " + terminals);
CardTerminal terminal = terminals.get(0);
System.out.println("Waiting for a card..");
if (terminal == null) {
return;
}
terminal.waitForCardPresent(0);
Card card = terminal.connect("T=1");
System.out.println("Card: " + card);
System.out.println("Protocol: " + card.getProtocol());
CardChannel channel = card.getBasicChannel();
ResponseAPDU response = channel.transmit(new CommandAPDU(new byte[]{(byte) 0xFF, (byte) 0xCA, (byte) 0x00, (byte) 0x00, (byte) 0x00}));
System.out.println("Response: " + response.toString());
if (response.getSW1() == 0x63 && response.getSW2() == 0x00) {
System.out.println("Failed");
}
System.out.println("UID: " + bin2hex(response.getData()));
getUid = bin2hex(response.getData());
} catch (CardException ex) {
Logger.getLogger(CardId.class.getName()).log(Level.SEVERE, null, ex);
}
}
Note that we cannot compile nor run a code snippet, and so any answer given will need to include guesses, but that being said, I think that the problem is that you have a faulty assumption here:
//This is the part i called it but doesnt change the jtextfield into getUid
Login login = new Login(); // **** A ****
login.jTextField_username.setText(getUid); // **** B ****
At line A you create a new Login object, but is this the actual displayed object? I have a feeling that it's not, that you've already created and displayed the Login window, and are now creating a new one, one never displayed, and on line B are changing its state (the text held in one of its text components). If my guess is correct, then the better solution is to change the state of the actual displayed Login object, not a new and distinct one that you're creating in this method. How to do this? Impossible to state give the information that you've given so far.
If you want a more robust answer, then you will want to create and post a valid [Minimal, Complete, and Verifiable example](Minimal, Complete, and Verifiable example) in with your question -- please check out the link as it will explain all.
Other unrelated issues:
Your question mentions JTextArea, but the code suggests that we're dealing with a JTextField -- which is it?
Your question text suggests that you're mixing Scanner/console input with a Swing GUI. If this is so, I strongly urge you to not go this route, to get all input via the GUI. This will save you hours of debugging and frustration.
Related
Hey guys i'll like to do the project call "RFID Management System"
I found some samlpe code from some websites and add a few codes into it.
My RFID can read the number from mifare card right now, but I Already face the problem : How to create a loop for my RFID machine in order to read the card again and again without pushing the "RUN" button in Eclipse
import java.util.List;
import javax.smartcardio.*;
import javax.xml.bind.DatatypeConverter;
public class Blog {
public static void main(String[] args) {
try {
// Display the list of terminals
TerminalFactory factory = TerminalFactory.getDefault();
List<CardTerminal> terminals = factory.terminals().list();
System.out.println("Terminals: " + terminals);
// Use the first terminal
CardTerminal terminal = terminals.get(0);
// Connect wit hthe card
Card card = terminal.connect("*");
System.out.println("card: " + card);
CardChannel channel = card.getBasicChannel();
// Send Select Applet command
ResponseAPDU answer = channel.transmit(new CommandAPDU(new byte[] { (byte)0xFF, (byte)0xCA, (byte)0x00, (byte)0x00, (byte)0x00 } ));
// Send test command
answer = channel.transmit(new CommandAPDU(new byte[] { (byte)0xFF, (byte)0xCA, (byte)0x00, (byte)0x00, (byte)0x00 } ));
byte r[] = answer.getData();
String hex = DatatypeConverter.printHexBinary(answer.getBytes());
System.out.println("Response: " + hex);
// Disconnect the card
card.disconnect(false);
} catch(Exception e) {
System.out.println("Ouch: " + e.toString());
}
}
}
U might be aware of arduino programming , right?, there we have a loop function(), so whatever code we write inside it loops for ever. That is the logic for these things (like rfid, finger print scanner, temp sensors, motion detectors etc) . So use the same technology here. Put ur code inside a
while(1){
}
loop.
This will iterate ur code for ever. hence u will get the desired o/p. U can flash ur card as many times as u want.
Make sure that the code for reading and processing the data should only come inside the loop. Otherwise it takes much memory and may crash ur code.
Im making an application which (to sum it up in very basic terms) acts as an interface to another application, so rather than having to view things through the console I can see them in a nice Swing window. I had made an earlier version of this, which simply output everything into a JTextArea as plain text. It worked fine, and I had no issues with it. But feeling the need to expand out this very basic program a bit, I decided to try and color coat the messages so that someone other than myself could find their way around the output a bit more easily. First part of the program involves this:
class ServerIOStream extends Thread {
private boolean _isRunning = false;
private Process _serverProcess = null;
private BufferedReader input = null;
private PrintWriter writer = null;
public void run() {
try {
_serverProcess = Runtime.getRuntime().exec(PropertiesReader.getLaunchString());
input = new BufferedReader(new InputStreamReader(_serverProcess.getInputStream()));
_isRunning = true;
String line;
while ((line = input.readLine()) != null)
MainWindow.writeToOutput(line, 0);
_isRunning = false;
MainWindow.writeToOutput("Service has stopped...", 1);
} catch (IOException ex) {
MainWindow.writeToOutput(ex.getMessage(), 3);
_isRunning = false;
}
}
public boolean ServerStatus(){
return _isRunning;
}
}
My apologies if things seem a bit messy and some stuff does not make sense, as it is quite late and I have been tinkering with the code in strange ways to try and get this to work as desired.
NOW, as you can see, upon being run the thread will pick up a runtime, and then via a loop just spit out what it receives into method. That method (Code shown below) is responsible for delivering the content to JEditorPane. Here is how the MainWindow.writeToOutput() function works.
private static String output;
public static void writeToOutput(String message, int inputType){
String finalMessage = null;
String type = null;
switch(inputType){
case 0: // For input from the server
finalMessage = message;
break;
case 1: // General info from the GUI
type = "INFO";
break;
case 2: // Warnings from the GUI
type = "WARN";
break;
case 3: // Error messages from the GUI
type = "ERROR";
break;
default: // Unknown messages
type = "UNKNOWN";
break;
}
if(inputType == 1 || inputType == 2 || inputType == 3){
finalMessage = String.format("[" + new SimpleDateFormat("HH:mm:ss").format(new Date()) + " GUI %s" + "]: %s", type, message);
if(inputType == 1)
finalMessage = "<font color=\"" + PropertiesReader.getInfoColor() + "\">" + finalMessage + "</font>";
else if(inputType == 2)
finalMessage = "<font color=\"" + PropertiesReader.getWarnColor() + "\">" + finalMessage + "</font>";
else if(inputType == 3)
finalMessage = "<font color=\"" + PropertiesReader.getErrColor() + "\">" + finalMessage + "</font>";
}
else if(inputType == 0){
try{
String s = finalMessage;
s = s.substring(s.indexOf("[") + 1);
s = s.substring(0, s.indexOf("]"));
if(s.contains("INFO"))
finalMessage = "<font color=\"" + PropertiesReader.getInfoColor() + "\">" + finalMessage + "</font>";
else if(s.contains("WARN"))
finalMessage = "<font color=\"" + PropertiesReader.getWarnColor() + "\">" + finalMessage + "</font>";
else if(s.contains("ERROR"))
finalMessage = "<font color=\"" + PropertiesReader.getErrColor() + "\">" + finalMessage + "</font>";
}
catch(StringIndexOutOfBoundsException ex){
finalMessage = "<font color=\"red\">" + finalMessage + "</font>";
}
}
if(output != null)
output += finalMessage + "<br>";
else
output = finalMessage + "<br>";
ServerOutputTextArea.setText(output);
if(inputType == 0 || inputType == 1 || inputType == 2)
System.out.println(finalMessage);
else
System.err.println(finalMessage);
if(AutoScrollCheckbox.isSelected())
ServerOutputTextArea.setCaretPosition(ServerOutputTextArea.getDocument().getLength());
finalMessage = null;
message = null;
System.out.println("\nLength: " + output.length());
}
I apologize yet again if the code is hard to follow or nonsensical. As I said before, it is late and I was just tinkering with it in all sorts of ways in an attempt to get it to work.
Basically, input goes as follows. Argument 1 is the message, and argument 2 is the type of message represented as an int. 0 is used to represent messages coming from the runtime displayed before, 1 is for general info, 2 is for warnings, and 3 is for errors/exceptions. If argument 2 is equal to zero, then the first chunk of the message (Typically formatted as such: "[HH:MM:SS Type]") will be dissected to determine its type.
The code I have made is very makeshift and clunky and I understand that- however that is not the topic of discussion right now. The issue at hand is that first, each time something new is output to the JEditorPane the pane will briefly go blank (for a fraction of a second) before the text reappears with the new message at the bottom of it. Honestly when it happens from a single message its hard to notice, but when the process is spitting messages out left and right the program will flicker and flash too much, and cut and scroll down to random points in the application inexplicably as the autoscroll struggles to keep up.
The second issue is the memory issue. What happens is when the application first starts and before the process has really started to get going it sits calmly around 50MB of memory usage, and hogs little to none of my precious CPU cycles. But suddenly as the process gives messages faster and faster, memory usage seems to increase exponentially. Going from 50MB, to 100MB, to 500MB, and normally up to a max of around 1.5GB to 1.8GB of memory usage.
At first, I was not sure if this was being caused by the JEditorPane, but then I ran a small experiment. I went back to using JTextArea and left most everything the same and sure enough, even when the process was spitting out info like mad I only ever saw peaks of around 70MB of memory usage, and the flickering and autoscroll struggle that I described was non-existent.
Here is what I saw in testing:
JTextArea | Output contained 47553 characters, and memory usage was at 52MB
JEditorPane | Output contained 50531 characters, and memory usage was at 1550MB
ALSO:
On one final note I would like to say that I am still not very experienced with Java, or when it comes to making applications with visual interfaces in general. Thank you very much to all who answer.
I decided to try and color coat the messages
I would use a JTextPane instead of a JEditor pane. I find working with attributes easier than working with HTML and don't know for sure but would guess the memory requirement would be smaller since you don't need to parse the HTML.
Using attributes is straight forward:
JTextPane textPane = new JTextPane();
textPane.setText( "one\ntwo\nthree\nfour\nfive\nsix\nseven\neight" );
StyledDocument doc = textPane.getStyledDocument();
// Define a keyword attribute
SimpleAttributeSet keyWord = new SimpleAttributeSet();
StyleConstants.setForeground(keyWord, Color.RED);
StyleConstants.setBackground(keyWord, Color.YELLOW);
StyleConstants.setUnderline(keyWord, Boolean.TRUE );
StyleConstants.setBold(keyWord, true);
// Define green attribute
SimpleAttributeSet green = new SimpleAttributeSet();
StyleConstants.setFontFamily(green, "Courier New Italic");
StyleConstants.setForeground(green, Color.GREEN);
// Change attributes on some text
doc.setCharacterAttributes(0, 5, keyWord, false);
doc.setCharacterAttributes(20, 4, green, true);
// Add some text with attributes
try
{
doc.insertString(3, "\ngreen text", green);
}
catch(Exception e) {}
I would use StringBuilder rather than String for the
private static String output
Also simple setText() replaced with setDocument()
Document doc=ServerOutputTextArea.getEditorKit().createDefaultDocument();
ServerOutputTextArea.getEditorKit().read(new StringReader(output),doc,0);
ServerOutputTextArea.setDocument(doc);
setText() calls remove(0, getLength()) for the document and could leave some cached data - positions, image cache etc.
I'm doing a client/server program in Java (including a GUI).
I've got the following code in the client:
public class SBListener implements ActionListener{
public void actionPerformed(ActionEvent e){
try{
outToServer.writeUTF(usn.getText().trim());
System.out.println("sent username to server");
playerExists = inToClient.readBoolean();
System.out.println("past getting player");
System.out.println("player exists = " + playerExists);
}catch(IOException a){
System.err.println(a);
}
if(playerExists == false){
JButton submitInfo = new JButton("submit info");
submitInfo.addActionListener(new SBNewInfoListener());
init.add(new JLabel(""));//dummy element to get the right alignment
init.add(new JLabel("First Name:"));
init.add(fn);
init.add(new JLabel("Last Name:"));
init.add(ln);
init.add(submitInfo);
add(init, BorderLayout.WEST);
init.setVisible(true);
init.revalidate();
init.repaint();
}
}
}
And the following code in the Server:
String username = inp.readUTF();
System.out.println(username);
out.writeBoolean(false);
System.out.println("wrote boolean, waiting for fn/ln/un");
fn = inp.readUTF();
System.out.println("got fn");
ln = inp.readUTF();
un = inp.readUTF();
But when the button that calls SBListener is clicked, the program freezes when it gets to the point where the Server is waiting for fn/ln/username. I added a bunch of system.out statements for debugging and I get up to the one that says "wrote boolean, waiting for fn/ln/un".
Basically, I'm trying to update the screen after the Server returns a false value. Specifically, I want to add two text fields for first & last name. I then want to send those values to the server.
Can anyone tell me how to fix this? Thanks in advance for any help!
Don't execute client/server code in an ActionListener. This will cause the Event Dispatch Thread to block while waiting for a response from the server. When EDT is blocked the whole GUI freezes.
Read the section from the Swing tutorial on Concurrency for more information. You need so use a separate Thread for the client/server code. Or you can use a SwingWorker as discussed in the tutorial.
My guess is that outToServer isn't being flushed. I would guess (although I can't tell from your sample code) that outToServer is a DataOutputStream. You need to call .flush to get the data out of the buffer and onto the wire.
Try this:
outToServer.writeUTF(usn.getText().trim());
outToServer.flush();
I have a problem about creating a textfile with the name I want.
I want to create a textfile named : 'username' Subjects.
private void saveSubjects(){
RegisterFrame r = new RegisterFrame();
String username = r.txtUser.getText();;
try{
FileWriter f = new FileWriter(username + "" + "Subjects" + ".txt", true);
String subjects[] = lstSubjects.getItems();
for(int i = 0; i<subjects.length; i++){
f.write(subjects[i] + "\r\n");
}
f.close();
JOptionPane.showMessageDialog(null, "Data saved!", "Data Saved", JOptionPane.INFORMATION_MESSAGE);
}catch(Exception e){
JOptionPane.showMessageDialog(null, "Nothing Inputted!", "Error", JOptionPane.ERROR_MESSAGE);
}
}
I want to get the username from RegisterFrame as it is inputted there but it's not working.
I know it's a simple thing but I'm still a beginner in this. How can I solve this?
Thanks in advance
try this:
String username = r.txtUser.getText();
System.out.println("The loaded username is: " + username);
then you will see where your problem is : writing into the file OR getting the username text.
If the problem is in getting the text, consider other way of getting it or modify the question by removing the file write part and specifiing the username getting part.
Otherwise, IDK where the error is.
BTW: how is it not working? the file is not created at all? do you see any errors? the file has wrong name? please specify
Your code for writing the file seems to be fine. Based on your code I tried this which worked perfectly:
public static void main(String[] args) {
FileWriter f = null;
try {
f = new FileWriter("Subjects.txt", true);
String subjects[] = {"subject1", "subject2"};
for (String subject : subjects) {
f.write(subject + "\r\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
IOUtils.closeQuietly(f);
}
}
I'd say your problem is elsewhere.
Please note that best practice dictates that Closeable objects such as FileWriter should be closed in a finally block
Assuming new RegisterFrame() starts up a GUI window, the issue is your code runs before you have a chance to type in your name. Instead you need to use event listeners to capture the contents of text fields, otherwise the code to get the name runs immediately after the window opens, long before you have a chance to type anything in.
The timeline is like this:
RegisterFrame starts a new thread to display the GUI without blocking your code
Your code immediately pulls "" from txtUser, which is of course empty
Now you type your name in
Nothing happens, because nothing in your code is paying attention to that action
Instead, it should be:
RegisterFrame starts a new thread to display the GUI without blocking your code
The method returns, or starts doing work that isn't dependent on the GUI
Now you type your name in
An event listener is triggered from the new thread, and the associated action to get the name and write to a file is executed
You have to decide what sort of listener makes sense for your use case, for instance you might want to wait until the user clicks a button (that says "Submit" or "Write File" for instance) and register an ActionListener on that button. Then you put your username polling and file writing behavior in that action* and you're golden!
*I should add that in truth you want to do as little as possible in ActionListeners, and it would be better to check if the username is not empty, then pass the actual work off to another thread, for instance with a SwingWorker, but for your purposes I suspect it will be alright to not worry about that.
I have created a text file in which to store some variables which are taken from text fields. But in order to submit new variables to this text file, I need to close my program and reopen it. The dispose(); command closes the JFrame taking me to my main menu but upon opening the menu again and submitting different values, the values from the previous time have been resubmitted. Is there a simple way to amend this?
Here is my write to .txt code:
public class writeto {
static String data = AddProperty.inputdata;
BufferedWriter out;
public writeto(){
try{
out = new BufferedWriter(new FileWriter("writeto.txt", true));
out.write(data);
out.newLine();
out.close();
}catch(IOException e){
System.out.println("you have an error" + e);
}
}
}
and where the method is called in my addproperty class
submitproperty.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
housenumber1 = houseNumber.getText();
streetname1 = streetName.getText();
town1 = town.getText();
postcode1 = postcode.getText();
beds1 = beds.getText();
price1 = price.getText();
type1 = type.getText();
inputdata = housenumber1 + " " + streetname1 + " " + town1 + " " +
postcode1 +" " + beds1 + " " + price1 + " " + type1;
writeto write = new writeto();
dispose();
}
});
}
From your menu you should always create a new JFrame with new widgets (like text fields). A new text field has no content, if you show a text field again, it will still display it's previous content.
Additional remarks:
Please use standard naming conventions - not only when you show code to others. In your case: class names shall start with a capital letter, camel-case notation is preferred (writeto -> WriteTo)
The writeto class abuses the constructor. The code in your constructor does not create an writeto object but dumps some strings to a file. Put this kind of code to a method, not to a constructor.
The BufferedWriter will not be closed if an exception occurs. Look around at stackoverflow, a lot of questions/answers show the correct io-closeing pattern
disposing the jframe is a risk - the code is executed after pressing a button (correct?), inside a method on a button that is displayed on the frame (correct?). In that case the button may be disposed while a method on the button object is still executed.. Try setVisible(false) if you just want to hide the JFrame (like "close the dialog")
You would benefit greatly from using a database as opposed to a text file. Further your question displays a fundamental lack of knowledge of not only Swing, but basic CRUD (Create, Read, Update, Delete) functionality.
To answer your question you can clear your text field with textField1.setText("");
I would read up on using a database for storing data. It will make life much easier for you.