As a little side project I'd thought it would cool to make a text editor. I'm currently stuck on opening files. This is my code for opening the file(e is an ActionEvent, open is a JMenuItem):
else if (e.getSource() == open) {
JFileChooser choice = new JFileChooser();
int option = choice.showOpenDialog(this);
if (option == JFileChooser.APPROVE_OPTION) {
try{
Scanner scan = new Scanner(new FileReader((open).getSelectedFile().getPath()));
}
}
}
The try block is giving me the trouble. Eclipse is saying that getSelectedFile() is undefined for type JMenuItem. It also appears to be undefined for MenuItems as well. Is there another way to approach this, or another method that works the same?
You need to call getSelectedFile() on the JFileChooser once it has returned, so change your code to:
choice.getSelectedFile()
private void selectfileActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser jFileChooser=new JFileChooser();
StringBuffer buffer;
buffer = new StringBuffer();
int result= jFileChooser.showOpenDialog(this);
if(result==JFileChooser.APPROVE_OPTION)
{
try {
FileReader reader;
reader = null;
JOptionPane.showMessageDialog(this,"hii user clicked open sysytem");
File file=jFileChooser.getSelectedFile();
reader=new FileReader(file);
int i=1;
while(i!=-1)
{
i=reader.read();
char ch=(char) i;
buffer.append(ch);
}
notepad.setText(buffer.toString());
} catch (FileNotFoundException ex) {
Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
import java.awt.EventQueue;
public class FileChooser extends JFrame
{
private JPanel contentPane;
String filename;
// main
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
try
{
FileChooser frame = new FileChooser();
frame.setVisible(true);
} catch (Exception e)
{
e.printStackTrace();
}
}
});
}
public FileChooser()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
// button to selct file
JButton btnNewButton = new JButton("Select file");
btnNewButton.setBounds(10, 2, 89, 23);
contentPane.add(btnNewButton);
// area to display file content
final JTextArea textArea = new JTextArea();
textArea.setBounds(10, 36, 414, 215);
contentPane.add(textArea);
// save button
final JButton btnSave = new JButton("Save");
btnSave.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
try
{
FileWriter writer = new FileWriter(filename.replace(".",
"_out."));
BufferedWriter bwr = new BufferedWriter(writer);
bwr.write(textArea.getText());
bwr.close();
writer.close();
System.out.println(textArea.getText());
} catch (Exception e)
{
System.out.println("Error");
}
}
});
btnSave.setBounds(283, 2, 89, 23);
contentPane.add(btnSave);
// listen to button clicks
btnNewButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
JFileChooser fileChooser = new JFileChooser();
int returnValue = fileChooser.showOpenDialog(null);
if (returnValue == JFileChooser.APPROVE_OPTION)
{
File selectedFile = fileChooser.getSelectedFile();
filename = selectedFile.getAbsolutePath();
try
{
FileReader reader = new FileReader(filename);
BufferedReader br = new BufferedReader(reader);
textArea.read(br, null);
br.close();
System.out.println(textArea.getText());
} catch (Exception e)
{
System.out.println("Error");
}enter code here
}
}
enter code here
});
}
}
Related
I'm having a problem with my methods for a school assignment which are supposed to load and save String arrays to a file. It seems like it does not save or load properly. For example, I saved a string of "ok" in a file, let's call it x. Then I rerun the app and changed the path to a directory and it read the string "ok" from it even though it wasn't initially saved the directory and the directory shouldn't be allowed anyways. I really don't know how to solve it and I tried to manipulate the code but I do not know what causes it so it's hard to think of a solution.
Some details on my task:
have to use File Output/Input Stream and Object Output/Input Stream
question and answer strings have to be initialized to 0 size if the path is empty/is a dir/ file not found
take answer and question string from textfield, save it to a file and read the existing ones from the file
question and answer string arrays have to be in a separate class
Code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.util.Arrays;
public class App2 extends JFrame implements ActionListener {
JPanel mpanel, qpanel, apanel, bpanel, upanel;
JTextField tf1, tf2, tf3;
JButton jb;
JLabel jl1, jl2, jl3;
String path;
public static void main(String[] args) {
App2 object = new App2();
System.out.println("app init/ array size:" + QAData.question.length);
}
App2() {
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setSize(400, 200);
this.setTitle("App2");
mpanel = new JPanel();
this.add(mpanel);
mpanel.setLayout(new GridLayout(4, 1));
qpanel = new JPanel();
mpanel.add(qpanel);
apanel = new JPanel();
mpanel.add(apanel);
upanel = new JPanel();
mpanel.add(upanel);
bpanel = new JPanel();
mpanel.add(bpanel);
jl1 = new JLabel("Question: ");
qpanel.add(jl1);
tf1 = new JTextField(20);
tf1.setHorizontalAlignment(JTextField.LEFT);
qpanel.add(tf1);
tf1.addActionListener(this);
jl2 = new JLabel("Answer: ");
apanel.add(jl2);
tf2 = new JTextField(20);
tf2.setHorizontalAlignment(JTextField.LEFT);
apanel.add(tf2);
tf2.addActionListener(this);
jl3 = new JLabel("Path: ");
upanel.add(jl3);
tf3 = new JTextField(20);
tf3.setHorizontalAlignment(JTextField.LEFT);
upanel.add(tf3);
tf3.addActionListener(this);
jb = new JButton("Update");
jb.setHorizontalAlignment(JButton.CENTER);
bpanel.add(jb);
jb.addActionListener(this);
this.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == tf3)
path = tf3.getText();
if (e.getSource() == jb) {
load();
save();
tf1.setText("");
tf2.setText("");
}
}
void load() {
try {
File file = new File("path");
FileInputStream fis = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fis);
boolean fileIsOk = file.isFile() && !(tf3.getText().equals("")) && !(file.isDirectory());
if (!fileIsOk) {
QAData.question = new String[0];
QAData.answer = new String[0];
System.out.println("size 0 applied");
} else {
QAData.question = (String[]) ois.readObject();
QAData.answer = (String[]) ois.readObject();
}
ois.close();
} catch (ClassNotFoundException e) {
System.out.println("No such class found");
e.printStackTrace();
} catch (IOException e) {
System.out.println("I/O exception during the load");
e.printStackTrace();
} catch (NullPointerException e) {
System.out.println("The object you are trying to read has the null value");
e.printStackTrace();
}
}
void save() {
try {
File file = new File("path");
FileOutputStream fos = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(fos);
boolean fileIsOk = file.isFile() && !(tf3.getText().equals("")) && !(file.isDirectory());
if (fileIsOk) {
QAData.question = Arrays.copyOf(QAData.question, QAData.question.length + 1);
QAData.question[(QAData.question.length - 1)] = tf1.getText();
QAData.answer = Arrays.copyOf(QAData.answer, QAData.answer.length + 1);
QAData.answer[(QAData.answer.length - 1)] = tf2.getText();
oos.writeObject(QAData.question);
oos.writeObject(QAData.answer);
}
oos.close();
} catch (IOException e) {
System.out.println("I/O exception during the save");
e.printStackTrace();
} catch (NullPointerException e) {
System.out.println("The object you are trying to save has the null value");
e.printStackTrace();
}
}
static class QAData implements Serializable {
static String[] question = new String[0];
static String[] answer = new String[0];
}
}
I want to know how my console output can be save in a notepad file?
import java.awt.EventQueue;
public class HLS1 {
private JFrame frmHttpsLiveStreaming;
private JTextField textField;
// file is accessed to the whole class
private File file;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
HLS1 window = new HLS1();
window.frmHttpsLiveStreaming.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public HLS1() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmHttpsLiveStreaming = new JFrame();
frmHttpsLiveStreaming.setTitle("HTTPS Live Streaming");
frmHttpsLiveStreaming.setBounds(100, 100, 494, 112);
frmHttpsLiveStreaming.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmHttpsLiveStreaming.getContentPane().setLayout(null);
JButton btnBrowse = new JButton("Open File");
btnBrowse.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.out.println("Argument:" + arg0);
JFileChooser fs = new JFileChooser(new File("c:\\"));
fs.setDialogTitle("Open a file");
fs.setFileFilter(new FileTypeFilter(".m3u8", ""));
fs.setFileFilter(new FileTypeFilter(".m3u", ""));
fs.showOpenDialog(null);
file = fs.getSelectedFile();
textField.setText(file.getAbsolutePath());
}
});
btnBrowse.setBounds(336, 7, 89, 23);
frmHttpsLiveStreaming.getContentPane().add(btnBrowse);
JButton btnNewButton_1 = new JButton("Clear");
btnNewButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
textField.setText("");
}
});
btnNewButton_1.setBounds(237, 39, 89, 23);
frmHttpsLiveStreaming.getContentPane().add(btnNewButton_1);
JLabel lblUrl = new JLabel("URL");
lblUrl.setBounds(83, 11, 24, 14);
frmHttpsLiveStreaming.getContentPane().add(lblUrl);
textField = new JTextField();
textField.setBounds(116, 11, 210, 19);
frmHttpsLiveStreaming.getContentPane().add(textField);
textField.setColumns(10);
JButton btnNewButton = new JButton("Check");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
List<String> fileArray = new ArrayList<String>();
List<String> errors = new ArrayList<String>();
String regex = "^(https?|ftp|file)://[-a-zA-Z0-9+&##/%?=~_|!:,.;]*[-a-zA-Z0-9+&##/%=~_|]";
Scanner s = null;
if(textField.getText().matches(regex)){
URL url = new URL(textField.getText());
s= new Scanner(url.openStream());
}else{
s = new Scanner(new BufferedReader(new FileReader(file)));
}
if(s != null){
while(s.hasNextLine()){
String line = s.nextLine();
if(!line.isEmpty()){
fileArray.add(line);
}
System.out.println(line);
}
}
s.close();
errors.addAll(validateEXTM3U(fileArray));
for (String error : errors) {
System.out.println(error);
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
btnNewButton.setBounds(126, 39, 89, 23);
frmHttpsLiveStreaming.getContentPane().add(btnNewButton);
}
private List<String> validateEXTM3U(List<String> fileArray){
List<String> errors = new ArrayList<String>();
String tag = fileArray.get(0);
if(!tag.equals("#EXTM3U")){
errors.add("First line in the menifest file is not #EXTM3U");
}
return errors;
}
}
It could be a hacky solution , but if you are running in windows or linux then you can pipe / redirect it.
java HLS1 > notepad.txt
if not what you are looking for , then why not using something called log4j ?
Why don't you write your own utility that has an public static void output(String output) method. Then instead of using System.out.println("...") you call output("...") then in your output(String output) method you can do anything with the output, like first write to the file, then print to the console.
Hope this helps.
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
}
i have made an application that loads image from specific directory, loads all images in stack, when i am clicking on next button next image loads.
i have also added JSlider that change Brightness of Loaded Image but it doesn't work.
i don't know why but i am not getting exact problem.
my code :
public class PictureEditor extends JFrame
{
private static final long serialVersionUID = 6676383931562999417L;
String[] validpicturetypes = {"png", "jpg", "jpeg", "gif"};
Stack<File> pictures ;
JLabel label = new JLabel();
BufferedImage a = null;
float fval=1;
public PictureEditor()
{
JPanel panel = new JPanel();
JMenuBar menubar = new JMenuBar();
JMenu toolsmenu = new JMenu("Tools");
final JSlider slider1;
slider1 = new JSlider(JSlider.HORIZONTAL,0,4,1);
slider1.setToolTipText("Slide To Change Brightness");
slider1.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, null, null, null, null));
slider1.setMajorTickSpacing(1);
slider1.setPaintLabels(true);
slider1.setPaintTicks(true);
slider1.setPaintTrack(true);
slider1.setAutoscrolls(true);
slider1.setBounds(50, 55, 200, 50);
slider1.addChangeListener(new ChangeListener()
{
#Override
public void stateChanged(ChangeEvent e)
{
System.out.println("Before");
fval=slider1.getValue();
chgBrt(fval);
repaint();
}
});
TitledBorder title;
title = BorderFactory.createTitledBorder("Operations");
title.setTitleJustification(TitledBorder.LEFT);
JButton RT90 = new JButton("");
JButton RT180 = new JButton("");
JButton RTM90 = new JButton("");
JButton RTM180 = new JButton("");
JButton NEXT = new JButton("");
Image img = null;
Image imgn = null;
try
{
img = ImageIO.read(getClass().getResource("/images/images_Horizontal.png"));
imgn = ImageIO.read(getClass().getResource("/images/next12.png"));
}
catch (IOException e)
{
e.printStackTrace();
}
RT90.setIcon(new ImageIcon(img));
RT180.setIcon(new ImageIcon(img));
RTM90.setIcon(new ImageIcon(img));
RTM180.setIcon(new ImageIcon(img));
NEXT.setIcon(new ImageIcon(imgn));
JPanel buttonPane = new JPanel();
buttonPane.add(slider1);
buttonPane.add(Box.createRigidArea(new Dimension(250,0)));
buttonPane.setBorder(title);
buttonPane.add(RT90);
buttonPane.add(RT180);
buttonPane.add(RTM90);
buttonPane.add(RTM180);
buttonPane.add(Box.createRigidArea(new Dimension(250,0)));
NEXT.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0)
{
nextImage();
}
});
buttonPane.add(NEXT);
getContentPane().add(buttonPane, BorderLayout.SOUTH);
final File dir = new File("");
final JFileChooser file;
file = new JFileChooser();
file.setCurrentDirectory(dir);
file.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
file.showOpenDialog(panel);
String path = file.getSelectedFile().getAbsolutePath();
System.out.println(path);
pictures= getFilesInFolder(path.toString());
Action nextpictureaction = new AbstractAction("Next Picture")
{
private static final long serialVersionUID = 2421742449531785343L;
#Override
public void actionPerformed(ActionEvent e)
{
nextImage();
}
};
setJMenuBar(menubar);
menubar.add(toolsmenu);
toolsmenu.add(nextpictureaction);
panel.add(label,BorderLayout.CENTER);
add(panel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationByPlatform(true);
setSize(1000, 700);
setTitle("PictureEditor");
setVisible(true);
}
public Stack<File> getFilesInFolder(String startPath)
{
File startFolder = new File(startPath);
Stack<File> picturestack = new Stack<File>();
String extension;
int dotindex;
// Go through the folder
for (File file : startFolder.listFiles())
{
extension = "";
dotindex = file.getName().lastIndexOf('.'); // Get the index of the dot in the filename
if (dotindex > 0)
{
extension = file.getName().substring(dotindex + 1);
// Iterate all valid file types and check it
for (String filetype : validpicturetypes)
{
if (extension.equals(filetype))
{
picturestack.add(file);
}
}
}
}
return picturestack;
}
public void nextImage()
{
try
{
a=ImageIO.read(pictures.pop().getAbsoluteFile());
}
catch (IOException e1)
{
e1.printStackTrace();
}
final ImageIcon image = new ImageIcon(a);
label.setIcon(image);
repaint();
}
#SuppressWarnings("null")
public void chgBrt(float f)
{
Graphics g = null;
Graphics2D g2d=(Graphics2D)g;
try
{
BufferedImage dest=changeBrightness(a,(float)fval);
System.out.println("Change Bright");
int w = a.getWidth();
int h = a.getHeight();
g2d.drawImage(dest,w,h,this);
ImageIO.write(dest,"jpeg",new File("/images/dest.jpg"));
System.out.println("Image Write");
}
catch(Exception e)
{
e.printStackTrace();
}
}
public BufferedImage changeBrightness(BufferedImage src,float val)
{
RescaleOp brighterOp = new RescaleOp(val, 0, null);
return brighterOp.filter(src,null); //filtering
}
public static void main(String[] args)
{
javax.swing.SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new PictureEditor();
}
});
}
}
anyone who can guide me and tell me where i am wrong ??
You may be able to adapt the approach shown in this RescaleTest, which varies the scaleFactor passed to RescaleOp to a value between zero and twice the slider's maximum.