I am developing a java program which takes a students name and displays the name and date on a JTextPane. When the user presses exit, the program is supposed to automatically save the file in a specified directory inside a new folder created with the same name as the one the user provided for the student. Below is my code:
public class StudentRecorder extends JFrame implements ActionListener{
MyKeyListener listener;
public JTextPane page;
private JScrollPane scroll;
private JMenuBar menubar;
private AttributeSet aset;
public String name;
private JMenu menufile;
private JMenuItem exit;
StudentRecorder(){
super("Student Recorder");
init();
this.setSize(400, 400);
this.setLocation(400, 400);
this.setVisible(true);
}
void init(){
menubar = new JMenuBar();
name = JOptionPane.showInputDialog(this, "Enter Student's Name:\n(For locations of files to be preserved, "
+ "names\nare case-sensitive.)", "Student Name", JOptionPane.QUESTION_MESSAGE);
String timeStamp = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss").format(Calendar.getInstance().getTime());
page = new JTextPane();
if (name.equals("")){
aset = StyleContext.getDefaultStyleContext().addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, Color.RED);
page.setCharacterAttributes(aset, false);
page.setText(timeStamp + "\n" + "(Student Name Not Typed In. You must manually save this file. File "
+ "wont be autosaved.)" + "\n\n");
}
else{
page.setText(timeStamp + "\n" + name + "\n\n");
}
//Declaration
menufile = new JMenu("File");
exit = new JMenuItem("Exit");
//Adding to JMenuBar
menubar.add(menufile);
menufile.add(exit);
//Add ActionListener
exit.addActionListener(this);
//Page characteristics
aset = StyleContext.getDefaultStyleContext().addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, Color.BLACK);
page.setCharacterAttributes(aset, false);
Font font = new Font("Arial", Font.PLAIN, 14);
page.setFont(font);
this.setJMenuBar(menubar);
scroll = new JScrollPane(page);
this.add(scroll);
scroll.createHorizontalScrollBar();
listener = new MyKeyListener();
page.addKeyListener(listener);
page.setFocusable(true);
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == exit){
File f = new File("./Desktop/" + name);
try{
if(f.mkdir()){
System.out.println("Directory Created.");
System.exit(0);
}
else{
System.out.println("Directory Not Created.");
}
}catch(Exception e1){
e1.printStackTrace();
}
}
}
}
I am running into an issue in my program where the file doesn't save to the Directory with the name provided. It consistently pops up in the console 'Directory Not Created'. Can anyone please tell me how I can fix this problem? There are no other errors in my code preventing it from running.
Thanks in advance to all who reply.
The reason you are getting this problem is because you are trying to create a directory inside ./Desktop and you are running this from inside Documents which doesn't have a Desktop folder. To save it to Desktop you have to use an absolute path. Absolute paths start with a / on unix (mac and linux) and with C: on Windows:
File f = new File("/Users/yourname/Desktop/" + name);
Related
I've a simple GUI file which is here:
I want to update the Label text each time when new file is selected
But when I am selecting any file, it is overlapping on the existing Jlabel text, so, please help me how do I update my JLabel text.
Here is my code:
protected static void excelButtonAction(){
excelReturnVal = fc.showOpenDialog(excelButton);
if(excelReturnVal==JFileChooser.APPROVE_OPTION){
FileValidation.excelFileValidation(fc);
System.out.println(FileValidation.getName() );
if(status==JFileChooser.CANCEL_OPTION){
}else{
fileName=FileValidation.getName();
FileValidation.updatemylabel(fileName);
excelFileName = new JLabel(fileName);
excelFileName.setText(fileName);
excelFileName.setBounds(140, 67, 350, 30);
excelFileName.setFont(new Font("Myriad Pro",Font.PLAIN,10));
panel.add(excelFileName);
panel.revalidate();
panel.repaint();
}
} else{
System.out.println("Open command cancelled by user." + newline);
}
}
public static void updatemylabel(String exfileName){
excelFileName = new JLabel(fileName);
excelFileName.setText(fileName);
JFileChooser chooser = new JFileChooser();
chooser.addPropertyChangeListener(new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
if(JFileChooser.SELECTED_FILE_CHANGED_PROPERTY.equals(evt.getPropertyName())){
JFileChooser chooser = (JFileChooser) evt.getSource();
File oldFile = (File) evt.getOldValue();
File newFile = (File) evt.getNewValue();
File curFile = chooser.getSelectedFile();
}else if(JFileChooser.SELECTED_FILES_CHANGED_PROPERTY.equals(evt.getPropertyName())){
JFileChooser chooser = (JFileChooser)evt.getSource();
File[] oldFiles = (File[])evt.getOldValue();
File[] newFiles = (File[])evt.getNewValue();
File[] files = chooser.getSelectedFiles();
}
}
});
excelFileName = new JLabel(fileName);
excelFileName.setText(fileName);
excelFileName.setBounds(140, 67, 350, 30);
excelFileName.setFont(new Font("Myriad Pro",Font.PLAIN,10));
panel.add(excelFileName);
panel.revalidate();
panel.repaint();
existingText=exfileName;
}
Let me know if any further information is required to resolve my issue.
Thanks in advance for your co-operateion.
Your code creates a new JLabel instance every time. You need to create an instance once, store it in a field of your class, and call setText() whenever you need to update it.
You can have a look at the following for better understanding of labels in java :
How to Use Labels
setText
public void setText(String text)
Defines the single line of text this component will display. If the value of text is null or empty string, nothing is displayed.
The default value of this property is null.
This is a JavaBeans bound property.
Here is my code. I am trying to make a basic text editor just to try out file writing and reading along with JPanels and such. My current issue is that users are required to input the full file path of the file and that can get quite frustrating. So I made a button that allows the user to have preset file path settings. When you click on the 'File Path Settings' button, there is a window that pops up allowing you to set the settings. (A file browsing button will be implemented later I just wanted to do this for fun first.)
public class EventListeners {
String textAreaValue;
String filePath;
String rememberedPath;
String rememberedPathDirectory;
//Global components
JTextField fileName,saveFilePath,filePathSaveDirectory,savedFilePath;
JButton save,help,savePath;
//JTextArea text;
public EventListeners(){
window();
}
public void window(){
JFrame window = new JFrame();
window.setVisible(true);
window.setSize(650,500);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
JButton saveFilePath = new JButton("File Path Save Settings");
JTextArea ltext = new JTextArea(10,50);
JLabel filler = new JLabel(" ");
JLabel lfileName = new JLabel("File Path(If error click help)");
JLabel lsaveFilePath = new JLabel("Save Path");
fileName = new JTextField(30);
save = new JButton("Save File");
help = new JButton("Help");
panel.add(lfileName);
panel.add(fileName);
panel.add(save);
panel.add(help);
panel.add(ltext);
panel.add(filler);
window.add(panel);
saveFilePath.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
//JOptionPane.showMessageDialog(null,"Hello world!");
JFrame windowB = new JFrame();
int windows = 2;
windowB.setVisible(true);
windowB.setSize(500,500);
windowB.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panelB = new JPanel();
JLabel lFilePathSaveDirectory = new JLabel("Directory where the file path settings will be stored");
filePathSaveDirectory = new JTextField(20);
JLabel lsavedFilePath = new JLabel("The full file path or part you want stored.");
savedFilePath = new JTextField(20);
savePath = new JButton("Save Settings");
panelB.add(lFilePathSaveDirectory);
panelB.add(filePathSaveDirectory);
panelB.add(lsavedFilePath);
panelB.add(savedFilePath);
panelB.add(savePath);
windowB.add(panelB);
}
});
save.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textAreaValue = ltext.getText();
filePath = fileName.getText();
try {
FileWriter fw = new FileWriter(filePath);
PrintWriter pw = new PrintWriter(fw);
pw.println(textAreaValue);
pw.close();
JOptionPane.showMessageDialog(panel, "File Written!","Success!",JOptionPane.PLAIN_MESSAGE);
} catch(IOException x) {
JOptionPane.showMessageDialog(panel, "Error in writing file. \n\n Try Checking the file path or making sure the directory in which you are saving the file exists. \n\n Keep Calm and Love Beavers","Error",JOptionPane.ERROR_MESSAGE);
}
}
});
help.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(panel, " ***The file name must be the full file path.***\n\n-=-=-=-=-=-=-=-=-=(MAC)=-=-=-=-=-=-=-=-=-\n\n Example: /Users/Cheese/Documents/FileName.txt\n\n\n-=-=-=-=-=-=-=-=(WINDOWS)=-=-=-=-=-=-=-=-\n\n *Note that 2 back slashes must be used* \n\nC:\\user\\docs\\example.txt", "Help",JOptionPane.PLAIN_MESSAGE);
}
});
panel.add(saveFilePath);
window.add(panel);
saveFilePath.setSize(20,100);
savePath.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
rememberedPathDirectory = filePathSaveDirectory.getText();
rememberedPath = savedFilePath.getText();
try {
FileWriter fw = new FileWriter(rememberedPathDirectory+"filePathSettings.txt");
PrintWriter pw = new PrintWriter(fw);
pw.println(rememberedPath);
pw.close();
JOptionPane.showMessageDialog(panel, "File Written!","Success!",JOptionPane.PLAIN_MESSAGE);
} catch(IOException x) {
JOptionPane.showMessageDialog(panel, "Error in writing file. \n\n Try Checking the file path or making sure the directory in which you are saving the file exists. \n\n Keep Calm and Love Beavers","Error",JOptionPane.ERROR_MESSAGE);
}
JOptionPane.showMessageDialog(panel, "The application will close. Anythings not saved will be deleted", "Alert",JOptionPane.WARNING_MESSAGE);
}
});
}
public static void main(String[] args) {
new EventListeners();
}
}
main problem is you are creating variable with same name inside the constructer, you already define as instance .then your instance variable keep uninitialized/null.
for example
you have declare instance variable
JButton save, help, savePath, saveFilePath;
inside constructor you are creating another local jbutton and initialize it so instance variable is null.
so instead of creating new one you should initialize instance field.
JButton saveFilePath = new JButton("File Path Save Settings"); // problem
saveFilePath = new JButton("File Path Save Settings"); // correct way
but there is a another problem ..you have declare saveFilePath instance field as a jtextfield and you have created a saveFilePath button inside the constructor .i think it may be a button not a textfield.
also you are initializing some variables inside saveFilePath.addActionListener(new ActionListener() { method but you are adding actionlistners to them before saveFilePath action fired .you have to add actionlistners after you initialized a component.
also you should call repaint() at last after you add all the component to a frame..
try to run this code
import javax.swing.*;
import java.awt.event.*;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class EventListeners {
String textAreaValue;
String filePath;
String rememberedPath;
String rememberedPathDirectory;
//Global components
JTextField fileName, filePathSaveDirectory, savedFilePath;
JButton save, help, savePath, saveFilePath;
//JTextArea text;
public EventListeners() {
window();
}
public void window() {
JFrame window = new JFrame();
window.setSize(650, 500);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
saveFilePath = new JButton("File Path Save Settings");
JTextArea ltext = new JTextArea(10, 50);
JLabel filler = new JLabel(" ");
JLabel lfileName = new JLabel("File Path(If error click help)");
JLabel lsaveFilePath = new JLabel("Save Path");
fileName = new JTextField(30);
save = new JButton("Save File");
help = new JButton("Help");
panel.add(lfileName);
panel.add(fileName);
panel.add(save);
panel.add(help);
panel.add(ltext);
panel.add(filler);
window.add(panel);
saveFilePath.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//JOptionPane.showMessageDialog(null,"Hello world!");
JFrame windowB = new JFrame();
int windows = 2;
windowB.setVisible(true);
windowB.setSize(500, 500);
windowB.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panelB = new JPanel();
JLabel lFilePathSaveDirectory = new JLabel("Directory where the file path settings will be stored");
filePathSaveDirectory = new JTextField(20);
JLabel lsavedFilePath = new JLabel("The full file path or part you want stored.");
savedFilePath = new JTextField(20);
savePath = new JButton("Save Settings");
panelB.add(lFilePathSaveDirectory);
panelB.add(filePathSaveDirectory);
panelB.add(lsavedFilePath);
panelB.add(savedFilePath);
panelB.add(savePath);
windowB.add(panelB);
System.out.println(savePath);
savePath.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
rememberedPathDirectory = filePathSaveDirectory.getText();
rememberedPath = savedFilePath.getText();
try {
FileWriter fw = new FileWriter(rememberedPathDirectory + "filePathSettings.txt");
PrintWriter pw = new PrintWriter(fw);
pw.println(rememberedPath);
pw.close();
JOptionPane.showMessageDialog(panel, "File Written!", "Success!", JOptionPane.PLAIN_MESSAGE);
} catch (IOException x) {
JOptionPane.showMessageDialog(panel, "Error in writing file. \n\n Try Checking the file path or making sure the directory in which you are saving the file exists. \n\n Keep Calm and Love Beavers", "Error", JOptionPane.ERROR_MESSAGE);
}
JOptionPane.showMessageDialog(panel, "The application will close. Anythings not saved will be deleted", "Alert", JOptionPane.WARNING_MESSAGE);
}
});
}
});
save.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textAreaValue = ltext.getText();
filePath = fileName.getText();
try {
FileWriter fw = new FileWriter(filePath);
PrintWriter pw = new PrintWriter(fw);
pw.println(textAreaValue);
pw.close();
JOptionPane.showMessageDialog(panel, "File Written!", "Success!", JOptionPane.PLAIN_MESSAGE);
} catch (IOException x) {
JOptionPane.showMessageDialog(panel, "Error in writing file. \n\n Try Checking the file path or making sure the directory in which you are saving the file exists. \n\n Keep Calm and Love Beavers", "Error", JOptionPane.ERROR_MESSAGE);
}
}
});
help.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(panel, " ***The file name must be the full file path.***\n\n-=-=-=-=-=-=-=-=-=(MAC)=-=-=-=-=-=-=-=-=-\n\n Example: /Users/Cheese/Documents/FileName.txt\n\n\n-=-=-=-=-=-=-=-=(WINDOWS)=-=-=-=-=-=-=-=-\n\n *Note that 2 back slashes must be used* \n\nC:\\user\\docs\\example.txt", "Help", JOptionPane.PLAIN_MESSAGE);
}
});
panel.add(saveFilePath);
window.add(panel);
saveFilePath.setSize(20, 100);
window.setVisible(true);
}
public static void main(String[] args) {
new EventListeners();
}
}
You also may want to consider dependency injection. That is becoming the standard way of doing things in the industry. Instead of the constructor doing all the work of creating all the objects your class uses, or calling another method like window() to do all the work, you pass in all the specifications to the constructor. It might look something like
public EventListeners(JButton save, JButton help, JButton saveFilePath) {
this.save = save;
this.help = help;
this.saveFilePath = saveFilePath);
}
Of course, you could also use a dependency injection framework like Spring, but that might be a bit much if your application is small.
I was having an issue with an embedded applet I've been working on for a while now. The applet's jar is signed and all-permissions are granted, and it runs perfectly fine in the applet viewer. When loaded in the browser there is only a blank box with an error logo where my applet should be. When clicked it returns "java.lang.invocationtargetexception". I am using a basic HTML format to embed the applet.
Here is the HTML Code I am using to display it:
<html>
<body background="BG.png">
Back to the index
<center><h1>Web Forum</h1></center>
<center><table border = "0">
<tr>
<td><center><h3>Forums</h3></center></td>
<td width = 25></td>
<td width = 225><center><h3>Chatbox</h3></center></td>
</tr>
<tr>
<td><center><applet
code=Topics.class
archive=Topics.jar
width=750
height=1000 ><PARAM name="permissions" value="sandbox"></PARAM>
</applet></center></td>
<td width = 25></td>
<td width = 225 bgcolor = #00FF00><center><h3>Coming Soon</h3></center></td>
</tr>
</table></center>
</Body>
</Html>
And here is the Java console dump thread list:
Dump thread list ...
Group main,ac=19,agc=2,pri=10
main,5,alive
traceMsgQueueThread,5,alive,daemon
Timer-0,5,alive
AWT-Shutdown,5,alive
AWT-Windows,6,alive,daemon
Java Plug-In Pipe Worker Thread (Client-Side),5,alive,daemon
AWT-EventQueue-0,6,alive
SysExecutionTheadCreator,5,alive,daemon
MemoryCache-DelayedCleanup,5,alive,daemon
CacheMemoryCleanUpThread,5,alive,daemon
Browser Side Object Cleanup Thread,5,alive
JVM[id=1]-Heartbeat,5,alive,daemon
Group Plugin Thread Group,ac=4,agc=0,pri=10
AWT-EventQueue-1,6,alive
Image Fetcher 0,8,alive,daemon
TimerQueue,5,alive,daemon
SysExecutionThead,5,alive,daemon
Group http://25.2.202.42/-threadGroup,ac=4,agc=0,pri=4
Applet 1 LiveConnect Worker Thread,4,alive
AWT-EventQueue-2,4,alive
TimerQueue,4,alive,daemon
ConsoleTraceListener,4,alive,daemon
Done.
Here is the signed jar's manifest:
Manifest-Version: 1.0
Name: .classpath
SHA-256-Digest: IhqMeyTH+t/Wtxr+NP6B1f5GapLwQ67HJhYQ7UM+kA0=
Name: .project
SHA-256-Digest: Lw9C+yAb3p1vC6m2pwcjhv8TB1ET8xOYjM2sFlgIjIw=
Permissions: all-permissions
Codebase: http://25.2.202.42/
I see no reason the error would be resulting form my code itself, but here it is just incase:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.applet.*;
import java.io.*;
#SuppressWarnings("serial")
public class Topics extends Applet {
String name;
String topics;
String paragraphs;
//reading file for existing posts
String fileread = "Topics.txt";
static String line = null;
{
try {
FileReader fileReader =
new FileReader(fileread);
BufferedReader bufferedReader =
new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
bufferedReader.close();
}
catch(FileNotFoundException ex) {
System.out.println(
"Unable to open file '" +
fileread + "'");
}
catch(IOException ex1) {
System.out.println(
"Error reading file '"
+ fileread + "'");
}
}
static String display = line;
JPanel topicPanel;
JLabel title, username, topic, paragraph, topicsTitle, dtopicsTitle;
JTextField nameField, topicField;
JButton submitButton, topicrefreshButton;
JTextArea paragraphArea, topicArea;
public void init() {
final JPanel topicGUI = new JPanel();
topicGUI.setLayout(null);
setBackground(Color.GREEN);
setVisible(true);
// JLabels
JLabel title = new JLabel(" Make A Post ");
title.setSize(150, 25);
title.setFont(new Font("Serif", Font.PLAIN, 25));
title.setHorizontalAlignment(0);
add(title);
JLabel username = new JLabel("Username: ");
username.setSize(70, 15);
username.setHorizontalAlignment(0);
add(username);
// JTextField
nameField = new JTextField(8);
nameField.setSize(150, 18);
add(nameField);
// JLabel
JLabel topic = new JLabel("Topic: ");
topic.setSize(40, 15);
topic.setHorizontalAlignment(0);
add(topic);
// JTextField
topicField = new JTextField(8);
topicField.setSize(180, 18);
add(topicField);
//JLabel
JLabel paragraph = new JLabel(" Paragraph: ");
paragraph.setSize(70, 15);
paragraph.setHorizontalAlignment(0);
add(paragraph);
// JTextAreas
paragraphArea = new JTextArea(8, 5);
paragraphArea.setSize(700, 100);
paragraphArea.setLineWrap(true);
paragraphArea.setEditable(true);
add(paragraphArea);
// JButton
JButton submitButton = new JButton("SUBMIT");
submitButton.setSize(100, 30);
submitButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
name = nameField.getText();
topics = topicField.getText();
paragraphs = paragraphArea.getText();
display ="\n" + "\t" + name + " - " + "\n" + "\t" + topics + " : " + "\n" + paragraphs + display + "\n";
topicField.setText("");
paragraphArea.setText("");
//writing new info to file
String fileName = "Topics.txt";
try {
FileWriter fileWriter =
new FileWriter(fileName);
BufferedWriter bufferedWriter =
new BufferedWriter(fileWriter);
bufferedWriter.write(display);
bufferedWriter.close();
}
catch(IOException ex) {
System.out.println(
"Error writing to file '"
+ fileName + "'");
}
topicArea.setText(display);
}
});
add(submitButton);
JLabel dtopicsTitle = new JLabel(" Topics: ");
dtopicsTitle.setLocation(170, 3);
dtopicsTitle.setSize(150,30);
dtopicsTitle.setFont(new Font("Serif", Font.PLAIN, 25));
dtopicsTitle.setHorizontalAlignment(0);
add(dtopicsTitle);
topicrefreshButton = new JButton("Refresh Topics");
topicrefreshButton.setLocation(250, 30);
topicrefreshButton.setSize(100, 30);
topicrefreshButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
topicArea.setText(display);
}
});
add(topicrefreshButton);
topicArea = new JTextArea(40, 64);
topicArea.setSize(650, 430);
topicArea.setLineWrap(true);
topicArea.setEditable(false);
topicArea.setText(display);
add(topicArea);
JScrollPane topicScroll = new JScrollPane(topicArea);
topicScroll.setSize(650,430);
add(topicScroll);
}
}
Thank you for any support you can offer.
Applet and File mix like oil and water (i.e. 'not').
Not only would any File object not point where you expect (they point to the user's local file-system, rather than the server), but the applet would need to be digitally signed, and trusted, before it could use files.
Applets would typically access resources by URL. If the URL can be formed relative to the code base, document base, or class-path of the applet, it can remain sand-boxed and still work. Otherwise it will need to be trusted.
Other tips
Ensure the Java Console is configured to show for applets & JWS apps. If there is no output at the default level, raise it and try again.
Change code of the form catch (Exception e) { .. to catch (Exception e) { e.printStackTrace(); // very informative! ..
Java GUIs might have to work on a number of platforms, on different screen resolutions & using different PLAFs. As such they are not conducive to exact placement of components. To organize the components for a robust GUI, instead use layout managers, or combinations of them, along with layout padding & borders for white space.
Don't mix Swing components with AWT components. (Use JApplet instead of Applet.)
This code adds the user's favorited songs to a JmenuItem from an ArrayMap
public void actionPerformed(ActionEvent evt) {
String cmd = evt.getActionCommand();
if (cmd != null) {
if (cmd.equalsIgnoreCase("Favorite song")) {
Music.f.add(Music.s);
System.out.println(Music.s + " added to favorites");
System.out.println(Music.f + " current list");
}
}
}
public void initUI() {
try {
//...
JMenu fileMenu = new JMenu("Music And Sound Options");
JMenu favorites = new JMenu("Favorite songs");
for (String name : Music.f) {
JMenuItem menuItem = new JMenuItem(name);
menuItem.addActionListener(this);
favorites.add(menuItem);
}
JMenuBar menuBar = new JMenuBar();
JMenuBar jmenubar = new JMenuBar();
frame.add(jmenubar);
menuBar.add(favorites);
frame.getContentPane().add(menuBar, BorderLayout.NORTH);
frame.pack();
frame.setVisible(true); // can see the client
init();
//...
} catch (Exception e) { e.printStackTrace(); }
}
I want the list of songs to update after a song is added, instead of having to restart the client to see more songs
//JMenu favorites = new JMenu("Favorite songs");
favorites = new JMenu("Favorite songs");
The Favorites menu needs to be defined as a class variable. Then when you do this your ActionListener can now reference the menu and add a new menu item to the menu.
if (cmd.equalsIgnoreCase("Favorite song")) {
Music.f.add(Music.s);
System.out.println(Music.s + " added to favorites");
System.out.println(Music.f + " current list");
JMenuItem item = new JMenItem(...);
favorites.add( item );
If you store a reference to your JMenuBar as a class field, you can call menuBar.removeAll() and repopulate it with new menu items whenever you want (though make sure you do it on the Swing thread when you do, using SwingUtilities.invokeLater() or your Swing method of choice).
I have been using the "Learning Java 2nd Edtion" book to try make my java application write my input to a text file called properties. I have manipulated the text book example into my own code but still having problems trying to get it to work. I think i may need to hook it up to my submit button but this wasnt mentioned within the chapter.
Basically im trying to store the information in the text file and then use that text file within another location to read all of the property details.
Here is my code for the AddProperty Page so far any advice would be greatly appreciated.
At the moment iv hit the wall.
/**
*
* #author Graeme
*/
package Login;
import java.io.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.border.EmptyBorder;
public class AddProperty
{
public void AddProperty()
{
JFrame frame = new JFrame("AddPropertyFrame");
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// having to set sizes of components is rare, and often a sign
// of problems with layouts.
//frame.setSize(800,600);
JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20,20));
// make it big like the original
panel.setBorder(new EmptyBorder(100,20,100,20));
frame.add(panel);
//panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
JLabel HouseNumber = new JLabel("House Number/Name");
panel.add(HouseNumber);
JTextField HouseNumber1 = new JTextField(10);
panel.add(HouseNumber1);
JLabel HousePrice = new JLabel("House Price");
panel.add(HousePrice);
JTextField HousePrice1 = new JTextField(10);
panel.add(HousePrice1);
JLabel HouseType = new JLabel("House Type");
panel.add(HouseType);
JTextField HouseType1 = new JTextField(10);
panel.add(HouseType1);
JLabel Location = new JLabel("Location");
panel.add(Location);
JTextField Location1 = new JTextField(10);
panel.add(Location1);
JButton submit = new JButton("Submit");
panel.add(submit);
submit.addActionListener(new Action());
// tell the GUI to assume its natural (minimum) size.
frame.pack();
}
static class Action implements ActionListener{
#Override
public void actionPerformed (ActionEvent e)
{
// this should probably be a modal JDialog or JOptionPane.
JOptionPane.showMessageDialog(null, "You have successfully submitted a property.");
}
static class propertyList
{
public static void main (String args[]) throws Exception {
File properties = new File(args[0]);
if (!properties.exists() || !properties.canRead() ) {
System.out.println("Cant read " + properties);
return;
}
if (properties.isDirectory()){
String [] properties1 = properties.list();
for (int i=0; i< properties1.length; i++)
System.out.println();
}
else
try {
FileReader fr = new FileReader (properties);
BufferedReader in = new BufferedReader (fr);
String line;
while ((line = in.readLine())!= null)
System.out.println(line);
}
catch (FileNotFoundException e){
System.out.println("Not Able To Find File");
}
}
}
}
}
in your Action performed you are not stating anything, for example in your action performed you could add.
public void actionPerformed(ActionEvent e)
{
houseNumber2 = houseNumber1.getText();
housePrice2 = housePrice1.getText();
town1 = town.getText();
comboBoxType2 = comboBoxType1.getSelectedItem();
inputData = housenumber2 + "," + housePrice2 + "," + town1 + "," + comboBoxType2;
FileName.Filewritermethod(inputData);
frame.setVisible(false);
}
});
This would strings to take the values of your JTexFields and pass them onto a textfile provided you have a FileWriter Class
Your action listener is not doing anything much right now.
Add code to add property in the following method:
public void actionPerformed (ActionEvent e)
{
//add your code here
}