I am developing Swing Application . I create new Tab for new Log Process..Print all console statement inside it . when i place tab in tab component it get mismatched pro1 hold log2 pro2 hold log1 so i dig to much but not figure out code is follow.
ProjectExecute Event Which call to CreateNew TAb Method .
if (e.getSource() == btnExecute) {
createTab();
String s = new StringBuffer().append(ProjectOutPath).toString();
dirr = new File(s);
if (!dirr.exists()) {
}
final File tagFile = new File(dirr, projectName + ".log");
if (!tagFile.exists()) {
try {
tagFile.createNewFile();
} catch (IOException e1) {
e1.printStackTrace();
}
}
SwingWorker<Boolean, Integer> worker = new SwingWorker<Boolean, Integer>() {
#SuppressWarnings({ "unchecked", "null" })
#Override
protected Boolean doInBackground() throws Exception {
PrintStream printStream = new PrintStream(new CustomOutputStream(logTextArea, tempArea));
System.setOut(printStream);
System.setErr(printStream);
File outFile = new File(tagFile.getAbsolutePath());
FileOutputStream outFileStream = new FileOutputStream(outFile);
PrintWriter outStream = new PrintWriter(outFileStream);
try {
System.out.println("ChooserFile 1 :" + chooserFile1);
MainApp.runApp(chooserFile1);
chooserFile1 = new StringBuilder().append(chooserFile1).append("/raw_data").toString();
outStream.write(logTextArea.getText());
System.out.flush();
Runtime.getRuntime().exec("clear");
outStream.close();
printStream.close();
} catch (IOException e1) {
e1.printStackTrace();
}
Thread.sleep(1000);
return true;
}
protected void done() {
try {
Component c[] = panel_tree.getComponents();
panel_tree.remove(c.length - 1);
panel_tree.add(ExomDataGUI.getTreeUpdate());
panel_tree.revalidate();
panel_tree.repaint();
scrollPane.getViewport().setView(ExomDataGUI.panel_tree);
} catch (Exception e) {
System.out.println("Exception Occured....!");
}
}
#Override
protected void process(List<Integer> chunks) {
int mostRecentValue = chunks.get(chunks.size() - 1);
countLabel.setText(Integer.toString(mostRecentValue));
}
};
worker.execute();
} else {
}
}
Create TAB method
private static JScrollPane createScroll() {
System.out.println("Creatre Scrollpane Method Called....");
JTextArea ja = new JTextArea();
String S = logTextArea.getText();
ja.setText(S);
JScrollPane JScrolling = new JScrollPane(ja);
logTextArea.setText(null);
return JScrolling;
}
public static void createTab() {
JLabel lblTitle;
if (flag == 1) {
//System.out.println("************Inside If Flag ***********");
tabbedPane1.add("", new JScrollPane(logTextArea));
Demo.add(tabbedPane1);
JTextArea JTA = new JTextArea();
String log = logTextArea.getText();
JTA.setText(log);
logTextArea.setText(null);
lblTitle= new JLabel(projectName);
flag = 0;
} else {
// System.out.println("+++++++++++++++++++Inside If Flag +++++++++++");
JScrollPane JSP = createScroll();
tabbedPane1.add("here", JSP);
lblTitle= new JLabel(projectName);
}
JPanel pnlTab = new JPanel();
pnlTab.setOpaque(false);
//JLabel lblTitle = new JLabel();
JButton btnClose = new JButton();
btnClose.setOpaque(false);
btnClose.setRolloverIcon(CLOSE_TAB_ICON);
btnClose.setRolloverEnabled(true);
btnClose.setIcon(CLOSE_TAB_ICON);
btnClose.setBorder(null);
btnClose.setFocusable(false);
pnlTab.setForeground(Color.white);
pnlTab.setBackground(Color.white);
pnlTab.add(lblTitle);
pnlTab.add(btnClose);
pnlTab.setForeground(Color.white);
tabbedPane1.setTabComponentAt(tabbedPane1.getTabCount() - 1, pnlTab);
Demo.add(tabbedPane1);
ActionListener listener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
int response = JOptionPane.showConfirmDialog(null, "Do You Want To Close Tab ?");
if (response == 0)
tabbedPane1.remove(tabbedPane1.getSelectedComponent());
tabIndex--;
}
};
btnClose.addActionListener(listener);
}
Related
I am writing a GUI for a minesweeper and I am saving the difficulty in a text file. However instead of writing to file the difficulty properly, it always empties the file and my null check condition is triggered.
I have tried using debugging and manually editing the text file to contain the string "HARD", but after changing the difficulty (setting it again to hard, or switching to easy), the file becomes empty.
public class MineSweeperMain extends Application {
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) throws Exception {
String difficulty;
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("LastProgramState.txt"));
difficulty = br.readLine();
if (difficulty == null) {
System.out.println("???");
throw new FileNotFoundException(); // If I comment this out, file becomes empty
}
} catch (FileNotFoundException e) {
BufferedWriter bw = new BufferedWriter(new FileWriter("LastProgramState.txt"));
bw.write("EASY");
bw.close();
difficulty = "EASY";
} finally {
if (br != null)
br.close();
}
int xSize;
int ySize;
int bombCount;
System.out.println(difficulty);
if (difficulty == null) {
System.exit(200);
}
if (difficulty.equals("HARD")) {
xSize = 16;
ySize = 16;
bombCount = 40;
}
else {
xSize = 9;
ySize = 9;
bombCount = 10;
}
Menu menu1 = new Menu("Options");
Menu menu2 = new Menu("Help");
MenuItem mi1 = new MenuItem("Difficulty: Easy");
MenuItem mi2 = new MenuItem("Difficulty: Hard");
MenuItem mi3 = new MenuItem("How to play");
MenuItem mi4 = new MenuItem("About...");
menu1.getItems().add(mi1);
menu1.getItems().add(mi2);
menu2.getItems().add(mi3);
menu2.getItems().add(mi4);
MenuBar bar = new MenuBar();
bar.getMenus().addAll(menu1,menu2);
Label score = new Label("Score:");
Scene scene = new Scene(bp);
primaryStage.setScene(scene);
primaryStage.setTitle("MineSweeper");
primaryStage.show();
}
mi1.setOnAction(event -> { //EASY
try {
BufferedWriter bwriter = new BufferedWriter(new FileWriter("LastProgramState.txt"));
bwriter.write("EASY");
} catch (IOException e) {
System.exit(100);
}
primaryStage.close();
Platform.runLater( () -> { //RUN APPLICATION AGAIN
try {
new MineSweeperMain().start( new Stage() );
} catch (Exception ex) {
System.exit(100);
}
} );
});
mi2.setOnAction(event -> { //HARD
try {
BufferedWriter bwriter = new BufferedWriter(new FileWriter("LastProgramState.txt"));
bwriter.write("HARD");
} catch (IOException e) {
System.exit(100);
}
primaryStage.close();
Platform.runLater( () -> {
try {
new MineSweeperMain().start( new Stage() );
} catch (Exception ex) {
System.exit(100);
}
} );
});
}
If I choose hard difficulty, I expect the txt file to contain the string "HARD", but instead it contains the string "EASY". The same behaviour occurs when I choose easy difficulty. Also I noticed that if I remove the throw new FileNotFoundException(), the file becomes completely empty. What am I doing wrong? Any help is appreciated.
EDIT: Issue solved, I forgot to close the file after writing to in in mi1.setOnAction() and mi2.setOnAction().
How I can manage multiple GoPro cameras at the same time? I want to stream three videos of three GoPro cameras at the same time and record the videos on the hard disk.
I have written a tool in Java for one GoPro and it works correctly.
Help me please!
This is the code:
public class GoProStreamer extends JFrame {
private static final String CAMERA_IP = "10.5.5.9";
private static int PORT = 8080;
private static DatagramSocket mOutgoingUdpSocket;
private Process streamingProcess;
private Process writeVideoProcess;
private KeepAliveThread mKeepAliveThread;
private JPanel contentPane;
public GoProStreamer() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(800, 10, 525, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JButton btnStop = new JButton("Stop stream");
JButton btnStart = new JButton("Start stream");
JButton btnRec = new JButton("Rec");
JButton btnStopRec = new JButton("Stop Rec");
// JButton btnZoomIn = new JButton("Zoom In sincrono");
// JButton btnZoomOut = new JButton("Zoom out sincrono");
// JButton btnZoomIn1 = new JButton("Zoom In Camera 1");
// JButton btnZoomOut1 = new JButton("Zoom out Camera 1");
// JButton btnZoomIn2 = new JButton("Zoom in Camera 2");
// JButton btnZoomOut2 = new JButton("Zoom out Camera 2");
// JButton btnZoomIn3 = new JButton("Zoom in camera 3");
// JButton btnZoomOut3 = new JButton("Zoom out Camera 3");
btnStop.setEnabled(false);
btnRec.setEnabled(false);
btnStopRec.setEnabled(false);
// btnZoomIn.setEnabled(false);
// btnZoomOut.setEnabled(false);
// btnZoomIn1.setEnabled(false);
// btnZoomOut1.setEnabled(false);
// btnZoomIn2.setEnabled(false);
// btnZoomOut2.setEnabled(false);
// btnZoomIn3.setEnabled(false);
// btnZoomOut3.setEnabled(false);
JPanel panel = new JPanel();
// JPanel panel2 = new JPanel();
// JPanel panel3 = new JPanel();
// JPanel panel4 = new JPanel();
panel.add(btnStart);
panel.add(btnStop);
panel.add(btnRec);
panel.add(btnStopRec);
// panel2.add(btnZoomIn1);
// panel3.add(btnZoomOut1);
// panel2.add(btnZoomIn2);
// panel3.add(btnZoomOut2);
// panel2.add(btnZoomIn3);
// panel3.add(btnZoomOut3);
// panel4.add(btnZoomIn);
// panel4.add(btnZoomOut);
contentPane.add(panel, BorderLayout.SOUTH);
// contentPane.add(panel2, BorderLayout.NORTH);
// contentPane.add(panel3, BorderLayout.CENTER);
btnStart.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
startStreamService();
keepAlive();
startStreaming();
btnStart.setEnabled(false);
btnStop.setEnabled(true);
btnRec.setEnabled(true);
btnStopRec.setEnabled(false);
// btnZoomIn.setEnabled(true);
// btnZoomOut.setEnabled(true);
// btnZoomIn1.setEnabled(true);
// btnZoomOut1.setEnabled(true);
// btnZoomIn2.setEnabled(true);
// btnZoomOut2.setEnabled(true);
// btnZoomIn3.setEnabled(true);
// btnZoomOut3.setEnabled(true);
}
});
btnStop.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
stopStreaming();
stopKeepalive();
btnStart.setEnabled(true);
btnStop.setEnabled(false);
btnRec.setEnabled(false);
btnStopRec.setEnabled(false);
}
});
btnRec.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
startRec();
btnStart.setEnabled(false);
btnStop.setEnabled(false);
btnRec.setEnabled(false);
btnStopRec.setEnabled(true);
}
});
btnStopRec.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
stopRec();
btnStart.setEnabled(false);
btnStop.setEnabled(true);
btnRec.setEnabled(true);
btnStopRec.setEnabled(false);
}
});
}
private void startStreamService() {
HttpURLConnection localConnection = null;
try {
String str = "http://" + CAMERA_IP + "/gp/gpExec?p1=gpStreamA9&c1=restart";
localConnection = (HttpURLConnection) new URL(str).openConnection();
localConnection.addRequestProperty("Cache-Control", "no-cache");
localConnection.setConnectTimeout(5000);
localConnection.setReadTimeout(5000);
int i = localConnection.getResponseCode();
if (i >= 400) {
throw new IOException("sendGET HTTP error " + i);
}
}
catch (Exception e) {
}
if (localConnection != null) {
localConnection.disconnect();
}
}
#SuppressWarnings("static-access")
private void sendUdpCommand(int paramInt) throws SocketException, IOException {
Locale localLocale = Locale.US;
Object[] arrayOfObject = new Object[4];
arrayOfObject[0] = Integer.valueOf(0);
arrayOfObject[1] = Integer.valueOf(0);
arrayOfObject[2] = Integer.valueOf(paramInt);
arrayOfObject[3] = Double.valueOf(0.0D);
byte[] arrayOfByte = String.format(localLocale, "_GPHD_:%d:%d:%d:%1f\n", arrayOfObject).getBytes();
String str = CAMERA_IP;
int i = PORT;
DatagramPacket localDatagramPacket = new DatagramPacket(arrayOfByte, arrayOfByte.length, new InetSocketAddress(str, i));
this.mOutgoingUdpSocket.send(localDatagramPacket);
}
private void startStreaming() {
Thread threadStream = new Thread() {
#Override
public void run() {
try {
streamingProcess = Runtime.getRuntime().exec("ffmpeg-20150318-git-0f16dfd-win64-static\\bin\\ffplay -i http://10.5.5.9:8080/live/amba.m3u8");
InputStream errorStream = streamingProcess.getErrorStream();
byte[] data = new byte[1024];
int length = 0;
while ((length = errorStream.read(data, 0, data.length)) > 0) {
System.out.println(new String(data, 0, length));
System.out.println(System.currentTimeMillis());
}
} catch (IOException e) {
}
}
};
threadStream.start();
}
private void startRec() {
Thread threadRec = new Thread() {
#Override
public void run() {
try {
writeVideoProcess = Runtime.getRuntime().exec("ffmpeg-20150318-git-0f16dfd-win64-static\\bin\\ffmpeg -re -i http://10.5.5.9:8080/live/amba.m3u8 -c copy -an Video_GoPro_" + Math.random() + ".avi");
InputStream errorRec = writeVideoProcess.getErrorStream();
byte[] dataRec = new byte[1024];
int lengthRec = 0;
while ((lengthRec = errorRec.read(dataRec, 0, dataRec.length)) > 0) {
System.out.println(new String(dataRec, 0, lengthRec));
System.out.println(System.currentTimeMillis());
}
} catch (IOException e) {
}
}
};
threadRec.start();
}
private void keepAlive() {
mKeepAliveThread = new KeepAliveThread();
mKeepAliveThread.start();
}
class KeepAliveThread extends Thread {
public void run() {
try {
Thread.currentThread().setName("gopro");
if (mOutgoingUdpSocket == null) {
mOutgoingUdpSocket = new DatagramSocket();
}
while ((!Thread.currentThread().isInterrupted()) && (mOutgoingUdpSocket != null)) {
sendUdpCommand(2);
Thread.sleep(2500L);
}
}
catch (SocketException e) {
}
catch (InterruptedException e) {
}
catch (Exception e) {
}
}
}
private void stopStreaming() {
if (streamingProcess != null) {
streamingProcess.destroy();
streamingProcess = null;
}
stopKeepalive();
mOutgoingUdpSocket.disconnect();
mOutgoingUdpSocket.close();
}
private void stopRec() {
writeVideoProcess.destroy();
writeVideoProcess = null;
}
private void stopKeepalive() {
if (mKeepAliveThread != null) {
mKeepAliveThread.interrupt();
try {
mKeepAliveThread.join(10L);
mKeepAliveThread = null;
}
catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
public static void main(String[] args) {
GoProStreamer streamer = new GoProStreamer();
streamer.setVisible(true);
streamer.setTitle("Pannello di controllo");
}
}
IMHO, it is a physical problem : a standard wifi card can't connect to multiple wifi networks.
if you're running Windows, here is a Microsoft utilty ( http://research.microsoft.com/en-us/downloads/994abd5f-53d1-4dba-a9d8-8ba1dcccead7/ ) that seems to allow it.
Microsoft Research Virtual WiFi
Virtual WiFi helps a user connect to multiple IEEE 802.11 networks with one WiFi card. VIt works by exposing multiple virtual adapters, one for each wireless network to which connectivity is desired. Virtual WiFi uses a network hopping scheme to switch the wireless card across the desired wireless networks.
As soon as you can connect all cameras at one time, try to do one thread by camera as suggested by jjurm in comments. Keep in mind that you are limited by your bandwith according to the resolution of the stream wanted (Full HD 24fps uncompressed = 1920 * 1080 * 24 ~ 50 Mbs <=> 802.11g Wifi theoric speed ).
Hope it helps
I have this app that runs in eclipse's console and I want it to run in a jframe.
By that I mean that I want it to ask for name, a and b on the JFrame window and then write something on a file.
It works perfectly in the console but I don't know how to run it as a JFrame.
I want it to look something like this(Image made in photoshop):
http://i.imgur.com/rTWko1R.png
And then automaticaly close
Thanks in advance!
some imports...(trying to save space)
public class Test {
public static void main(String[] args) throws FileNotFoundException,IOException {
Scanner s = new Scanner(System.in);
String fileName = new SimpleDateFormat("dd-MM-yyyy_HH-mm'.txt'").format(new Date());
String obs;
String name;
String path = "some path";
int a = 0, b = 0, c = 0, d = 0;
System.out.println("input file name");
name = s.nextLine();
System.out.println("input a");
a = s.nextInt();
System.out.println("input b");
b = s.nextInt();
obs = s.nextLine();
if (a >= 100) {
d = a / 100;
c = a % 100;
b = c;
a = a + d;
}
File file;
if (StringUtils.isBlank(name)) {
file = new File(path + fileName);
} else {
file = new File(path + name + "#" + fileName);
}
FileWriter writer = null;
try {
writer = new FileWriter(file);
writer.write("something");
if (StringUtils.isBlank(obs)) {
writer.write("something");
} else {
writer.write(obs + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (writer != null)
try {
writer.close();
} catch (IOException ignore) {
}
}
}
}
What you'll need to do
separate out your core logic into a separate method that takes String name, int a, int b, ideally in a separate class - then you can reuse from your console version
Create a basic GUI in a frame with a button to kick off the process
listen to the button press and call core logic method
add validation of inputs if necessary
consider using JFileChooser to allow user to pick the file rather than having to type it in
Example
public class ConsoleInFrame {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new ConsoleInFrame().showGui();
}
});
}
public void showGui() {
JFrame frame = new JFrame();
JTextField file = new JTextField(20);
JTextField aText = new JTextField(4);
JTextField bText = new JTextField(4);
JButton go = new JButton("Go");
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(3, 2));
panel.add(new JLabel("File"));
panel.add(file);
panel.add(new JLabel("a"));
panel.add(aText);
panel.add(new JLabel("b"));
panel.add(bText);
frame.getContentPane().setLayout(
new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS));
frame.getContentPane().add(panel);
frame.getContentPane().add(go);
go.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
process(file.getText(), Integer.parseInt(aText.getText()),
Integer.parseInt(bText.getText()));
}
});
frame.pack();
frame.setVisible(true);
}
public void process(String name, int a, int b) {
String fileName = new SimpleDateFormat("dd-MM-yyyy_HH-mm'.txt'")
.format(new Date());
String obs;
String path = "some path";
int c = 0, d = 0;
if (a >= 100) {
d = a / 100;
c = a % 100;
b = c;
a = a + d;
}
File file;
if (StringUtils.isBlank(name)) {
file = new File(path + fileName);
} else {
file = new File(path + name + "#" + fileName);
}
FileWriter writer = null;
try {
writer = new FileWriter(file);
writer.write("something");
if (StringUtils.isBlank(obs)) {
writer.write("something");
} else {
writer.write(obs + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (writer != null)
try {
writer.close();
} catch (IOException ignore) {
}
}
}
}
I think you could do something like this:
To do this you have to use JLabel to display text: https://docs.oracle.com/javase/tutorial/uiswing/components/label.html
Then to get the input use JTextField:
https://docs.oracle.com/javase/tutorial/uiswing/components/textfield.html
And if you want you can use a JButton after you write in the JTextField to save everything to the file:
https://docs.oracle.com/javase/7/docs/api/javax/swing/JButton.html
http://www.javamex.com/tutorials/swing/jbutton.shtml
once a user selects the button "CLICK HERE TO UPLOAD", the3 file path is stored into a file, and these paths are read into an arraylist, which is shown on the JPanel. the problem is that once a file is selected, it is never updated automatically on the JPanel, unless the application is re runed, before the up to date number of information is displayed. How can this problem be rectified, because i have no clue where i have gone wrong. By the way the arraylists gets updated on runtime but the JPanel never gets updated.
public class Media2 extends JPanel {
private JPanel video_pnl, control_pnl;
private JButton play_btn;
private JLabel loc_lbl;
private int increment;
ArrayList<String> file_location;
ArrayList<JButton> button_lists;
private FileWriter file_writer;
private BufferedWriter buffered_writer;
private JFileChooser filechooser;
private File file;
private JButton btn_upload;
private BufferedReader br;
private FileReader fr;
public Media2(ArrayList<String> file_location) throws IOException {
btn_upload = new JButton("Click here to Upload Video");
String file_path = "C:\\Users\\goldAnthony\\Documents\\NetBeansProjects\\VDMS\\src\\VideoInfos.txt";
file = new File(file_path);
if (!file.exists()) {
file.createNewFile();
file_writer = new FileWriter(file.getAbsolutePath());
} else {
file_writer = new FileWriter(file.getAbsolutePath(), true);
}
add(btn_upload);
Handlers handler = new Handlers();
btn_upload.addActionListener(handler);
this.file_location = file_location;
readFile(file_location, file_path);
}
private void readFile(ArrayList<String> file_location, String file_path) throws FileNotFoundException, IOException {
fr = new FileReader(file_path);
br = new BufferedReader(fr);
String text = "";
String line2;
line2 = br.readLine();
while (line2 != null) {
int i = 0;
file_location.add(i, line2);
line2 = br.readLine();
i++;
}
configurePanel(file_location);
//System.out.print(file_location.size() + "in the read file 1");
}
private void configurePanel(ArrayList<String> file_location) {
increment = 0;
while (increment < file_location.size()) {
video_pnl = new JPanel();
video_pnl.setLayout(new BoxLayout(video_pnl, BoxLayout.Y_AXIS));
loc_lbl = new JLabel();
loc_lbl.setText(file_location.get(increment));
control_pnl = new JPanel();
control_pnl.setLayout(new FlowLayout(FlowLayout.CENTER));
video_pnl.add(loc_lbl);
control_pnl.add(createButton(increment));
video_pnl.add(control_pnl, BorderLayout.SOUTH);
video_pnl.revalidate();
add(video_pnl);
increment++;
}
}
private JButton createButton(final int i) {
play_btn = new JButton("Play");
play_btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// System.out.println(file_location.get(i));
play(i);
}
});
return play_btn;
}
public void play(int i) {
System.out.println(file_location.get(i));
}
private class Handlers implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btn_upload) {
try { //display the image in jlabel
file = new File("C:\\Users\\goldAnthony\\Documents\\NetBeansProjects\\VDMS\\src\\VideoInfos.txt");
if (!file.exists()) {
file.createNewFile();
file_writer = new FileWriter(file.getAbsolutePath());
} else {
file_writer = new FileWriter(file.getAbsolutePath(), true);
}
buffered_writer = new BufferedWriter(file_writer);
//creating a file chooser
filechooser = new JFileChooser();
filechooser.setDialogTitle("Choose Your Video");
// //below codes for select the file
int returnval = filechooser.showOpenDialog(null);
if (returnval == JFileChooser.APPROVE_OPTION) {
file = filechooser.getSelectedFile();
String filename = file.getAbsolutePath();
buffered_writer.write(filename);
buffered_writer.newLine();
buffered_writer.close();
}
} catch (IOException | HeadlessException ex) {
System.out.println(ex.getMessage());
}
}
}
}
public static void main(String[] args) throws IOException {
//Declare and initialize local variables
ArrayList<String> file_location = new ArrayList<>();
//creates instances of the VlcPlayer object, pass the mediaPath and invokes the method "run"
Media2 mediaplayer = new Media2(file_location);
JFrame ourframe = new JFrame();
ourframe.setContentPane(mediaplayer);
ourframe.setLayout(new GridLayout(5, 1));
ourframe.setSize(300, 560);
ourframe.setVisible(true);
ourframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
When you add components to a visible GUI the basic code is:
panel.add(...);
panel.revalidate();
panel.repaint();
You are revalidating the wrong panel:
video_pnl.revalidate(); // wrong panel
add(video_pnl);
You should be doing:
//video_pnl.revalidate();
add(video_pnl);
revalidate();
repaint();
Your code needs some changes, try:
private void configurePanel(ArrayList<String> file_location) {
increment = 0;
while (increment < file_location.size()) {
addEntry(file_location.get(increment));//--------->New line
increment++;
}
}
private void addEntry(String location) {//--------->New constructor
video_pnl = new JPanel();
video_pnl.setLayout(new BoxLayout(video_pnl, BoxLayout.Y_AXIS));
loc_lbl = new JLabel();
loc_lbl.setText(location);
control_pnl = new JPanel();
control_pnl.setLayout(new FlowLayout(FlowLayout.CENTER));
video_pnl.add(loc_lbl);
control_pnl.add(createButton(increment));
video_pnl.add(control_pnl, BorderLayout.SOUTH);
video_pnl.revalidate();
add(video_pnl);
}
and:
private class Handlers implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btn_upload) {
try { //display the image in jlabel
file = new File("C:\\VideoInfos.txt");
if (!file.exists()) {
file.createNewFile();
file_writer = new FileWriter(file.getAbsolutePath());
} else {
file_writer = new FileWriter(file.getAbsolutePath(), true);
}
buffered_writer = new BufferedWriter(file_writer);
//creating a file chooser
filechooser = new JFileChooser();
filechooser.setDialogTitle("Choose Your Video");
// //below codes for select the file
int returnval = filechooser.showOpenDialog(null);
if (returnval == JFileChooser.APPROVE_OPTION) {
file = filechooser.getSelectedFile();
String filename = file.getAbsolutePath();
buffered_writer.newLine();
buffered_writer.write(filename);
buffered_writer.newLine();
buffered_writer.close();
addEntry(filename);//---------------->New Line
validate();//------------>New Line
}
} catch (IOException | HeadlessException ex) {
System.out.println(ex.getMessage());
}
}
}
}
Now it's working. You have to make further changes, of course :)
I am attempting to make a "messenger"(just for learning really) and am pretty new to Socket/ServerSocket and am currently stuck in making the networking part.
Also, I do know that the ClientNetworking isn't complete. I have tried to finish it but I am stumped.
ServerMain:
public class ServerMain extends JFrame {
int WIDTH = 480;
int HEIGHT = 320;
String writeToConsole;
JPanel mainPanel, userPanel, consolePanel;
JTabbedPane tabbedPane;
JButton launchButton;
JTextArea console;
JTextField consoleInput;
JScrollPane consoleScroll;
public ServerMain() {
super("Messenger Server");
mainPanel = new JPanel();
mainPanel.setLayout(null);
Networking();
createConsolePanel();
userPanel = new JPanel();
userPanel.setLayout(null);
tabbedPane = new JTabbedPane();
tabbedPane.add(mainPanel, "Main");
tabbedPane.add(userPanel, "Users");
tabbedPane.add(consolePanel, "Console");
add(tabbedPane);
}
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch(UnsupportedLookAndFeelException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
ServerMain frame = new ServerMain();
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setSize(frame.WIDTH, frame.HEIGHT);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setResizable(false);
}
public void Networking() {
ServerNetworking net;
try {
net = new ServerNetworking();
net.start();
} catch(Exception e) {
e.printStackTrace();
}
}
public void createConsolePanel() {
consolePanel = new JPanel();
consolePanel.setLayout(null);
console = new JTextArea();
console.setFont(new Font("", Font.PLAIN, 13 + 1/2));
console.setBounds(0, 0, WIDTH, HEIGHT - 100);
console.setEditable(false);
console.setLineWrap(true);
consoleInput = new JTextField(20);
consoleInput.setBounds(0, 0, WIDTH, 25);
consoleInput.setLocation(0, 240);
consoleInput.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event) {
String input = consoleInput.getText();
if(input.equalsIgnoreCase("/sendmessage")) {
//console.append(input);
console.append("Input who you would like to send the message to:");
consoleInput.setText("");
} if (input.equalsIgnoreCase("/ban")) {
console.append("Who you would like to ban");
consoleInput.setText("");
}
}
});
consolePanel.add(console);
consolePanel.add(consoleInput);
}
public void consoleWrite(String write) {
console.append(write);
}
}
ServerNetworking(Thread):
public class ServerNetworking extends Thread {
private static ServerSocket servSock;
private static final int PORT = 1234;
private static void handleClient() {
Socket link = null;
try {
link = servSock.accept();
Scanner input = new Scanner(link.getInputStream());
PrintWriter output =
new PrintWriter(link.getOutputStream(),true);
int numMessages = 0;
String message = input.nextLine();
while (!message.equals("***CLOSE***")) {
System.out.println("Message received.");
numMessages++;
output.println("Message " +
numMessages + ": " + message);
message = input.nextLine();
}
output.println(numMessages + " messages received.");
} catch(IOException ioEx) {
ioEx.printStackTrace();
} finally {
try {
System.out.println( "\n* Closing connection... *");
link.close();
} catch(IOException ioEx) {
System.out.println("Unable to disconnect!");
System.exit(1);
}
}
}
public void run() {
System.out.println("Opening port...\n");
try {
servSock = new ServerSocket(PORT);
} catch(IOException ioEx) {
System.out.println("Unable to attach to port!");
System.exit(1);
} do {
handleClient();
} while (true);
}
}
ClientMain:
public class ClientMain extends JFrame {
int WIDTH = 640;
int HEIGHT = 480;
JTabbedPane tabbedPane;
JMenuBar topMenuBar;
JMenu userMenu, helpMenu, settingsMenu;
JRadioButtonMenuItem menuItem;
JPanel mainPanel, friendsPanel, groupsPanel, testPanel;
JLabel title;
JScrollPane consoleScrollPane;
JSplitPane friendsPane;
JTextArea messageArea, testArea;
JTextField testField;
Box box;
public ClientMain() {
super("Messenger Client");
Networking();
title = new JLabel("Client!");
title.setFont(new Font("Impact", Font.PLAIN, 32));
mainPanel = new JPanel();
mainPanel.setLayout(null);
mainPanel.add(title);
groupsPanel = new JPanel();
groupsPanel.setLayout(null);
friendsPanel = new JPanel();
friendsPanel.setLayout(null);
testPanel = new JPanel();
testPanel.setLayout(null);
testArea = new JTextArea();
testArea.setFont(new Font("", Font.PLAIN, 13 + 1/2));
testArea.setBounds(0, 0, WIDTH, HEIGHT - 100);
testArea.setEditable(false);
testArea.setLineWrap(true);
testField = new JTextField(20);
testField.setBounds(0, 380, 640, 25);
//testField.setLocation(0, HEIGHT - 50);
testField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ClientNet net = new ClientNet();
String input = null;
input = testField.getText();
testArea.append(input);
testField.setText("");
if(input.equalsIgnoreCase("/sendmessage")) {
testArea.append("\n Input who you would like to send the message to:");
input = null;
if(input.equalsIgnoreCase("Hello")) {
net.userEntry = input;
}
}
}
});
testPanel.add(testArea);
testPanel.add(testField);
tabbedPane = new JTabbedPane();
tabbedPane.add(mainPanel, "Main");
tabbedPane.add(friendsPanel, "Friends");
tabbedPane.add(groupsPanel, "Groups");
tabbedPane.add(testPanel, "Test");
topMenuBar = new JMenuBar();
userMenu = new JMenu("User");
settingsMenu = new JMenu("Settings");
helpMenu = new JMenu("Help");
menuItem = new JRadioButtonMenuItem("Something here");
userMenu.add(menuItem);
topMenuBar.add(userMenu, "User");
topMenuBar.add(settingsMenu, "Settings");
topMenuBar.add(helpMenu, "Help");
add(topMenuBar);
add(tabbedPane);
}
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch(UnsupportedLookAndFeelException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
ClientMain frame = new ClientMain();
Insets insets = frame.getInsets();
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setSize(frame.WIDTH, frame.HEIGHT);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setResizable(false);
frame.setJMenuBar(frame.topMenuBar);
}
public void Networking() {
ClientNet net;
try {
net = new ClientNet();
net.start();
} catch(Exception e) {
e.printStackTrace();
}
}
public void createMenuBar() {
topMenuBar = new JMenuBar();
userMenu = new JMenu("User");
settingsMenu = new JMenu("Settings");
helpMenu = new JMenu("Help");
menuItem = new JRadioButtonMenuItem("MenuItem");
menuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
topMenuBar.add(userMenu, "User");
topMenuBar.add(settingsMenu, "Settings");
topMenuBar.add(helpMenu, "Help");
}
public void getFriends(String username) {
}
}
ClientNetworking(Thread):
public class ClientMain extends JFrame {
int WIDTH = 640;
int HEIGHT = 480;
JTabbedPane tabbedPane;
JMenuBar topMenuBar;
JMenu userMenu, helpMenu, settingsMenu;
JRadioButtonMenuItem menuItem;
JPanel mainPanel, friendsPanel, groupsPanel, testPanel;
JLabel title;
JScrollPane consoleScrollPane;
JSplitPane friendsPane;
JTextArea messageArea, testArea;
JTextField testField;
Box box;
public ClientMain() {
super("Messenger Client");
Networking();
title = new JLabel("Client!");
title.setFont(new Font("Impact", Font.PLAIN, 32));
mainPanel = new JPanel();
mainPanel.setLayout(null);
mainPanel.add(title);
groupsPanel = new JPanel();
groupsPanel.setLayout(null);
friendsPanel = new JPanel();
friendsPanel.setLayout(null);
testPanel = new JPanel();
testPanel.setLayout(null);
testArea = new JTextArea();
testArea.setFont(new Font("", Font.PLAIN, 13 + 1/2));
testArea.setBounds(0, 0, WIDTH, HEIGHT - 100);
testArea.setEditable(false);
testArea.setLineWrap(true);
testField = new JTextField(20);
testField.setBounds(0, 380, 640, 25);
//testField.setLocation(0, HEIGHT - 50);
testField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ClientNet net = new ClientNet();
String input = null;
input = testField.getText();
testArea.append(input);
testField.setText("");
if(input.equalsIgnoreCase("/sendmessage")) {
testArea.append("\n Input who you would like to send the message to:");
input = null;
if(input.equalsIgnoreCase("Hello")) {
net.userEntry = input;
}
}
}
});
testPanel.add(testArea);
testPanel.add(testField);
tabbedPane = new JTabbedPane();
tabbedPane.add(mainPanel, "Main");
tabbedPane.add(friendsPanel, "Friends");
tabbedPane.add(groupsPanel, "Groups");
tabbedPane.add(testPanel, "Test");
topMenuBar = new JMenuBar();
userMenu = new JMenu("User");
settingsMenu = new JMenu("Settings");
helpMenu = new JMenu("Help");
menuItem = new JRadioButtonMenuItem("Something here");
userMenu.add(menuItem);
topMenuBar.add(userMenu, "User");
topMenuBar.add(settingsMenu, "Settings");
topMenuBar.add(helpMenu, "Help");
add(topMenuBar);
add(tabbedPane);
}
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch(UnsupportedLookAndFeelException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
ClientMain frame = new ClientMain();
Insets insets = frame.getInsets();
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setSize(frame.WIDTH, frame.HEIGHT);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setResizable(false);
frame.setJMenuBar(frame.topMenuBar);
}
public void Networking() {
ClientNet net;
try {
net = new ClientNet();
net.start();
} catch(Exception e) {
e.printStackTrace();
}
}
public void createMenuBar() {
topMenuBar = new JMenuBar();
userMenu = new JMenu("User");
settingsMenu = new JMenu("Settings");
helpMenu = new JMenu("Help");
menuItem = new JRadioButtonMenuItem("MenuItem");
menuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
topMenuBar.add(userMenu, "User");
topMenuBar.add(settingsMenu, "Settings");
topMenuBar.add(helpMenu, "Help");
}
public void getFriends(String username) {
}
}
This is the error I get when I launch the server, then the client:
It shouldn't be saying "Message received" cause I don't actually send a message
Opening port...
Message received.
* Closing connection... *
Exception in thread "Thread-1" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)
at Server.ServerNetworking.handleClient(ServerNetworking.java:29)
at Server.ServerNetworking.run(ServerNetworking.java:53)
I think the problem is the following loop in the ServerNetworking class:
while (!message.equals("***CLOSE***")) {
System.out.println("Message received.");
numMessages++;
output.println("Message " +
numMessages + ": " + message);
message = input.nextLine();
}
The problem with this code is that after recieving the complete message from the client the last line of code
message = input.nextLine();
looks for another next line from the message, but since the message has already been consumed, it throws the following exception:
NoSuchElementException - if no line was found
So before reading for the next line you need to make sure that there is next line to be read. This you can do using the
hasNextLine()
method, which will return true if there is next line otherwise false.
if(input.hasNextLine()) {
message = input.nextLine(); // read the next line
} else {
break; // exit the loop because, nothing to read left
}