JAVA - Failed to iterate sphinx4 within swing component - java

I am using CMU sphinx, i am running my program but getting this error appears "Can't open microphone line with format PCM_SIGNED 16000.0 Hz, 16 bit, mono, 2 bytes/frame, big-endian not supported." Cannot start microphone. i want my program to listen voice using JButton whenever JButton clicked but i can only execute once in single button click. Next click will error as i stated above. please help me what is wrong.
This is what i am doing.
public class VoiceChat {
private static JPanel contentPane;
private static JTextField textField;
private static JTextField textField2;
private static JWindow window;
private static boolean alive = true;
private static String chatMessage;
private static boolean runTimer = true;
private static boolean OverSession = false;
private static Recognizer recognizer;
private static Microphone microphone;
public VoiceChat() {
ExecutorService executor = Executors.newFixedThreadPool(2);
FutureTask<String> CountTimer = new FutureTask<String>(
new ShowCounter());
FutureTask<String> talkMode = new FutureTask<String>(new DoTalk());
executor.submit(CountTimer);
initRecognize();
executor.submit(talkMode);
try {
System.out.println(talkMode.get(20, TimeUnit.SECONDS));
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (TimeoutException e) {
executor.shutdownNow();
e.printStackTrace();
} finally {
executor.shutdown();
}
}
public static void initGUI()
{
window = new JWindow();
window.setBounds(100, 100, 400, 200);
window.setLocationRelativeTo(null);
window.setOpacity(0.9f);
window.setVisible(true);
textField = new JTextField();
textField.setVisible(true);
textField.setEnabled(false);
textField.setBorder(new LineBorder(new Color(139, 0, 139), 2));
textField.setFont(new Font("Tunga", Font.BOLD, 36));
textField.setBounds(138, 83, 100, 53);
window.add(textField);
textField.setColumns(10);
JLabel lblNewLabel = new JLabel("Start Talking in 10 Seconds");
lblNewLabel.setVisible(true);
lblNewLabel.setForeground(new Color(0, 0, 255));
lblNewLabel.setFont(new Font("Batang", Font.PLAIN, 14));
lblNewLabel.setBounds(90, 83, 100, 53);
window.add(lblNewLabel);
}
public static void initRecognize()
{
ConfigurationManager cm = new ConfigurationManager(
VoiceChat.class.getResource("myconfig.xml"));
recognizer = (Recognizer) cm.lookup("recognizer");
recognizer.allocate();
microphone = (Microphone) cm.lookup("microphone");
if (!microphone.startRecording()) {
System.out.println("Cannot start microphone.");
recognizer.deallocate();
microphone.stopRecording();
}
}
public static boolean isAlive() {
return alive;
}
public static void setAlive(boolean alive) {
VoiceChat.alive = alive;
}
public static boolean isRunTimer() {
return runTimer;
}
public static void setRunTimer(boolean runTimer) {
VoiceChat.runTimer = runTimer;
}
public static boolean isOverSession() {
return OverSession;
}
public static void setOverSession(boolean overSession) {
OverSession = overSession;
}
public static String getChatMessage() {
return chatMessage;
}
public static void setChatMessage(String chatMessage) {
VoiceChat.chatMessage = chatMessage;
}
static class ShowCounter implements Callable<String> {
#Override
public String call() throws Exception {
Thread.sleep(5000);
Integer timeNote = 0;
initGUI();
try {
for (int i = 0; i < 10; i++) {
if (!isRunTimer()) {
textField.setVisible(false);
window.setVisible(false);
window.dispose();
break;
}
textField.setText(" " + (10 - i) + "");
timeNote = 10 - (10 - i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
textField.setVisible(false);
window.setVisible(false);
window.dispose();
setAlive(false);
setOverSession(true);
return timeNote.toString();
}
}
static class DoTalk implements Callable<String> {
#Override
public String call() throws Exception {
String resultText = "";
System.out.println("Start speaking. Press Ctrl-C to quit.\n");
while (isAlive()) {
Result result = recognizer.recognize();
if (result != null) {
resultText = result.getBestFinalResultNoFiller();
System.out.println((new StringBuilder())
.append("You said: ").append(resultText)
.append('\n').toString());
if (!resultText.isEmpty()) {
setRunTimer(false);
break;
}
// wordFilter.add(resultText);
} else {
System.out.println("I can't hear what you said.\n");
}
}
microphone.stopRecording();
if (recognizer.getState() == State.ALLOCATED) {
recognizer.deallocate();
}
setChatMessage(resultText);
return resultText;
}
public static void main(String[] args) {
JFrame frames = new JFrame();
frames.setTitle("Simple MultiThread");
frames.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frames.setBounds(100, 100, 450, 300);
frames.setResizable(false);
frames.setVisible(true);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(null);
frames.setContentPane(contentPane);
JButton btnStart = new JButton("Start");
btnStart.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
VoiceChat x = new VoiceChat();
System.out.println(getChatMessage());
}});
btnStart.setFont(new Font("Mangal", Font.BOLD, 16));
btnStart.setBounds(180, 166, 78, 23);
contentPane.add(btnStart);
}
}}
Thanks so much. Hope you can help me.

Related

JFreeChart | Not able to position a graph properly in a specific location inside a JPanel

I have a project that uses JFreeChart.
The chart that I am using is displaying correctly and works fine with the current code.
My problem is that I can only position the graph to the east, south, west, center or north of my JPanel.
My desire is to move this chart to any position inside my JPanel.
This is the short code snippet where I add my graph to the panSimulator JPanel. The problematic code is at the bottom of the ConfigurationFrame class:
public class ConfigurationFrame extends JFrame {
private KettlerBikeConnector bike1 = null;
private static final long serialVersionUID = 1L;
CrosshairDemo chd = new CrosshairDemo();
private JPanel panSimulator;
private PanelBikeSimulator panBSim;
private Timer timerBike;
private TimerListener listener;
private final int UPDATE_MS = 1000; // updates every second
private JTabbedPane tabPane;
private JPanel panConfiguration;
private JPanel panGame;
private JComboBox<String> cbxPort;
private JTextPane lblStatus;
// to have access to the textfield
public static JTextField txtEnergy;
public static JTextField txtDistance;
public static JTextField txtHeartRate;
public static JTextField txtTime;
public File path = null;
public int key = -1;
boolean run = true;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ConfigurationFrame frame = new ConfigurationFrame();
frame.setVisible(true);
// frame.pack(); // give a suitable size to window automatically
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
* #throws IOException
* #throws SAXException
* #throws ParserConfigurationException
*/
public ConfigurationFrame() throws ParserConfigurationException, SAXException, IOException {
setResizable(false);
setMinimumSize(new Dimension(1900, 1000));
setTitle("Bike Simulation ... I need a name ...");
setLocationRelativeTo(null);
addWindowListener(new WindowAdapter() {
#Override
public void windowClosed(WindowEvent arg0) {
try {
timerBike.stop();
bike1.close();
} catch (Exception e) {
log(e.getMessage());
}
}
});
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
getContentPane().setLayout(null);
// Panel
tabPane = new JTabbedPane(JTabbedPane.TOP);
tabPane.setFont(new Font("Tahoma", Font.PLAIN, 24));
tabPane.setBounds(0, 0, 1892, 994);
getContentPane().add(tabPane);
// Configuration-Panel
panConfiguration = new JPanel();
tabPane.addTab("Configuration", null, panConfiguration, null);
panConfiguration.setLayout(null);
// ComboBox for Kettler
cbxPort = new JComboBox<String>();
cbxPort.setFont(new Font("Tahoma", Font.PLAIN, 24));
cbxPort.setBounds(734, 5, 247, 49);
panConfiguration.add(cbxPort);
// Button-Connection
JButton btnConnect = new JButton("Connect");
btnConnect.setFont(new Font("Tahoma", Font.PLAIN, 24));
btnConnect.setBounds(157, 7, 137, 49);
btnConnect.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
bike1 = new KettlerBikeConnector();
bike1.connect(cbxPort.getSelectedItem().toString(), new KettlerBikeListener() {
#Override
public void bikeAck() {
switch (listener.state) {
case hello:
listener.state = State.connected;
break;
case reset:
listener.state = State.hello;
break;
case connected:
log("connection successful");
break;
case notConnected:
log("not connected");
break;
}
}
#Override
public void bikeData(DataRecord data) {
//Sending the Ergometer velcoity every 1000ms to the
panBSim.setErgometerVelocity(data.getSpeed() / 10);
panBSim.setErgometerRPM(data.getPedalRpm());
panBSim.setTrueDataHere(true);
double power = panBSim.getTraveledDistance();
chd.setPower(power);
//getPower und dann set hier die Ergometer widerstand
try {
bike1.sendSetPower(panBSim.getErgometerPower());
} catch (IOException ignored) {
System.out.println("ignored");
}
}
#Override
public void bikeDestPowerChanged(int power) {
log("dest power: " + power);
}
#Override
public void bikeError() {
log("error1");
}
});
} catch (Exception e) {
log(e.getMessage());
}
}
});
panConfiguration.add(btnConnect);
// Button-Start
JButton btnStart = new JButton("Start");
btnStart.setFont(new Font("Tahoma", Font.PLAIN, 24));
btnStart.setBounds(304, 7, 137, 49);
btnStart.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
listener = new TimerListener(bike1);
timerBike = new Timer(UPDATE_MS, listener);
timerBike.start();
tabPane.setSelectedComponent(panSimulator); // switch to GamePanel
panBSim.startSimulate();
} catch (Exception e) {
log(e.getMessage());
}
}
});
panConfiguration.add(btnStart);
// Button-Scan
JButton btnScan = new JButton("Scan");
btnScan.setFont(new Font("Tahoma", Font.PLAIN, 24));
btnScan.setBounds(10, 7, 137, 49);
btnScan.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Enumeration<CommPortIdentifier> portList = CommPortIdentifier.getPortIdentifiers(); // list of named
while (portList.hasMoreElements()) {
CommPortIdentifier portId = (CommPortIdentifier) portList.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
cbxPort.addItem(portId.getName());
if (portId.isCurrentlyOwned()) {
log("Port " + portId.getName() + " is already open");
}
}
}
}
});
panConfiguration.add(btnScan);
// Status displays information regarding connection
lblStatus = new JTextPane();
lblStatus.setText(
"Anweisung:\r\n\t1) W\u00E4hle ein Lebensmittel aus der Food-Item Combobox aus\r\n\t2) Dr\u00FCcke den Scan-Button und w\u00E4hle den Port aus der Port Combobox aus\r\n\t3) Dr\u00FCcke den Connect-Button, um die Ger\u00E4te zu verbinden\r\n\t4) Dr\u00FCcke den Start-Button, um die Anwendung zu starten\r\n\t5) Warte auf das akustische Signal des Ergometer\r\n\t6) Beginne zu treten");
lblStatus.setFont(new Font("Tahoma", Font.PLAIN, 24));
lblStatus.setBounds(10, 125, 971, 229);
lblStatus.setDisabledTextColor(Color.BLACK);
lblStatus.setSelectionColor(new Color(51, 153, 255));
panConfiguration.add(lblStatus);
// FH Logo
JLabel lblLogo = new JLabel("");
lblLogo.setBounds(10, 365, 971, 430);
try {
File in = new File("FHLogo.png");
Image logo = ImageIO.read(in);
Image scaledLogo = logo.getScaledInstance(lblLogo.getWidth(), lblLogo.getHeight(), Image.SCALE_SMOOTH);
ImageIcon iconLogo = new ImageIcon(scaledLogo);
lblLogo.setIcon(iconLogo);
} catch (IOException e2) {
e2.printStackTrace();
}
panConfiguration.add(lblLogo);
// Labels
JLabel lblPort = new JLabel("Port:");
lblPort.setFont(new Font("Tahoma", Font.PLAIN, 24));
lblPort.setBounds(600, 5, 124, 49);
panConfiguration.add(lblPort);
//-----------------------------------------------------------------------------XXX
//Tab Bike Simulator
BorderLayout bdl = new BorderLayout();
panSimulator = new JPanel();
tabPane.addTab("Bike Simulator", null, panSimulator, null);
panSimulator.setLayout(bdl);
//Panel Bike Simulator
//panBSim = new PanelBikeSimulator();
//panBSim.setBorder(BorderFactory.createLineBorder(Color.black));
panSimulator.add(chd.getContentPane(), bdl.NORTH);
}
/**
* To log information
*
* #param str String that is shown
*/
private void log(String str) {
lblStatus.setText(lblStatus.getText() + str + "\n");
}
}
And this class belongs to my chart that I want to move to any location in my JPanel.
public class CrosshairDemo extends JFrame {
private static double POWER = 0.0;
public void setPower(double power) {
POWER = power;
}
public CrosshairDemo() {
super();
this.setContentPane(new CrosshairDemo.MyDemoPanel());
}
public static class MyDemoPanel extends JPanel implements Runnable {
/**
*
*/
private static final long serialVersionUID = 1L;
Thread t = new Thread((Runnable) this);
private TimeSeries series;
private final ChartPanel chartPanel;
private final JFreeChart chart = this.createChart();
public MyDemoPanel() {
super(new BorderLayout());
this.chartPanel = new ChartPanel(this.chart);
this.chartPanel.setPreferredSize(new Dimension(200, 550));
this.chartPanel.setLocation(getWidth() + 50, getHeight() + 30);
this.chartPanel.setDomainZoomable(true);
this.chartPanel.setRangeZoomable(true);
this.add(this.chartPanel);
t.start();
}
private JFreeChart createChart() {
XYDataset dataset1 = this.createDataset("Random 1", 100.0D, new Minute(), 200);
JFreeChart chart1 = ChartFactory.createTimeSeriesChart("Crosshair Demo 1", "Time of Day", "Value", dataset1);
XYPlot plot = (XYPlot)chart1.getPlot();
plot.setOrientation(PlotOrientation.VERTICAL);
plot.setDomainCrosshairVisible(true);
plot.setDomainCrosshairLockedOnData(false);
plot.setRangeCrosshairVisible(false);
return chart1;
}
private XYDataset createDataset(String name, double base, RegularTimePeriod start, int count) {
this.series = new TimeSeries(name);
RegularTimePeriod period = start;
double value = base;
for(int i = 0; i < count; ++i) {
this.series.add(period, value);
period = period.next();
value *= 1.0D + (Math.random() - 0.495D) / 10.0D;
}
TimeSeriesCollection dataset = new TimeSeriesCollection();
dataset.addSeries(this.series);
return dataset;
}
#Override
public void run() {
// TODO Auto-generated method stub
while(true) {
int value = (int) POWER; //this.slider.getValue();
XYPlot plot = (XYPlot)this.chart.getPlot();
ValueAxis domainAxis = plot.getDomainAxis();
Range range = domainAxis.getRange();
double c = domainAxis.getLowerBound() + (double)value / 100.0D * range.getLength();
plot.setDomainCrosshairValue(c);
}
}
}
Right now it's "attached" to the top (NORTH) of my JPanel:
Current chart position:
I would appreciate any help, because I have no more idea how to position this chart freely, therefore, I need your help guys.

How To Get Java Swing To Paint Properly?

I have a minimal app to show Java Swing GUI update problem, seems it's not painting the components properly, the errors look like this :
Here is my program :
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import java.util.concurrent.*;
public class Java_Test extends JPanel
{
static JFrame frame=new JFrame("Java Test");
static int W=800,H=260,Executor_Count=12;
JPanel Progress_Panel=new JPanel(),Center_Panel;
JButton Do_Test_Button=new JButton("Do Test");
Get_Time Timer=new Get_Time();
ThreadPoolExecutor executor;
Progress_Bar Progress_bar;
Timer Display_Timer=new Timer(1);
public Java_Test()
{
setLayout(new BorderLayout());
JPanel Top_Panel=new JPanel();
Top_Panel.setPreferredSize(new Dimension(W-6,60));
add("North",Top_Panel);
Do_Test_Button.setFont(new Font("Times New Roman",0,16));
Do_Test_Button.setBackground(new Color(118,198,250));
Do_Test_Button.setForeground(new Color(0,28,218));
Do_Test_Button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { Do_Test(); } });
Top_Panel.add(Do_Test_Button);
JPanel Center_Panel=new JPanel();
Center_Panel.setPreferredSize(new Dimension(W-2,170));
add("Center",Center_Panel);
Progress_Panel.setPreferredSize(new Dimension(W-2,160));
Center_Panel.add(Progress_Panel);
JLabel Progress_Label=new JLabel("Progress");
Progress_Label.setFont(new Font("Times New Roman",0,20));
Progress_Label.setBackground(new Color(253,253,253));
Progress_Label.setForeground(new Color(8,68,128));
Progress_Label.setPreferredSize(new Dimension(W-20,53));
Progress_Label.setHorizontalAlignment(SwingConstants.CENTER);
Progress_Panel.add(Progress_Label);
Progress_bar=new Progress_Bar(620,26);
Progress_Panel.add(Progress_bar);
JPanel Time_Used_Panel=new JPanel(new FlowLayout(FlowLayout.CENTER,6,26));
Time_Used_Panel.setPreferredSize(new Dimension(W-20,60));
Progress_Panel.add(Time_Used_Panel);
JLabel Time_Used_Label=new JLabel("Time : ");
Time_Used_Label.setFont(new Font("Times New Roman",0,14));
Time_Used_Label.setForeground(new Color(0,0,238));
Time_Used_Label.setHorizontalAlignment(SwingConstants.CENTER);
Time_Used_Panel.add(Time_Used_Label);
Display_Timer.setFont(new Font("Times New Roman",0,14));
Display_Timer.setForeground(new Color(0,0,238));
Display_Timer.setPreferredSize(new Dimension(50,17));
Time_Used_Panel.add(Display_Timer);
Clock clock=new Clock(0);
clock.setFont(new Font("Monospaced",Font.PLAIN,16));
clock.setBackground(new Color(0,110,220));
clock.setForeground(new Color(250,250,250));
clock.setOpaque(true);
clock.setPreferredSize(new Dimension(288,30));
clock.start();
JPanel Bottom_Panel=new JPanel();
Bottom_Panel.setPreferredSize(new Dimension(W-2,50));
Bottom_Panel.add(clock);
add("South",Bottom_Panel);
setPreferredSize(new Dimension(W,H));
}
void Do_Test()
{
String Info="",Result;
Out("Do_Test");
try
{
Display_Timer.start();
Timer.Start();
Output_Time("[ 1 ]");
Progress_bar.Set_Progress(1);
int Task_Count=222;
executor=new ThreadPoolExecutor(Executor_Count,Executor_Count*2,1,TimeUnit.SECONDS,new LinkedBlockingQueue());
ArrayList<Future<String>> futures=new ArrayList<>(Task_Count);
Test_Runner A_Runner;
try
{
for (int i=0;i<Task_Count;i++)
{
A_Runner=new Test_Runner();
futures.add(executor.submit(A_Runner));
}
executor.shutdown();
while (!executor.isTerminated()) { executor.awaitTermination(100,TimeUnit.MILLISECONDS); }
for (Future<String> future : futures)
{
Result=future.get();
if (Result!=null) Info+=Result;
}
}
catch (Exception e) { e.printStackTrace(); }
}
catch (Exception e) { e.printStackTrace(); }
Output_Time("[ 2 ]");
Progress_bar.Set_Progress(100);
Out("Done");
Display_Timer.stop();
}
String Output_Time(String Id)
{
Timer.End();
String Time_Duration=Id+" : Time = "+Timer.Get_Duration_Hour_Minute_Second();
Out(Time_Duration);
return Time_Duration;
}
private static void Out(String message) { System.out.println(message); }
static void Create_And_Show_GUI()
{
final Java_Test demo=new Java_Test();
frame.add(demo);
frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } });
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { Create_And_Show_GUI(); } }); }
}
class Progress_Bar extends JPanel implements Runnable
{
int W,H,Last_Progress=-99,Progress,counter=0,Unit_Size=20;
static JProgressBar b=new JProgressBar();
boolean Started_B=false,Do_Step_B=false;
Thread Progress_Bar_Runner_Thread;
public Progress_Bar(int W,int H)
{
setPreferredSize(new Dimension(W,H));
b.setPreferredSize(new Dimension(W-20,H-8));
b.setStringPainted(true);
add(b);
start();
}
public void Set_Progress(int Progress)
{
if (Progress==1 || (this.Progress<Progress && Progress<=100))
{
this.Progress=Progress;
b.setValue(Progress);
b.paintImmediately(0,0,b.getWidth(),b.getHeight());
Out(" Progress = "+Progress+" %");
}
if (Progress==1) Started_B=true;
else if (Progress>=100)
{
Started_B=false;
Do_Step_B=false;
}
}
public void run()
{
try
{
while (Progress<=100)
{
if ((Progress==0 || Progress==50 || Progress==100 || Do_Step_B) && Last_Progress!=Progress)
{
b.setValue(Progress);
// revalidate();
b.paintImmediately(0,0,b.getWidth(),b.getHeight());
Last_Progress=Progress;
}
Thread.sleep(200); // Delay the thread
Do_Step_B=(Started_B && (counter++ % Unit_Size ==0));
if (Progress<100 && Do_Step_B) Progress++;
}
}
catch (Exception e) { e.printStackTrace(); }
}
public void start()
{
if (Progress_Bar_Runner_Thread==null)
{
Progress_Bar_Runner_Thread=new Thread(this);
Progress_Bar_Runner_Thread.setPriority(Thread.NORM_PRIORITY);
Progress_Bar_Runner_Thread.start();
}
}
public void stop() { if (Progress_Bar_Runner_Thread!=null) Progress_Bar_Runner_Thread=null; }
private static void Out(String message) { System.out.println(message); }
}
class Test_Runner implements Callable<String>
{
int Start_Index=0,End_Index=6999;
StringBuilder StrBdr=new StringBuilder();
public Test_Runner() { }
public String call() throws InterruptedException
{
try { for (int i=Start_Index;i<End_Index;i++) StrBdr.append("Test_Runner + Test_Runner + Test_Runner + Test_Runner + Test_Runner + Test_Runner"); }
catch (Exception e) {}
return StrBdr.toString();
}
}
class Timer extends JLabel implements Runnable
{
public static final long serialVersionUID=26362862L;
private Thread Timer_Thread;
String Time_Text="";
int updateInterval=1000,Format=0;
Get_Time Timer=new Get_Time();
public Timer()
{
setFont(new Font("Monospaced",Font.PLAIN,16));
setVerticalAlignment(SwingConstants.CENTER);
setHorizontalAlignment(SwingConstants.CENTER);
}
public Timer(int Format) { this.Format=Format; }
public void start()
{
Timer.Start();
if (Timer_Thread==null)
{
Timer_Thread=new Thread(this);
Timer_Thread.setPriority(Thread.NORM_PRIORITY);
Timer_Thread.start();
}
}
public void run()
{
Thread myThread=Thread.currentThread();
while (Timer_Thread==myThread)
{
switch (Format)
{
case 1 : Time_Text=Timer.Get_Duration_Hour_Minute_Second();break;
}
setText(Time_Text);
paintImmediately(0,0,getWidth(),getHeight());
revalidate();
try { Thread.sleep(updateInterval); }
catch (InterruptedException e) { }
}
}
public void stop() { if (Timer_Thread != null) Timer_Thread=null; }
}
class Clock extends JLabel implements Runnable
{
public static final long serialVersionUID=26362862L;
private Thread clockThread;
String Time_Text="";
int updateInterval=1000,Format=0;
Get_Time Timer=new Get_Time();
public Clock() { start(); }
public Clock(int Format)
{
this.Format=Format;
start();
}
public void start()
{
setVerticalAlignment(SwingConstants.CENTER);
setHorizontalAlignment(SwingConstants.CENTER);
if (clockThread==null)
{
clockThread=new Thread(this);
// clockThread.setPriority(Thread.NORM_PRIORITY);
clockThread.setPriority(Thread.MIN_PRIORITY);
clockThread.start();
}
}
public void run()
{
Thread myThread=Thread.currentThread();
while (clockThread==myThread)
{
switch (Format)
{
case 0 : Time_Text=" "+new java.util.Date().toString().substring(0,19)+" ";break;
}
setText(Time_Text);
paintImmediately(0,0,getWidth(),getHeight());
revalidate();
try { Thread.sleep(updateInterval); }
catch (InterruptedException e) { }
}
}
public void stop() { if (clockThread != null) clockThread=null; }
}
class Get_Time
{
private long start,end;
public int Hours,Minutes,Seconds,Total_Seconds;
String ST_Hours,ST_Minutes,ST_Seconds;
public Get_Time() { Reset(); }
public void Start() { start=System.currentTimeMillis(); }
public void End()
{
int half_second;
end=System.currentTimeMillis();
Total_Seconds=(int)(end-start)/1000;
half_second=(int)(end-start)%1000;
if (half_second>499) Total_Seconds++;
Hours=Total_Seconds/3600;
Minutes=(Total_Seconds%3600)/60;
Seconds=(Total_Seconds%3600)%60;
ST_Hours=new String((Hours>9)?""+Hours:"0"+Hours);
ST_Minutes=new String((Minutes>9)?""+Minutes:"0"+Minutes);
ST_Seconds=new String((Seconds>9)?""+Seconds:"0"+Seconds);
}
public String Get_Duration_Hour_Minute_Second()
{
End();
return ST_Hours+":"+ST_Minutes+":"+ST_Seconds;
}
public void Reset() { start=0;end=0; }
}
My computer has a 12 core 3.33 GH Intel Corei7 x 980 CPU, with 24 GB of RAM, running on Windows 7, Java Version = 1.8.0_212
The question is how to fix it ?
Enumeration of Swing threading and painting problems:
All of the following code is called from the Swing event dispatch thread (EDT), and so far so good....
void Do_Test() {
String Info = "", Result;
Out("Do_Test");
try {
Display_Timer.start();
Timer.Start();
Output_Time("[ 1 ]");
Progress_bar.Set_Progress(1); // OK to call this on the event thread
int Task_Count = 222;
executor = new ThreadPoolExecutor(Executor_Count, Executor_Count * 2, 1,
TimeUnit.SECONDS, new LinkedBlockingQueue());
ArrayList<Future<String>> futures = new ArrayList<>(Task_Count);
Test_Runner A_Runner;
try {
for (int i = 0; i < Task_Count; i++) {
A_Runner = new Test_Runner();
futures.add(executor.submit(A_Runner));
}
executor.shutdown();
OK, here we start seeing problems as you're calling a potentially long while loop on the EDT, potentially blocking it:
while (!executor.isTerminated()) {
executor.awaitTermination(100, TimeUnit.MILLISECONDS);
}
Same here, as the call to Future#get() is a blocking call:
for (Future<String> future : futures) {
Result = future.get();
if (Result != null)
Info += Result;
}
OK, now we start seeing some truly unusual Swing code where you make Swing calls, including setting a JProgressBar's value off the EDT and then try to force the EDT to do some painting via paintImmediately(....). Making calls off the EDT can result in intermittent and unpredictable errors, and can cause the painting to mess up, and the GUI to sometimes freeze:
class Progress_Bar extends JPanel implements Runnable {
// .....
public void Set_Progress(int Progress) {
if (Progress == 1 || (this.Progress < Progress && Progress <= 100)) {
this.Progress = Progress; // ****** being called off the EDT
b.paintImmediately(0, 0, b.getWidth(), b.getHeight()); // ***** Don't do this
Out(" Progress = " + Progress + " %");
}
// .....
}
public void run() {
try {
while (Progress <= 100) {
if ((Progress == 0 || Progress == 50 || Progress == 100 || Do_Step_B)
&& Last_Progress != Progress) {
// ***** called off the EDT -- don't do this
b.setValue(Progress);
// revalidate();
b.paintImmediately(0, 0, b.getWidth(), b.getHeight()); // **** and don't do this
Last_Progress = Progress;
}
Thread.sleep(200); // Delay the thread
Do_Step_B = (Started_B && (counter++ % Unit_Size == 0));
if (Progress < 100 && Do_Step_B)
Progress++;
}
} catch (Exception e) {
e.printStackTrace();
}
}
// .......
}
Similar strange goings-ons in this class, the Timer class, where you set a JLabel's text off of the EDT:
class Timer extends JLabel implements Runnable {
// ....
public void run() {
Thread myThread = Thread.currentThread();
while (Timer_Thread == myThread) {
switch (Format) {
case 1:
Time_Text = Timer.Get_Duration_Hour_Minute_Second();
break;
}
// again this is dangerous code **********
setText(Time_Text);
paintImmediately(0, 0, getWidth(), getHeight());
// ....
Same for the Clock class...
Solutions:
To repeatedly call code in a Swing GUI, use a javax.swing.Timer or "Swing Timer". For an example of use of this, please see my implementation of your MCVE, but using a Swing Timer for your threading code above.
The other code, the one that calls long-running tasks, should be done within a SwingWorker. This worker thread usually communicates with the Swing GUI in one of two ways (or both) -- either using a publish/process method pair, or (as in the example below), using a PropertyChangeListener attached to the Worker. Workers have several "bound" properties, fields that notify listeners of change, including the progress property, that can hold a value from 0 to 100, and the SwingWorker.StateValue, or "state" property:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import javax.swing.*;
#SuppressWarnings("serial")
public class JavaTest2 extends JPanel {
private static final int W = 800;
private static final int H = 260;
private Action doTestAction = new DoTestAction("Do Test");
private JProgressBar progressBar = new JProgressBar(0, 100);
private MyClockPanel clockPanel = new MyClockPanel();
private MyTimerPanel timerPanel = new MyTimerPanel();
public JavaTest2() {
JPanel topPanel = new JPanel();
topPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 35, 5));
topPanel.add(new JButton(doTestAction));
progressBar.setStringPainted(true);
JPanel progressPanel = new JPanel(new GridBagLayout());
progressPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 1.0;
progressPanel.add(progressBar, gbc);
JLabel progressLabel = new JLabel("Progress", SwingConstants.CENTER);
progressLabel.setFont(new Font("Times New Roman", 0, 20));
progressLabel.setForeground(new Color(8, 68, 128));
JPanel centralPanel = new JPanel(new BorderLayout(5, 5));
centralPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
centralPanel.add(progressLabel, BorderLayout.PAGE_START);
centralPanel.add(progressPanel);
JPanel clockWrapper = new JPanel();
clockWrapper.add(clockPanel);
JPanel bottomPanel = new JPanel();
bottomPanel.setLayout(new BoxLayout(bottomPanel, BoxLayout.PAGE_AXIS));
bottomPanel.add(timerPanel, BorderLayout.PAGE_START);
bottomPanel.add(clockWrapper, BorderLayout.PAGE_END);
setLayout(new BorderLayout());
setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
add(topPanel, BorderLayout.PAGE_START);
add(bottomPanel, BorderLayout.PAGE_END);
add(centralPanel);
}
#Override
public Dimension getPreferredSize() {
Dimension superSize = super.getPreferredSize();
if (isPreferredSizeSet()) {
return superSize;
} else {
int w = Math.max(superSize.width, W);
int h = Math.max(superSize.height, H);
return new Dimension(w, h);
}
}
private class DoTestAction extends AbstractAction {
private MyWorker myWorker = null;
public DoTestAction(String name) {
super(name);
int mnemonic = (int) name.charAt(0);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
if (myWorker != null && myWorker.getState() == SwingWorker.StateValue.STARTED) {
return; // still running
}
timerPanel.start();
progressBar.setValue(0);
myWorker = new MyWorker();
myWorker.addPropertyChangeListener(new WorkerListener());
myWorker.execute();
setEnabled(false);
}
}
class WorkerListener implements PropertyChangeListener {
#Override
public void propertyChange(PropertyChangeEvent evt) {
// if the worker is changing its progress bound property:
if (evt.getPropertyName().equals("progress")) {
int progress = (int) evt.getNewValue();
// just for safety's sake, limit progress to 100 and no more
progress = Math.min(progress, 100);
progressBar.setValue(progress);
} else if (evt.getNewValue() == SwingWorker.StateValue.DONE) {
// else if worker is done
try {
// get the result to at least trap errors
String result = ((MyWorker) evt.getSource()).get();
// can display result in the GUI
timerPanel.stop();
} catch (Exception e) {
// worker's exception is available to the GUI if desired here
e.printStackTrace();
}
progressBar.setValue(100);
doTestAction.setEnabled(true);
}
}
}
private static class MyWorker extends SwingWorker<String, Void> {
private static final int EXECUTOR_COUNT = 12;
private static final int TASK_COUNT = 222;
#Override
protected String doInBackground() throws Exception {
ExecutorService executor = new ThreadPoolExecutor(EXECUTOR_COUNT, EXECUTOR_COUNT * 2, 1,
TimeUnit.SECONDS, new LinkedBlockingQueue<>());
List<Future<String>> futures = new ArrayList<>();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < TASK_COUNT; i++) {
Callable<String> aRunner = new ARunner();
futures.add(executor.submit(aRunner));
}
executor.shutdown();
int index = 0;
for (Future<String> future : futures) {
String result = future.get();
sb.append(result);
sb.append(" ");
index++;
int progress = (100 * index) / TASK_COUNT;
progress = Math.min(progress, 100);
setProgress(progress);
}
return sb.toString();
}
}
private static class ARunner implements Callable<String> {
private static final long SLEEP_TIME = 800;
#Override
public String call() throws Exception {
TimeUnit.MILLISECONDS.sleep(SLEEP_TIME);
return "Foo";
}
}
private static void createAndShowGui() {
JavaTest2 mainPanel = new JavaTest2();
JFrame frame = new JFrame("Java Test 2");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
#SuppressWarnings("serial")
class MyClockPanel extends JPanel {
private static final Color FG = new Color(250, 250, 250);
private static final Color BG = new Color(0, 110, 220);
private static final int TIMER_DELAY = 200;
private static final Font FONT = new Font("Monospaced", Font.PLAIN, 16);
private JLabel clockLabel = new JLabel("", SwingConstants.CENTER);
private DateTimeFormatter formatter = DateTimeFormatter.ofPattern("E MMM dd yyyy kk:mm:ss");
public MyClockPanel() {
setBackground(BG);
clockLabel.setForeground(FG);
clockLabel.setFont(FONT);
displayDateTime();
setLayout(new BorderLayout());
setBorder(BorderFactory.createEmptyBorder(5, 50, 5, 50));
add(clockLabel);
new javax.swing.Timer(TIMER_DELAY, e -> {
displayDateTime();
}).start();
}
private void displayDateTime() {
LocalDateTime dateTime = LocalDateTime.now();
String text = dateTime.format(formatter);
clockLabel.setText(text);
}
}
#SuppressWarnings("serial")
class MyTimerPanel extends JPanel {
private static final Color FG = new Color(0, 0, 238);
private static final Font FONT = new Font("Times New Roman", 0, 14);
private static final int TIMER_DELAY = 40;
private static final String FORMAT_TXT = "Elapsed Time: %02d:%02d:%02d";
private JLabel timerLabel = new JLabel("", SwingConstants.CENTER);
private LocalDateTime startTime = null;
private Timer timer = null;
public MyTimerPanel() {
timerLabel.setForeground(FG);
timerLabel.setFont(FONT);
setLayout(new BorderLayout());
setBorder(BorderFactory.createEmptyBorder(5, 50, 5, 50));
timerLabel.setText(String.format(FORMAT_TXT, 0, 0, 0));
add(timerLabel);
}
public void start() {
stop();
startTime = LocalDateTime.now();
timer = new Timer(TIMER_DELAY, e -> incrementTime());
timer.start();
}
public void stop() {
if (timer != null && timer.isRunning()) {
timer.stop();
}
}
private void incrementTime() {
LocalDateTime currentTime = LocalDateTime.now();
long hours = ChronoUnit.HOURS.between(startTime, currentTime);
long minutes = ChronoUnit.MINUTES.between(startTime, currentTime) % 60;
long seconds = ChronoUnit.SECONDS.between(startTime, currentTime) % 60;
String text = String.format(FORMAT_TXT, hours, minutes, seconds);
timerLabel.setText(text);
}
}

Java Socket need to get name of sender

I'm starting with Socket Server in Java. I've written already simple app where I can send text between hosts. I'm sending with my message name of the host which is sending and here is my problem, how can I get host message?
Can someone just change my code to show host name instead of message?
Here is the code:
public class FMain extends JFrame {
private JPanel contentPane = null;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
FMain frame = new FMain();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public FMain() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 508, 321);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
PReceiver receiver = new PReceiver();
receiver.setBorder(new LineBorder(new Color(0, 0, 0)));
receiver.setBounds(35, 13, 423, 106);
contentPane.add(receiver);
PSender sender = new PSender((String) null, 0);
sender.setBorder(new LineBorder(new Color(0, 0, 0)));
sender.setBounds(35, 132, 423, 129);
contentPane.add(sender);
}
}
And the class which is receiving:
interface MyListener {
void messageReceived(String theLine);
}
class Receiver {
private List < MyListener > ml = new ArrayList < MyListener > ();
private Thread t = null;
private int port = 0;
private ServerSocket s = null;
private boolean end = false;
public void stop() {
t.interrupt();
try {
s.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void start() {
end = false;
t = new Thread(new Runnable() {
#Override
public void run() {
try {
s = new ServerSocket(port);
while (true) {
Socket sc = s.accept();
InputStream is = sc.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String theLine = br.readLine();
ml.forEach((item) - > item.messageReceived(theLine));
sc.close();
}
} catch (SocketException e) {} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
t.start();
}
public void addMyListener(MyListener m) {
ml.add(m);
}
public void removeMyListener(MyListener m) {
ml.remove(m);
}
Receiver(int port) {
this.port = port;
}
}
public class PReceiver extends JPanel implements MyListener {
private JTextField txtPort;
private Receiver r = null;
private JTextField txtMessage;
/**
* Create the panel.
*/
public PReceiver() {
setLayout(null);
txtPort = new JTextField();
txtPort.setBounds(282, 13, 62, 22);
add(txtPort);
// txtPort.setColumns(10);
JLabel lblPort = new JLabel("port:");
lblPort.setBounds(241, 16, 35, 16);
add(lblPort);
JToggleButton btnListen = new JToggleButton("Listen");
btnListen.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
if (btnListen.isSelected()) {
r = new Receiver(Integer.parseInt(txtPort.getText()));
r.addMyListener(PReceiver.this);
r.start();
} else {
r.stop();
}
}
});
btnListen.setBounds(265, 70, 79, 25);
add(btnListen);
JLabel lblMessage = new JLabel("message");
lblMessage.setBounds(12, 51, 56, 16);
add(lblMessage);
txtMessage = new JTextField();
txtMessage.setBounds(12, 71, 220, 22);
add(txtMessage);
//txtMessage.setColumns(10);
}
#Override
public void messageReceived(String theLine) {
txtMessage.setText(theLine);
}
}
And the sender class:
class Sender {
public void send(String message, String host, int port) {
Socket s;
try {
s = new Socket(host, port);
OutputStream out = s.getOutputStream();
PrintWriter pw = new PrintWriter(out, false);
pw.println(message);
pw.flush();
pw.close();
s.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public class PSender extends JPanel {
private JTextField txtMessage;
private JTextField txtHost;
private JTextField txtPort;
private JLabel lblMessage;
/**
* Create the panel.
*/
public PSender(String host, int port) {
setLayout(null);
txtMessage = new JTextField();
txtMessage.setBounds(12, 77, 216, 22);
add(txtMessage);
//txtMessage.setColumns(10);
JButton btnSend = new JButton("Send");
btnSend.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
new Sender().send(txtMessage.getText(), txtHost.getText(), Integer.parseInt(txtPort.getText()));
} catch (NumberFormatException e) {
e.printStackTrace();
}
}
});
btnSend.setBounds(268, 76, 78, 25);
add(btnSend);
txtHost = new JTextField();
txtHost.setBounds(51, 13, 149, 22);
add(txtHost);
//txtHost.setColumns(10);
txtPort = new JTextField();
txtPort.setBounds(268, 13, 78, 22);
add(txtPort);
//txtPort.setColumns(10);
JLabel lblHost = new JLabel("host:");
lblHost.setBounds(12, 16, 35, 16);
add(lblHost);
JLabel lblPort = new JLabel("port:");
lblPort.setBounds(231, 16, 35, 16);
add(lblPort);
lblMessage = new JLabel("message");
lblMessage.setBounds(12, 58, 56, 16);
add(lblMessage);
}
}

Application works perfect in eclipse but not as a jar, jpanel is not showing

I have a very strange problem, my application works perfect! Code looks ok, no visual error at all. Tested it a lot and no problems..... but when i exported it as a jar, it does not behave like in eclipse, the jpanel for logging in does not show, like it does in eclipse.
I just want to say this twice, the code is IDENTICAL! no changes at all! It works correctly when i run it in Eclipse IDE but when i export it as a Jar file and run it, it runs "incorrectly".
Here is a overview in code and pictures of the structure of my application and how it should behave and how it behaves when it is incorrect.
All relevant code in the GUI package is below.
Please if you comment, give me some concrete examples/advises/leads.
QUESTION : Why does the application "work" improperly and doesn't show the login panel that is created in the class: LoginPanelGui when i run it from jar.
Thanks in advance!!
//Dino
Here is some relevant code:
`public class StartApplication {
public static void main(String[] args) throws Exception{
MainFrameGui main = new MainFrameGui();
main.openMainFrameWindow();
}
}`
`public class MainFrameGui {
private JFrame mainFrame = null;
private LoginPanelGui loginPanelClass = null;
private CreateUserPanelGui createNewUserClass = null;
private MainPanelGui mainPanelClass =null;
private DeleteUserPanelGui deleteUserClass =null;
private DialogGui dialog=null;
private JMenuBarGui menu_bar = null;
public MainFrameGui(){
createMainWindow();
initlizeMenuBar();
}
public void openMainFrameWindow(){
showLoginPanel();
mainFrame.setVisible(true);
}
private void createMainWindow(){
this.mainFrame= new JFrame();
mainFrame.setIconImage(new ImageIcon("locked.png").getImage());
mainFrame.setTitle("PasswordSafe 1.0");
mainFrame.setVisible(false);
mainFrame.setSize(new Dimension(505, 355));
mainFrame.setLayout(null);
mainFrame.setLocationRelativeTo(null);
mainFrame.setResizable(false);
mainFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
mainFrame.setLocation(200, 10);
this.dialog = new DialogGui(this.mainFrame);
addLoginPanelToMainFrame();
addDeleteUSerToMainFrame();
addCreateNewUserToMainFrame();
addMainPanelToMainFrame();
}
private void initlizeMenuBar(){
this.menu_bar = new JMenuBarGui(this, dialog, createNewUserClass, deleteUserClass, loginPanelClass);
this.mainFrame.setJMenuBar(menu_bar.getJMenuBar());
}
private void addLoginPanelToMainFrame(){
loginPanelClass = new LoginPanelGui(this, dialog);
mainFrame.add(loginPanelClass.getJPanel()).setBounds(10, 10, 480, 305);
}
private void addCreateNewUserToMainFrame(){
createNewUserClass = new CreateUserPanelGui(this,dialog);
mainFrame.add(createNewUserClass.getJPanel()).setBounds(10, 10, 480, 365);
}
private void addMainPanelToMainFrame(){
this.mainPanelClass = new MainPanelGui(dialog);
mainFrame.add(mainPanelClass.getJPanel()).setBounds(10, 10, 1030, 620);
}
private void addDeleteUSerToMainFrame(){
this.deleteUserClass = new DeleteUserPanelGui(dialog);
mainFrame.add(deleteUserClass.getJPanel()).setBounds(10, 10, 480, 305);
}
public void showLoginPanel(){
deleteUserClass.hideDeleteUserPanel();
createNewUserClass.hideCreateNewUserPanel();
mainPanelClass.hideMainPanel();
loginPanelClass.showLoginPanel();
mainFrame.setSize(new Dimension(505, 375));
}
public void showCreateNewUserPanel(){
loginPanelClass.hideLoginPanel();
deleteUserClass.hideDeleteUserPanel();
mainPanelClass.hideMainPanel();
createNewUserClass.showCreateNewUserPanel();
mainFrame.setSize(new Dimension(505, 435));
}
public void showDeleteUserPanel(){
loginPanelClass.hideLoginPanel();
createNewUserClass.hideCreateNewUserPanel();
mainPanelClass.hideMainPanel();
deleteUserClass.showDeleteUserPanel();
mainFrame.setSize(new Dimension(505, 375));
}
public void showMainPanel(LUANObject luan){
loginPanelClass.hideLoginPanel();
deleteUserClass.hideDeleteUserPanel();
createNewUserClass.hideCreateNewUserPanel();
mainPanelClass.showMainPanel(luan);
mainFrame.setSize(new Dimension(1055, 690));
}
public String getLoginPanelSelectedAlgorithmMode(){
return loginPanelClass.getSelectedAlgorithmMode();
}
public String getCreateNewUserSelectedAlgorithmMode(){
return createNewUserClass.getSelectedAlgorithmMode();
}
public boolean isLoggedIn(){
return mainPanelClass.isLoggedIn();
}
public void setLockedIcon(){
mainFrame.setIconImage(new ImageIcon("locked.png").getImage());
}
public void setUnlockedIcon(){
mainFrame.setIconImage(new ImageIcon("unlocked.png").getImage());
}
public void setUserLabel_menuBar(String userLabel){
menu_bar.setUserLabel(userLabel);
}
public void removeUserLabel_menuBar(){
menu_bar.removeUserLabel();
}
}
`
`
import SecureFileManager.FileManager;
public class LoginPanelGui {
private JPanel loginPanel = null;
private FileManager fm = null;
private DialogGui dialog = null;
private MainFrameGui mainFrame=null;
private JComboBox <String> comboBoxSelectAlgorithm = null;
private JComboBox <String> comboBoxSelectuser = null;
private JPasswordField passwordFieldEncryptionKey = null;
private JPanel panelEncryptionKeyInfo=null;
private JPasswordField passwordFieldIvKey=null;
private JPanel panelFieldIvKeyInfo=null;
private JPasswordField passwordField =null;
private JPanel panelFieldPasswordInfo=null;
private JLabel labelPassword =null;
private JLabel labelEncryptionKey =null;
private JLabel labelIvKey=null;
private JButton buttonLogin=null;
private boolean createNewUser=false;
public LoginPanelGui(MainFrameGui mainFrame, DialogGui dialog){
this.mainFrame = mainFrame;
this.fm = new FileManager();
this.dialog = dialog;
createLoginJPanel();
}
private void createLoginJPanel(){
initlilizeLoginPanel();
addComboBoxAlghoritmToPanel();
addLabelIvKeyToFrame();
addLabelEncryptionKeyToFrame();
addPanelEncryptionKeyInfoToFrame();
addInitialVectorFieldToPanel();
addLabelPasswordToFrame();
addPasswordFiledAndPanelToFrame();
addComboBoxSelectUserToPanel();
addLoginButtonToFrame();
isIvKeyCorrect();
isKeyCorrect();
isPasswordCorrect();
}
private void initlilizeLoginPanel(){
loginPanel = new JPanel();
loginPanel.setLayout(null);
loginPanel.setBorder(BorderFactory.createEtchedBorder());
loginPanel.setVisible(true);
}
private void addComboBoxAlghoritmToPanel(){
String algorithms[]={"Select Algorithm","AES/CBC/PKCS5Padding","AES/CTR/PKCS5Padding","AES/ECB/PKCS5Padding","AES/GCM/PKCS5Padding","DES/CTR/PKCS5Padding"};
comboBoxSelectAlgorithm = new JComboBox<String>(algorithms);
Font font = new Font("Consolas", Font.BOLD, 20);
comboBoxSelectAlgorithm.setFont(font);
loginPanel.add(comboBoxSelectAlgorithm).setBounds(10, 10, 455, 40);
comboBoxSelectAlgorithm.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
isIvKeyCorrect();
isKeyCorrect();
if(getSelectedAlgorithmMode().equals("Select Algorithm") || getSelectedUser().equals("Select User")){
buttonLogin.setEnabled(false);
}
if(!getSelectedAlgorithmMode().equals("Select Algorithm") && !getSelectedUser().equals("Select User")){
buttonLogin.setEnabled(true);
}
if(getSelectedAlgorithmMode().contains("DES")){
panelEncryptionKeyInfo.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(),"Enter Key (8 Characters)", 0, 0, new Font("Arial", Font.BOLD, 13)));
panelFieldIvKeyInfo.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(),"Enter Iv-Key (8 Characters)", 0, 0, new Font("Arial", Font.BOLD, 13)));
}
if(!getSelectedAlgorithmMode().contains("DES")){
panelEncryptionKeyInfo.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(),"Enter Key (16 Characters)", 0, 0, new Font("Arial", Font.BOLD, 13)));
panelFieldIvKeyInfo.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(),"Enter Iv-Key (16 Characters)", 0, 0, new Font("Arial", Font.BOLD, 13)));
}
}
});
}
private void addLabelEncryptionKeyToFrame(){
this.labelEncryptionKey = new JLabel();
Font font = new Font("Ariel", Font.BOLD, 25);
labelEncryptionKey.setFont(font);
labelEncryptionKey.setHorizontalAlignment(JLabel.CENTER);
labelEncryptionKey.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(),"Key Status", 0, 0, new Font("Arial", Font.BOLD, 13)));
loginPanel.add(labelEncryptionKey).setBounds(10, 55, 225, 50);
}
private void addLabelIvKeyToFrame(){
this.labelIvKey = new JLabel();
Font font = new Font("Ariel", Font.BOLD, 21);
labelIvKey.setFont(font);
labelIvKey.setHorizontalAlignment(JLabel.CENTER);
labelIvKey.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(),"Iv-Key Status", 0, 0, new Font("Arial", Font.BOLD, 13)));
loginPanel.add(labelIvKey).setBounds(245, 55, 225, 50);
}
private void addPanelEncryptionKeyInfoToFrame(){
this.passwordFieldEncryptionKey= new JPasswordField();
this.panelEncryptionKeyInfo = new JPanel();
panelEncryptionKeyInfo.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(),"Enter Key (16 Characters)", 0, 0, new Font("Arial", Font.BOLD, 13)));
panelEncryptionKeyInfo.setVisible(true);
panelEncryptionKeyInfo.setLayout(null);
Font font = new Font("Arial", Font.BOLD, 35);
passwordFieldEncryptionKey.setFont(font);
passwordFieldEncryptionKey.setText("");
panelEncryptionKeyInfo.add(passwordFieldEncryptionKey).setBounds(10, 20, 205, 30);
loginPanel.add(panelEncryptionKeyInfo).setBounds(10, 105, 225, 60);
passwordFieldEncryptionKey.addKeyListener(new KeyListener() {
#Override
public void keyTyped(KeyEvent arg0) {
isKeyCorrect();
}
#Override
public void keyReleased(KeyEvent arg0) {
isKeyCorrect();
}
#Override
public void keyPressed(KeyEvent arg0) {
isKeyCorrect();
}
});
}
private void addInitialVectorFieldToPanel(){
this.passwordFieldIvKey = new JPasswordField();
this.panelFieldIvKeyInfo = new JPanel();
panelFieldIvKeyInfo.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(),"Enter Iv-Key (16 Characters)", 0, 0, new Font("Arial", Font.BOLD, 13)));
panelFieldIvKeyInfo.setVisible(true);
panelFieldIvKeyInfo.setLayout(null);
Font font = new Font("Arial", Font.BOLD, 35);
passwordFieldIvKey.setFont(font);
passwordFieldIvKey.setText("");
panelFieldIvKeyInfo.add(passwordFieldIvKey).setBounds(10, 20, 205, 30);
loginPanel.add(panelFieldIvKeyInfo).setBounds(245, 105, 225, 60);
passwordFieldIvKey.addKeyListener(new KeyListener() {
#Override
public void keyTyped(KeyEvent arg0) {
isIvKeyCorrect();
}
#Override
public void keyReleased(KeyEvent arg0) {
isIvKeyCorrect();
}
#Override
public void keyPressed(KeyEvent arg0) {
isIvKeyCorrect();
}
});
}
private void addLabelPasswordToFrame(){
this.labelPassword = new JLabel();
Font font = new Font("Ariel", Font.BOLD, 17);
labelPassword.setFont(font);
labelPassword.setHorizontalAlignment(JLabel.CENTER);
labelPassword.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(),"Password Status", 0, 0, new Font("Arial", Font.BOLD, 13)));
loginPanel.add(labelPassword).setBounds(10, 170, 225, 60);
// isIvKeyStatusInactivated();
}
private void addPasswordFiledAndPanelToFrame(){
this.passwordField= new JPasswordField();
this.panelFieldPasswordInfo = new JPanel();
panelFieldPasswordInfo.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(),"Enter Password (18-20 Characters)", 0, 0, new Font("Arial", Font.BOLD, 11)));
panelFieldPasswordInfo.setVisible(true);
panelFieldPasswordInfo.setLayout(null);
Font font = new Font("Arial", Font.BOLD, 28);
passwordField.setFont(font);
passwordField.setText("");
panelFieldPasswordInfo.add(passwordField).setBounds(10, 20, 205, 30);
loginPanel.add(panelFieldPasswordInfo).setBounds(10, 235, 225, 60);
passwordField.addKeyListener(new KeyListener() {
#Override
public void keyTyped(KeyEvent arg0) {
isPasswordCorrect();
}
#Override
public void keyReleased(KeyEvent arg0) {
isPasswordCorrect();
}
#Override
public void keyPressed(KeyEvent arg0) {
isPasswordCorrect();
}
});
}
private void addLoginButtonToFrame(){
this.buttonLogin = new JButton();
buttonLogin.setText("LOGIN");
buttonLogin.setFont(new Font("Consolas", Font.BOLD, 35));
buttonLogin.setEnabled(false);
loginPanel.add(buttonLogin).setBounds(245, 242, 225, 50);
buttonLogin.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
if(isIvKeyCorrect() && isKeyCorrect() && isPasswordCorrect() && fm.isfileExcisting(comboBoxSelectuser.getSelectedItem().toString())){
LUANObject luan = new LUANObject();
try{
luan.put("username", comboBoxSelectuser.getSelectedItem().toString());
luan.put("algorithm", comboBoxSelectAlgorithm.getSelectedItem().toString());
luan.put("password", new String(passwordField.getPassword()));
luan.put("ivKey", new String(passwordFieldIvKey.getPassword()));
luan.put("key", new String(passwordFieldEncryptionKey.getPassword()));
luan=fm.readEncryptedPassword(luan);
if(luan!= null && luan.containsString("password") && new String(passwordField.getPassword()).equals(luan.getString("password"))){
if(luan.containsString("password")){
luan.removeString("password");
}
if(luan.containsString("ivKey")){
luan.removeString("ivKey");
}
if(luan.containsString("key")){
luan.removeString("key");
}
luan.put("key", luan.getString("passwordTable_Key"));
luan.put("ivKey", luan.getString("passwordTable_Iv-Key"));
if(luan.containsString("passwordTable_Key")){
luan.removeString("passwordTable_Key");
}
if(luan.containsString("passwordTable_Iv-Key")){
luan.removeString("passwordTable_Iv-Key");
}
luan=fm.readEncryptedPasswordTable(luan);
mainFrame.showMainPanel(luan);
mainFrame.setUserLabel_menuBar(luan.getString("username"));
}else{
dialog.dynamicErrorDialogWindow("Authentication Faild", "Wrong Iv-key and/or decryption-Key and/or password!");
}
}catch(Exception ex){
dialog.dynamicErrorDialogWindow("Authentication Faild", "Wrong Iv-key and/or decryption-Key and/or password!");
}
}
}
});
}
private void addComboBoxSelectUserToPanel(){
String algorithms[]=fm.getUsers();
comboBoxSelectuser = new JComboBox<String>(algorithms);
Font font = new Font("Consolas", Font.BOLD, 20);
comboBoxSelectuser.setFont(font);
loginPanel.add(comboBoxSelectuser).setBounds(245, 178, 225, 50);
comboBoxSelectuser.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if(getSelectedAlgorithmMode().equals("Select Algorithm") || getSelectedUser().equals("Select User")){
buttonLogin.setEnabled(false);
}
else if(!getSelectedAlgorithmMode().equals("Select Algorithm") && !getSelectedUser().equals("Select User")){
buttonLogin.setEnabled(true);
}
}
});
}
private boolean isIvKeyCorrect(){
if(getSelectedAlgorithmMode().contains("AES/ECB")){
labelIvKey.setForeground(new Color(0,150,0));
labelIvKey.setText("NOT NEEDED");
passwordFieldIvKey.setEnabled(false);
passwordFieldIvKey.setBorder(BorderFactory.createLineBorder(new Color(0,150,0)));
return true;
}else if(!getSelectedAlgorithmMode().contains("DES") && passwordFieldIvKey.getPassword().length==16){
labelIvKey.setForeground(new Color(0,150,0));
labelIvKey.setText("IV-KEY CORRECT");
passwordFieldIvKey.setBorder(BorderFactory.createLineBorder(new Color(0,150,0)));
passwordFieldIvKey.setEnabled(true);
return true;
}else if(getSelectedAlgorithmMode().contains("DES") && passwordFieldIvKey.getPassword().length==8){
labelIvKey.setForeground(new Color(0,150,0));
labelIvKey.setText("IV-KEY CORRECT");
passwordFieldIvKey.setEnabled(true);
passwordFieldIvKey.setBorder(BorderFactory.createLineBorder(new Color(0,150,0)));//createEtchedBorder(new Color(0,150,0), new Color(0,150,0)));
return true;
}else{
labelIvKey.setForeground(Color.RED);
labelIvKey.setText("IV-KEY INCORRECT");
passwordFieldIvKey.setEnabled(true);
passwordFieldIvKey.setBorder(BorderFactory.createLineBorder(Color.RED));
return false;
}
}
private boolean isKeyCorrect(){
if(getSelectedAlgorithmMode().contains("DES") && passwordFieldEncryptionKey.getPassword().length==8 ){
labelEncryptionKey.setForeground(new Color(0,150,0));
passwordFieldEncryptionKey.setBorder(BorderFactory.createLineBorder(new Color(0,150,0)));
labelEncryptionKey.setText("KEY CORRECT");
return true;
}
else if(!getSelectedAlgorithmMode().contains("DES") && passwordFieldEncryptionKey.getPassword().length==16){
labelEncryptionKey.setForeground(new Color(0,150,0));
labelEncryptionKey.setText("KEY CORRECT");
passwordFieldEncryptionKey.setBorder(BorderFactory.createLineBorder(new Color(0,150,0)));
return true;
}else{
labelEncryptionKey.setForeground(Color.RED);
labelEncryptionKey.setText("KEY INCORRECT");
passwordFieldEncryptionKey.setBorder(BorderFactory.createLineBorder(Color.RED));
return false;
}
}
private boolean isPasswordCorrect(){
if(passwordField.getPassword().length>9 && passwordField.getPassword().length<21 ){
labelPassword.setForeground(new Color(0,150,0));
labelPassword.setText("PASSWORD CORRECT");
passwordField.setBorder(BorderFactory.createLineBorder(new Color(0,150,0)));
return true;
}else{
labelPassword.setForeground(Color.RED);
labelPassword.setText("PASSWORD INCORRECT");
passwordField.setBorder(BorderFactory.createLineBorder(Color.RED));
return false;
}
}
public String getSelectedAlgorithmMode(){
return this.comboBoxSelectAlgorithm.getSelectedItem().toString();
}
public String getSelectedUser(){
return this.comboBoxSelectuser.getSelectedItem().toString();
}
public boolean isCurrentModeLogin(){
return createNewUser;
}
public void showLoginPanel(){
updateComboboxUser();
loginPanel.setVisible(true);
}
private void updateComboboxUser(){
comboBoxSelectuser.removeAllItems();
String algorithms[]=fm.getUsers();
for(int i=0;i<algorithms.length;i++){
comboBoxSelectuser.addItem(algorithms[i]);
}
}
public void hideLoginPanel(){
loginPanel.setVisible(false);
mainFrame.removeUserLabel_menuBar();
passwordField.setText("");
passwordFieldEncryptionKey.setText("");
passwordFieldIvKey.setText("");
comboBoxSelectuser.setSelectedIndex(0);
comboBoxSelectAlgorithm.setSelectedIndex(0);
isIvKeyCorrect();
isIvKeyCorrect();
isPasswordCorrect();
}
public JPanel getJPanel(){
return this.loginPanel;
}
}
`
`
public class JMenuBarGui {
private DialogGui dialog=null;
private MainFrameGui mainFrameGui = null;
private JMenuBar menu_bar = null;
private JMenu accountManager_menu=null;;
private JMenuItem login_menuItem=null;
private JMenuItem logout_menuItem=null;
private JMenuItem createUser_menuItem=null;
private JMenuItem deleteUser_menuItem=null;
private CreateUserPanelGui createPanel=null;
private DeleteUserPanelGui deletePanel=null;
private LoginPanelGui loginPanel=null;
private JMenu help_menu;
private JMenuItem instructions_menuItem;
private JMenuItem about_menuItem;
private JLabel userLabel= null;
public JMenuBarGui(MainFrameGui mainFrameGui,DialogGui dialog, CreateUserPanelGui cp, DeleteUserPanelGui dp, LoginPanelGui lp){
this.loginPanel=lp;
this.createPanel=cp;
this.deletePanel=dp;
this.mainFrameGui = mainFrameGui;
this.dialog=dialog;
initilizeAccoutmanager_menu();
initilizeHelp_menu();
initilizeUserLabelToMenuBar();
initilizeMenuBar();
startLogin_menuItemEventListener();
startCreateUser_menuItemEventListener();
startDeleteUser_menuItemEventListener();
startLogout_menuItemEventListener();
startInstructions_menuItemEventListener();
startAbout_menuItemEventListener();
isLoggedInChangeListener();
}
private void initilizeMenuBar(){
this.menu_bar = new JMenuBar();
this.menu_bar.add(accountManager_menu);
this.menu_bar.add(help_menu);
this.menu_bar.add(Box.createGlue());
this.menu_bar.add(userLabel);
}
private void initilizeAccoutmanager_menu(){
this.accountManager_menu = new JMenu("Account Manager");
this.accountManager_menu.setVisible(true);
this.accountManager_menu.setLayout(new FlowLayout());
this.login_menuItem = new JMenuItem("Login");
this.createUser_menuItem = new JMenuItem("Create New User");
this.deleteUser_menuItem = new JMenuItem("Delete An User");
this.logout_menuItem = new JMenuItem("Logout");
this.accountManager_menu.add(login_menuItem);
this.accountManager_menu.add(createUser_menuItem);
this.accountManager_menu.add(deleteUser_menuItem);
this.accountManager_menu.add(logout_menuItem);
}
private void initilizeHelp_menu(){
this.help_menu = new JMenu("Help");
this.help_menu.setVisible(true);
this.help_menu.setLayout(new FlowLayout());
this.instructions_menuItem = new JMenuItem("Instructions");
this.about_menuItem = new JMenuItem("About PasswordSafe");
this.help_menu.add(instructions_menuItem);
this.help_menu.add(about_menuItem);
}
private void initilizeUserLabelToMenuBar(){
this.userLabel = new JLabel();
this.userLabel.setVisible(false);
}
public JMenuBar getJMenuBar(){
return this.menu_bar;
}
private void startLogin_menuItemEventListener(){
class login_menuItem implements ActionListener{
public void actionPerformed(ActionEvent e){
mainFrameGui.showLoginPanel();
}
}
login_menuItem.addActionListener(new login_menuItem());
}
private void startCreateUser_menuItemEventListener(){
class createUser_menuItem implements ActionListener{
public void actionPerformed(ActionEvent e){
mainFrameGui.showCreateNewUserPanel();
}
}
createUser_menuItem.addActionListener(new createUser_menuItem());
}
private void startDeleteUser_menuItemEventListener(){
class deleteUser_menuItem implements ActionListener{
public void actionPerformed(ActionEvent e){
mainFrameGui.showDeleteUserPanel();
}
}
deleteUser_menuItem.addActionListener(new deleteUser_menuItem());
}
private void startLogout_menuItemEventListener(){
class logout_menuItem implements ActionListener{
public void actionPerformed(ActionEvent e){
boolean logout=dialog.dynamicConfirmationDialog("Log out", "Are you sure that you want to logout?");
if(logout==true){
mainFrameGui.showLoginPanel();
}
}
}
logout_menuItem.addActionListener(new logout_menuItem());
}
private void startInstructions_menuItemEventListener(){
class instructions_menuItem implements ActionListener{
public void actionPerformed(ActionEvent e){
System.out.println("MISSION SUCCESS");
}
}
instructions_menuItem.addActionListener(new instructions_menuItem());
}
private void startAbout_menuItemEventListener(){
class about_menuItem implements ActionListener{
public void actionPerformed(ActionEvent e){
System.out.println("MISSION SUCCESS");
}
}
about_menuItem.addActionListener(new about_menuItem());
}
private void isLoggedInChangeListener(){
//could not fit(can maximum enter 30000 characters )
}
public void setUserLabel(String userLabel){
this.userLabel.setText("Logged in as: "+userLabel+" ");
this.userLabel.setVisible(true);
}
public void removeUserLabel(){
this.userLabel.setText("");
this.userLabel.setBorder(BorderFactory.createEtchedBorder());
this.userLabel.setVisible(false);
}
}
`
`
public class MainPanelGui {
private FileManager fm=null;
private JPanel mainPanel=null;
private DialogGui dialog = null;
private boolean loggedIn=false;
private JTableStructure ts=null;
public MainPanelGui(DialogGui dialog){
this.fm = new FileManager();
this.dialog = dialog;
initilizeMainPanel();
initilizePasswordTable();
}
private void initilizeMainPanel(){
mainPanel = new JPanel();
mainPanel.setLayout(null);
mainPanel.setBorder(BorderFactory.createEtchedBorder());
mainPanel.setVisible(false);
}
private void initilizePasswordTable(){
this.ts = new JTableStructure(dialog, fm);
this.mainPanel.add(ts.getPasswordTableScroll()).setBounds(10, 10, 1010, 600);
}
public JPanel getJPanel(){
return this.mainPanel;
}
public void showMainPanel(LUANObject luan){
ts.updateEntireTableFromFile(luan);
mainPanel.setVisible(true);
loggedIn=true;
}
public void hideMainPanel(){
mainPanel.setVisible(false);
ts.setLuanObectToNull();
this.loggedIn=false;
}
public boolean isLoggedIn(){
return this.loggedIn;
}
}`

How do I update JLabel from antoher class?

I need to use a thread to change the position of my JLabel (movingDisplay) every second when I click on my button (btnDisplay) and for the thread to stop when I click on my other button (btnDStop). I have a class called MoveDisplay that implements Runnable and does this action when I click on btnDisplay. After MoveDisplay has randomized x and y for my JLabel, it's supposed to send x and y back to my main class where it updates the position of the JLabel. I have a method in my mainclass to update the JLabel position however I get a NullPointerException when trying to do so. In fact it doesn't work changing any component at all from MoveDisplay class.
public class Main {
public static void main(String[] args) {
GUIFrame test = new GUIFrame();
}
}
MoveDisplay class:
public class MoveDisplay implements Runnable {
private GUIFrame gui;
private boolean moving = true;
private Thread thread;
public void run() {
gui = new GUIFrame();
if (moving) {
Random rand = new Random();
while (moving) {
int x = rand.nextInt(150) + 1;
int y = rand.nextInt(150) + 1;
gui.moveDisplay(x, y, 100, 100);
try {
thread.sleep(1000);
} catch (InterruptedException e) {
break;
}
}
}
}
public void start() {
thread = new Thread(new MoveDisplay());
thread.start();
}
public void stop() {
thread.interrupt();
System.out.println("Stopped");
}
}
GUIFrame class:
public class GUIFrame {
private JFrame frame; // The Main window
private JLabel movingDisplay;
private boolean playing = true;
private boolean moving = true;
private MoveDisplay moveDisplay = new MoveDisplay();
/**
* Starts the application
*/
public void Start() {
frame = new JFrame();
frame.setBounds(0, 0, 494, 437);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(null);
frame.setTitle("Multiple Thread Demonstrator");
InitializeGUI(); // Fill in components
frame.setVisible(true);
frame.setResizable(false); // Prevent user from change size
frame.setLocationRelativeTo(null); // Start middle screen
}
public void InitializeGUI() {
// The moving display outer panel
JPanel pnlDisplay = new JPanel();
Border b2 = BorderFactory.createTitledBorder("Display Thread");
pnlDisplay.setBorder(b2);
pnlDisplay.setBounds(12, 118, 222, 269);
pnlDisplay.setLayout(null);
// Add buttons and drawing panel to this panel
btnDisplay = new JButton("Start Display");
btnDisplay.setBounds(10, 226, 121, 23);
pnlDisplay.add(btnDisplay);
btnDStop = new JButton("Stop");
btnDStop.setBounds(135, 226, 75, 23);
pnlDisplay.add(btnDStop);
pnlMove = new JPanel();
pnlMove.setBounds(10, 19, 200, 200);
Border b21 = BorderFactory.createLineBorder(Color.black);
pnlMove.setBorder(b21);
pnlDisplay.add(pnlMove);
// Then add this to main window
frame.add(pnlDisplay);
movingDisplay = new JLabel("DisplayThread");
pnlMove.add(movingDisplay);
btnDStop.setEnabled(false);
btnDisplay.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
moving = true;
btnDisplay.setEnabled(false);
btnDStop.setEnabled(true);
startMoveDisplay();
}
});
btnDStop.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
moving = false;
btnDisplay.setEnabled(true);
btnDStop.setEnabled(false);
startMoveDisplay();
}
});
}
public void startMoveDisplay() {
if(moving) {
moveDisplay.start();
}
else {
moveDisplay.stop();
}
}
public void moveDisplay(int x, int y, int a, int b) {
movingDisplay.setBounds(10,10,150,150);
}
}
I've checked the code and in the MoveDisplay.run() you were creating a new frame, but in it's constructor the panel wasn't initialized, which triggered the NPE. Because of this I've refactored the GUIFrame constructor to initialeze all components (invoked the Start() method) and removed the new frame's initialization from the run method. Here are the modified classed
public class MoveDisplay {
private GUIFrame gui;
private volatile boolean moving;
public MoveDisplay(GUIFrame gui) {
this.gui = gui;
}
public void start() {
moving = true;
Random rand = new Random();
while (moving) {
int x = rand.nextInt(150) + 1;
int y = rand.nextInt(150) + 1;
gui.moveDisplay(x, y, 100, 100);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void stop() {
moving = false;
}
}
And here is the new frame class
public class GUIFrame {
private JFrame frame; // The Main window
private JLabel movingDisplay;
private boolean playing = true;
private boolean moving = true;
private MoveDisplay moveDisplay;
public GUIFrame() {
Start();
}
/**
* Starts the application
*/
private void Start() {
frame = new JFrame();
frame.setBounds(0, 0, 494, 437);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(null);
frame.setTitle("Multiple Thread Demonstrator");
InitializeGUI(); // Fill in components
frame.setVisible(true);
frame.setResizable(false); // Prevent user from change size
frame.setLocationRelativeTo(null); // Start middle screen
moveDisplay = new MoveDisplay(this);
}
public void InitializeGUI() {
// The moving display outer panel
JPanel pnlDisplay = new JPanel();
Border b2 = BorderFactory.createTitledBorder("Display Thread");
pnlDisplay.setBorder(b2);
pnlDisplay.setBounds(12, 118, 222, 269);
pnlDisplay.setLayout(null);
// Add buttons and drawing panel to this panel
JButton btnDisplay = new JButton("Start Display");
btnDisplay.setBounds(10, 226, 121, 23);
pnlDisplay.add(btnDisplay);
JButton btnDStop = new JButton("Stop");
btnDStop.setBounds(135, 226, 75, 23);
pnlDisplay.add(btnDStop);
JPanel pnlMove = new JPanel();
pnlMove.setBounds(10, 19, 200, 200);
Border b21 = BorderFactory.createLineBorder(Color.black);
pnlMove.setBorder(b21);
pnlDisplay.add(pnlMove);
// Then add this to main window
frame.add(pnlDisplay);
movingDisplay = new JLabel("DisplayThread");
pnlMove.add(movingDisplay);
btnDStop.setEnabled(false);
btnDisplay.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
moving = true;
btnDisplay.setEnabled(false);
btnDStop.setEnabled(true);
startMoveDisplay();
}
});
btnDStop.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
moving = false;
btnDisplay.setEnabled(true);
btnDStop.setEnabled(false);
startMoveDisplay();
}
});
}
public void startMoveDisplay() {
if(moving) {
new Thread(new Runnable() {
#Override
public void run() {
moveDisplay.start();
}
}).start();
} else {
moveDisplay.stop();
}
}
public void moveDisplay(int x, int y, int a, int b) {
movingDisplay.setBounds(x, y, a, b);
}
}
You have to get a reference to the existing GUIFrame instance instead of creating a new one, try this:
MoveDisplay
public class MoveDisplay implements Runnable {
private GUIFrame gui;
Random rand = new Random();
volatile boolean moving;
public MoveDispaly(GUIFrame gui){
this.gui = gui;
}
public void run() {
while (moving) {
int x = rand.nextInt(150) + 1;
int y = rand.nextInt(150) + 1;
try {
SwingUtilities.invokeAndWait(new Runnable(){
public void run(){
gui.moveDisplay(x, y, 100, 100);
}
});
thread.sleep(1000);
} catch (InterruptedException e) {
break;
}
}
}
public void start() {
moving = true;
thread = new Thread(new MoveDisplay());
thread.start();
}
public void stop() {
moving = false;
}
}
GUIFrame
public class GUIFrame{
MoveDisplay moveDisplay = new MoveDisplay(this);
...
}
Also, you have to run the part of the code that changes the GUI on the EDT thread.
Is not a good idea to stop a thread by interrupting it, you can stop it by setting the moving variable to false.
Maybe you can also use the Singleton Pattern to get the original instance of GUIFrame:
public static class instanceClassA {
private static instanceClassA = null;
public static instanceClassA(){
if(instance == null){
instance = instanceClassA();
}
return instance;
}
}

Categories