I have this problem in my system where when I scan the card on RFID, it displays the UID using System.out.println(str); but when I passed it thru jTextField.setText(str);, it doesn't display the UID. Also, the weird part is, when i try to System.out.println(jTextField.getText()); it display the UID.
Can someone help me with this problem? And explain if possible why does it happen?
This is my main class:
public class IDSystem {
public static String devicePortName = "Arduino Uno";
public static SerialPort arduinoPort = null;
public static InputStream arduinoStream = null;
public static int PACKET_SIZE_IN_BYTES = 8;
public static void main(String[] args) {
int len = SerialPort.getCommPorts().length;
SerialPort serialPorts[] = new SerialPort[len];
serialPorts = SerialPort.getCommPorts();
for (int i = 0; i < len; i++) {
String portName = serialPorts[i].getDescriptivePortName();
if (portName.contains(devicePortName)) {
arduinoPort = serialPorts[i];
arduinoPort.openPort();
break;
}
}
PacketListener listener = new PacketListener();
arduinoPort.addDataListener(listener);
Login l = new Login();
l.setVisible(true);
}
}
This is my PacketListener class:
public final class PacketListener implements SerialPortPacketListener {
String ex = "/";
String id;
#Override
public int getPacketSize() {
return IDSystem.PACKET_SIZE_IN_BYTES;
}
#Override
public int getListeningEvents() {
return SerialPort.LISTENING_EVENT_DATA_RECEIVED;
}
#Override
public void serialEvent(SerialPortEvent event) {
byte[] newData = event.getReceivedData();
String str = new String(newData).split("\n", 2)[0].replaceAll("\\s+", "");
int byteSize = 0;
try {
byteSize = str.getBytes("UTF-8").length;
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(PacketListener.class.getName()).log(Level.SEVERE, null, ex);
}
if (byteSize == IDSystem.PACKET_SIZE_IN_BYTES) {
System.out.println(str);
Login l = new Login();
l.jTextField.setText(l.jTextField.getText() + str);
System.out.println(l.jTextField.getText());
}
}
}
I'm assuming that your jtextfield is an instance of javax.swing.JTextField.
If it doesn't display the text you specified, check that:
You are setting the text on the correct JTextField instance,
You are adding the correct JTextField instance to a container (JPanel, etc...) that is being displayed.
As a last resort, if it's because you added the JTextField instance to its container after the container was already showing on the screen, try container.validate(); container.repaint(); .
If you could show the code for your Login class and how your jtextfield is being added to a container and displayed on the screen that would help in diagnosing the problem.
Related
I have been working on this code for a really long time and i just can't seem to figure out my problem. i want to be able to play a list of songs one right after another and i thought i would be able to do that with a simple recursive method that delays the average length of a song, and have it call the next song and play it... However it only plays the very first song and then stops after that and nothing else happens... I have asked countless people to look at this and nobody can help me out.. And no this is not a school project, it is a music player that my mother would like me to use at a party in the next upcoming weekend, so this is like my last ditch effort... Any help with this would be greatly appreciated!!!
private JLabel messageLabel;
private JButton playlist;
private JPanel panel;
BufferedImage image;
AudioStream audioStream1, audioStream2, audioStream3;
//Object[] music = new Object[3];
private final int WINDOW_WIDTH = 800;
private final int WINDOW_HEIGHT = 525;
// File destinationss
private String s1 = "C:\\Users\\Tony\\Desktop\\Java\\NetBeansProjects\\Gui Stuff\\src\\No_Pressure.wav";
private String s2 = "C:\\Users\\Tony\\Desktop\\Java\\NetBeansProjects\\Gui Stuff\\src\\Grateful_Dead_-_Touch_of_Grey.wav";
private String s3 = "C:\\Users\\Tony\\Desktop\\Java\\NetBeansProjects\\Gui Stuff\\src\\Stairway_to_Heaven_Led_Zeppelin_Lyrics.wav";
InputStream in1 = new FileInputStream(s1);
InputStream in2 = new FileInputStream(s2);
InputStream in3 = new FileInputStream(s3);
private ArrayList music;
public JukeBoxWithArrays() throws IOException {
music = new ArrayList();
audioStream1 = new AudioStream(in1);
audioStream2 = new AudioStream(in2);
audioStream3 = new AudioStream(in3);
music.add(audioStream1);
music.add(audioStream2);
music.add(audioStream3);
setTitle("Juke Box Playlist");
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
messageLabel = new JLabel("Click the Button to play the playlist");
// Create the Playlist button
playlist = new JButton("Playlist number 1");
// Register the event Listener
playlist.addActionListener(new PlaylistListener());
// Create the panel
panel = new JPanel();
image = ImageIO.read(new File("C:\\Users\\Tony\\Desktop\\Java\\NetBeansProjects\\Gui Stuff\\src\\jukebox2.jpg"));
panel.add(messageLabel);
panel.add(playlist);
panel.add((new JLabel(new ImageIcon(image))));
// Add the panel to the Content Pane
add(panel);
// Display the Window
setVisible(true);
}
private class PlaylistListener implements ActionListener {
int x = 0;
public void actionPerformed(ActionEvent e) {
try {
playMusic(x);
} catch (InterruptedException ex) {
Logger.getLogger(JukeBoxWithArrays.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void playMusic(int x) throws InterruptedException {
if (x > music.size()) {
AudioPlayer.player.stop((InputStream) music.get(x));
} else {
AudioPlayer.player.start((InputStream) music.get(x));
}
Thread.sleep(5 * 60 * 1000); // I believe this is where I am running into my problem
playMusic(x++);
}
}
#SuppressWarnings("restriction")
public static void main(String[] args) throws Exception {
JukeBoxWithArrays jbwa = new JukeBoxWithArrays();
jbwa.pack();
}
}
It seems your code is failing for the same reason this:
private static int x = 0;
public static void main(String[] args) throws ParseException {
int x = 0;
doSomething(x);
doSomething(x);
doSomething(x);
doSomething(x);
doSomething(x);
}
private static void doSomething(int x) {
System.out.println(x++);
}
Outputs this:
0
0
0
0
0
Your Listener has an x field, that your are passing by value between the methods. You should remove the x argument on playMusic(), so everytime it increments x, it would use the object field instead.
I am writing GUI for a chat, and I have problem I can't seem to find a solution.
When button Send is clicked variable OKpressed should change to true and in function getUserInput it should recognize it changed but it doesn't..
It's acting like it still says false..
I tried printing out in Send that works, so problem is only that functiong getUserInput doesn't recognize variable as changed
Any help is appreciated..Here's the code
I can't attach all other classes so you can start it, but everything is working except the problem mentioned above
public class Chat extends Process {
public static class myFrame extends JFrame{
/** Creates a new instance of myFrame */
private JTextArea ChatBox=new JTextArea(10,45);
private JScrollPane myChatHistory=new JScrollPane(ChatBox,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
private JTextArea UserText = new JTextArea(5,40);
private JScrollPane myUserHistory=new JScrollPane(UserText,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
private JButton Send = new JButton("Send");
private JTextField User=new JTextField(20);
private String ServerName;
private String UserName;
boolean OKPressed = false;
String poruka;
public myFrame() {
setResizable(false);
setTitle("Client");
setSize(560,400);
Container cp=getContentPane();
cp.setLayout(new FlowLayout());
cp.add(new JLabel("Chat History"));
cp.add(myChatHistory);
cp.add(new JLabel("Chat Box : "));
cp.add(myUserHistory);
cp.add(Send);
cp.add(User);
Send.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
poruka=(String)UserText.getText();
OKPressed = true;
}
});
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
}
static myFrame t=new myFrame();
public Chat(Linker initComm) {
super(initComm);
}
public synchronized void handleMsg(Msg m, int src, String tag){
if (tag.equals("chat")) {
System.out.println("Message from " + src +":");
System.out.println(m.getMessage());
t.ChatBox.append(src + ":" + m.getMessage() + "\n");
}
}
public String getUserInput() throws Exception {
while (t.OKPressed == false){}
String chatMsg=t.poruka;
return chatMsg;
}
public IntLinkedList getDest(BufferedReader din) throws Exception {
System.out.println("Type in destination pids with -1 at end:");
System.out.println("Only one pid for synch order:");
IntLinkedList destIds = new IntLinkedList(); //dest for msg
StringTokenizer st = new StringTokenizer(din.readLine());
// StringTokenizer st = new StringTokenizer(t.poruka);
while (st.hasMoreTokens()) {
int pid = Integer.parseInt(st.nextToken());
if (pid == -1) break;
else destIds.add(pid);
}
return destIds;
}
public static void main(String[] args) throws Exception {
String baseName = "Chat";
int myId = Integer.parseInt(args[0]);
int numProc = Integer.parseInt(args[1]);
Linker comm = null;
comm = new CausalLinker(baseName, myId, numProc);
Chat c = new Chat(comm);
for (int i = 0; i < numProc; i++)
if (i != myId) (new ListenerThread(i, c)).start();
BufferedReader din = new BufferedReader(
new InputStreamReader(System.in));
while (true){
System.out.println(c.getUserInput());
String chatMsg = c.getUserInput();
if (chatMsg.equals("quit")) break;
t.ChatBox.append(myId + ": " + chatMsg +"\n");
IntLinkedList destIds = c.getDest(din);
comm.multicast(destIds, "chat", chatMsg);
}
}
}
As you wrote, I cannot run you code, so it is kind of guess, however I think the problem is in empty infinite loop:
while (t.OKPressed == false){}
if you add anything inside, even:
while(t.OKPressed == false){
System.out.println();
}
It should work. It is connected with problem better described for example here: Threads: Busy Waiting - Empty While-Loop, and in post which duplicate it is.
I've been trying to populate a JPanel (here reffered to as 'BulletinsJPanel') in a class reffered to as 'Home.java' with a textfield (here reffered to as 'readerSetTxtJTextField') when a JLabel is clicked. ReaderPanel is in another class called 'Reader.java' which is supposed to read the contents of a text file and populate a JTextField object with a line of text.
I'm using netbeans which doesn't show me any code error highlights.
I would really appreciate some help in getting the textfield 'readerSetTxtJTextField' to show. Thanks a lot in advance.
Heres my code:
// The class Home
package Panels;
public class Home extends javax.swing.JPanel {
// Here's a method in the class 'Home.java' which should populate 'BulletinsJPanel' with the contents
private void MouseClickedList(java.awt.event.MouseEvent evt) {
BulletinsJPanel.add(Reader.readerMouseClickedList());
BulletinsJPanel.revalidate();
BulletinsJPanel.repaint();
}
}
// Now the class Reader below
package Database;
public class Reader {
public static JTextField readerSetTxtJTextField;
public static JTextField readerMouseClickedList() {
try {
// Our code
String fileURL = "/D:/TestFile.txt/";
List<String[]> matches = new ArrayList<String[]>();
String finalText;
FileInputStream fileInputStream = new FileInputStream(fileURL);
DataInputStream dataInputStream = new DataInputStream(fileInputStream);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(dataInputStream));
String stringLine;
while((stringLine = bufferedReader.readLine()) != null) {
String splittable = "[\\s]", splitLenth = "{955}";
if(stringLine.startsWith("2013001")) {
String[] splits = stringLine.split(splittable + splitLenth );
matches.add(splits);
}
}
dataInputStream.close();
for(String[] items : matches) {
int itemsLength = items.length;
int i;
for(i = 0; i <= itemsLength; i++) {
finalText = (items[i]);
readerSetTxtJTextField = new JTextField();
readerSetTxtJTextField.setText(finalText);
}
}
} catch (Exception e) {
// Catch exception if any
System.err.println("Error: " + e.getMessage());
}
return readerSetTxtJTextField;
}
}
As a quick fix to your error , Change :
for(i = 0; i <= itemsLength; i++)
to
for(i = 0; i < itemsLength; i++)
First of all i am brand new to Java : /
I have been trying to solve this problem on my own for about 2 days now but cant get around it the problem is i am trying to implement a variable change listener. I have tried without successes to implement Observer and Observable to my project but whit no successes at best i came up by wrapping some elements of the code in to while loops but that well fails.
Any how this is my class and if you look at it i have some global variables defined after the constructor i need to listen for a change in all of those global variables if one changes i would like to execute a method.
I have been told JavaFX has methods that can listen to variables can someone confirm this.
Anyhow thanks for help in advance.
public class Tower_Controller {
public Tower_Controller() {
}
//Global variables
String isSelected = null;
int hasModules = 0;
int cap_s = 0;
int cpu_s = 0;
int cap = 0;
int cpu = 0;
int shield = 0;
int armor = 0;
double em = 00.00;
double th = 00.00;
double ki = 00.00;
double ex = 00.00;
public void invoke() {
Invoke_GUI runnable = new Invoke_GUI();
final JLabel tower_name = runnable.tower_name;
final JComboBox tower_select = runnable.tower_select;
final JTree module_browser = runnable.module_browser;
final JTree selected_modules = runnable.selected_modules;
final JProgressBar cap_bar = runnable.cap_bar;
final JProgressBar cpu_bar = runnable.cpu_bar;
final JLabel em_res = runnable.em;
final JLabel th_res = runnable.thermic;
final JLabel ki_res = runnable.kinetic;
final JLabel ex_res = runnable.explosive;
tower_select.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (isSelected != null) {
Events evt = new Events();
evt.towerSelected(isSelected);
} else {
tower_name.setText(tower_select.getSelectedItem().toString());
isSelected = tower_name.toString();
}
}
});
removeTower(tower_name);
runnable.setVisible(true);
}
public void updateValues(final JProgressBar cap_bar, final JProgressBar cpu_bar, final JLabel em_res,
final JLabel th_res, final JLabel ki_res, final JLabel ex_res){
cap_bar.setMaximum(cap);
cap_bar.setString(cap_s + " / " + cap);
cap_bar.setStringPainted(true);
cpu_bar.setMaximum(cpu);
cpu_bar.setString(cpu_s + " / " + cpu);
cpu_bar.setStringPainted(true);
String em_v = String.valueOf(em);
em_res.setText(em_v);
String th_v = String.valueOf(th);
th_res.setText(th_v);
String ki_v = String.valueOf(ki);
ki_res.setText(ki_v);
String ex_v = String.valueOf(ex);
ex_res.setText(ex_v);
}
public void updateList(final ArrayList<String> nodes, final JTree selected_modules) {
DefaultMutableTreeNode nod = new DefaultMutableTreeNode();
for (int i = 0; i < nodes.size(); i++) {
nod.add(new DefaultMutableTreeNode(nodes.get(i)));
}
selected_modules.setModel(new DefaultTreeModel(nod));
}
public void removeTower(final JLabel tower_name) {
tower_name.addMouseListener(new MouseListener() {
#Override
public void mouseClicked(MouseEvent e) {
if (hasModules == 1 & isSelected != null) {
Events evt = new Events();
evt.towerHasModules();
} else if (isSelected == null) {
} else {
tower_name.setText("No Control Tower selected");
isSelected = null;
}
}
#Override
public void mousePressed(MouseEvent e) {
}
#Override
public void mouseReleased(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
}
});
}
public JLabel setTowerName(JLabel a, String name) {
a.setText(name);
return a;
}
}
The general procedure to be notified of a change to a variable is as follows:
First, make the variables private.
Create two methods for each variable, one which sets its value to an argument (often called setX(), where X is the variable name), the other which retrieves its value (getX())
Everywhere you need to read or set the variable, call the methods instead.
In the setX() method, call notifyObserver() on your Observers, in a loop.
And there you go! Now every time the variable is changed, registered Observers are notified. The key part of this solution is that the variables have to be private, so that no code can set their values without going through the setX() methods.
I have a JTable that I'm inserting rows into using data found on the internet. When I run the code that fills the list directly from the main function, I can see each row being inserted at the same time 'fireTableRowsInserted' is called - which is the behavior I want. However, when I run that same code from a JButton's ActionListener (during 'ActionPreformed()', the table does not update until the thread/event has finished.
I think the problem has something to do with threads, but I am not very familiar with how thread work and am not sure where to start.
Here is an example of the problem:
public class Main {
static TestModel myTestModel = new TestModel();
public static void main(String[] args) {
JFrame testFrame = new JFrame();
JTable table = new JTable(myTestModel);
JButton button = new JButton("Load");
testFrame.getContentPane().add(new JScrollPane(table), BorderLayout.CENTER);
testFrame.getContentPane().add(button, BorderLayout.PAGE_END);
testFrame.pack();
testFrame.setVisible(true);
testFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
button.addActionListener(new ActionListener(){
#Override public void actionPerformed(ActionEvent e) {
//When openURLStr is called here, the table in the JFrame doesn't add rows until
// the function has exited.
openURLStr("http://download.oracle.com/javase/1.4.2/docs/api/java/awt/Component.html", true);
}
});
//When openURLStr is called here, the table in the JFrame adds rows at the same time the
// list in the table-model adds a row. (the desired behavoir)
openURLStr("http://download.oracle.com/javase/1.4.2/docs/api/java/awt/Component.html", true);
myTestModel.myArrayList.clear();
myTestModel.fireTableDataChanged();
}
static class TestModel extends AbstractTableModel {
ArrayList<String> myArrayList = new ArrayList<String>();
#Override public int getColumnCount() { return(3); }
#Override public int getRowCount() { return(myArrayList.size()); }
#Override public Object getValueAt(int row, int col) {
char c = '*';
String rowStr = myArrayList.get(row);
if ( rowStr.length() > col ) c = rowStr.charAt(col);
return(c);
}
public boolean add(String line) {
int row = myArrayList.size();
if ( row < 100 ) {
myArrayList.add(line);
this.fireTableRowsInserted(row, row);
return(true);
}
else {
return(false);
}
}
}
private static void openURLStr(String urlStr, boolean lookForLinks) {
try {
URL url = new URL(urlStr);
InputStreamReader isr = new InputStreamReader(url.openConnection().getInputStream());
BufferedReader br = new BufferedReader(isr);
ArrayList<String> linksFound = new ArrayList<String>();
if ( br != null ) {
String strLine = br.readLine();
//row added to table-model here:
boolean continueParse = myTestModel.add(strLine);
//this code is mainly to induce more time between each addition of a line.
while ( strLine != null && continueParse ) {
if ( lookForLinks && strLine != null ) {
String ahrefStr = "a href=\"";
int start_i = strLine.indexOf(ahrefStr) + ahrefStr.length();
if ( start_i > -1 ) {
int end_i = strLine.indexOf("\"", start_i+1);
if ( end_i > -1 && end_i > start_i ) {
linksFound.add(strLine.substring(start_i, end_i));
}
}
}
strLine = br.readLine();
}
br.close();
}
for ( String link : linksFound ) {
openURLStr(link, false);
}
} catch (IOException e) {
}
}
}
The ActionListener's actionPerformed is executed on the event dispatch thread and this will be blocked by your code inside. Thus the GUI freezes for this time and no updates will be shown at all.
Try to separate the "long running" URL call e.g. in a SwingWorker.