I am looking for a quick fix to this problem I have: Here is my code:
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JTextField;
public class Directory{
public static void main(String args[]) throws IOException{
JFrame frame = new JFrame("Directory");
frame.setPreferredSize(new Dimension(300,300));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JProgressBar searchprogress = new JProgressBar();
JPanel panel = new JPanel();
final JButton searchbutton = new JButton("Search");
final JTextField searchfield = new JTextField();
searchfield.setPreferredSize(new Dimension(100,30));
searchprogress.setPreferredSize(new Dimension(200, 30));
searchbutton.setLocation(100, 100);
/* Start Buffered Reader */
BufferedReader br = new BufferedReader(new FileReader("test1.txt"));
String housetype = br.readLine();
String housenumber = br.readLine();
String housestreet = br.readLine();
String housepostal = br.readLine();
String houseplace = br.readLine();
String seperation = br.readLine();
/* Finish Buffered Reader */
/* Start Content Code */
JButton done = new JButton("Done");
done.setVisible(false);
JLabel housetype_label = new JLabel();
JLabel housenumber_label = new JLabel();
JLabel housestreet_label = new JLabel();
JLabel housepostal_label = new JLabel();
JLabel houseplace_label = new JLabel();
/* Finish Content Code */
/* Start Button Code */
searchbutton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae)
{
String searchquery = searchfield.getText();
searchprogress.setValue(100);
searchfield.setEnabled(false);
if(searchquery.equals(housetype)){
System.out.println("We Have Found A Record!!");
}}
});
/* Finish Button Code */
/* Test Field */
/* End Test Field */
panel.add(searchfield);
panel.add(done);
panel.add(searchbutton);
panel.add(searchprogress);
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
}
Basically After I wrote this code, Eclipse told me I had to change the modifier of housetype, to final. Which truly won't do, because I need to be a changing value if its going to go trough different records.
PLEASE HELP ME! D:
You have several options here:
The quickest would be to do what Eclipse tells you, actually it is Java that tells you that. In order to be able to use method local variables inside inner classes inside the method, the variables must be final.
Another option is to declare the housetype variable as an instance variable, immediately after the class definition. But, using it in the static main method means that the variable needs to be static too, which makes it a class variable.
Another one would be to keep the code as you have, but declare an extra variable like below and then use the house variable inside the inner class instead of housetype. See the entire code below:
public class Directory {
public static void main(String args[]) throws IOException {
JFrame frame = new JFrame("Directory");
frame.setPreferredSize(new Dimension(300, 300));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JProgressBar searchprogress = new JProgressBar();
JPanel panel = new JPanel();
final JButton searchbutton = new JButton("Search");
final JTextField searchfield = new JTextField();
searchfield.setPreferredSize(new Dimension(100, 30));
searchprogress.setPreferredSize(new Dimension(200, 30));
searchbutton.setLocation(100, 100);
/* Start Buffered Reader */
final List<String> housetypes = new ArrayList<String>();
String line = "";
BufferedReader br = new BufferedReader(new FileReader("test1.txt"));
while (line != null) {
line = br.readLine();
housetypes.add(line);
String housenumber = br.readLine();
String housestreet = br.readLine();
String housepostal = br.readLine();
String houseplace = br.readLine();
String seperation = br.readLine();
}
/* Finish Buffered Reader */
/* Start Content Code */
JButton done = new JButton("Done");
done.setVisible(false);
JLabel housetype_label = new JLabel();
JLabel housenumber_label = new JLabel();
JLabel housestreet_label = new JLabel();
JLabel housepostal_label = new JLabel();
JLabel houseplace_label = new JLabel();
/* Finish Content Code */
/* Start Button Code */
searchbutton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
String searchquery = searchfield.getText();
searchprogress.setValue(100);
searchfield.setEnabled(false);
for (String housetype : housetypes) {
if (searchquery.equals(housetype)) {
System.out.println("We Have Found A Record!!");
}
}
}
});
/* Finish Button Code */
/* Test Field */
/* End Test Field */
panel.add(searchfield);
panel.add(done);
panel.add(searchbutton);
panel.add(searchprogress);
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
}
There are even more options, but these are the quickest.
One workaround is that you create a new method inside your class Directory that is being called from the ActionListener and does your tasks:
private void searchButtonAction() {
String searchquery = searchfield.getText();
searchprogress.setValue(100);
searchfield.setEnabled(false);
if(searchquery.equals(housetype)){
System.out.println("We Have Found A Record!!");
}
}
and then call it like this:
public void actionPerformed(ActionEvent ae)
{
searchButtonAction();
});
This only works if you create a constructor in the class and call it from the main method. Furthermore all variables used inside the searchButtonAction method must be class visible.
Full code:
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JTextField;
public class Directory {
private final JTextField searchfield = new JTextField();
private final JProgressBar searchprogress = new JProgressBar();
private String housetype;
public Directory() throws IOException {
JFrame frame = new JFrame("Directory");
frame.setPreferredSize(new Dimension(300, 300));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
final JButton searchbutton = new JButton("Search");
searchfield.setPreferredSize(new Dimension(100, 30));
searchprogress.setPreferredSize(new Dimension(200, 30));
searchbutton.setLocation(100, 100);
/* Start Buffered Reader */
BufferedReader br = new BufferedReader(new FileReader("test1.txt"));
housetype = br.readLine();
String housenumber = br.readLine();
String housestreet = br.readLine();
String housepostal = br.readLine();
String houseplace = br.readLine();
String seperation = br.readLine();
/* Finish Buffered Reader */
/* Start Content Code */
JButton done = new JButton("Done");
done.setVisible(false);
JLabel housetype_label = new JLabel();
JLabel housenumber_label = new JLabel();
JLabel housestreet_label = new JLabel();
JLabel housepostal_label = new JLabel();
JLabel houseplace_label = new JLabel();
/* Finish Content Code */
/* Start Button Code */
searchbutton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
searchButtonAction();
}
});
/* Finish Button Code */
/* Test Field */
/* End Test Field */
panel.add(searchfield);
panel.add(done);
panel.add(searchbutton);
panel.add(searchprogress);
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
private void searchButtonAction() {
String searchquery = searchfield.getText();
searchprogress.setValue(100);
searchfield.setEnabled(false);
if (searchquery.equals(housetype)) {
System.out.println("We Have Found A Record!!");
}
}
public static void main(String args[]) throws IOException {
new Directory();
}
}
Related
I am trying to make my program so that an integer value entered in a JTextfield can be stored into a variable. Then, when a JButton is clicked, this variable can tell a JSlider to move it's head to that of the integer value stored in the variable. My class name is Camera.Java
Code is showing no errors, however if I click my JButton, nothing happens, instead I see this error in the console:
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:504)
at java.lang.Integer.parseInt(Integer.java:527)
at Camera.main(Camera.java:67)
My code:
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Hashtable;
import java.util.Scanner;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JPanel;
import javax.swing.*;
public class Camera {
static JButton addtolist;
static Scanner input = new Scanner(System.in);
static JSlider cam = new JSlider();
static JTextField enterval = new JTextField();
static int x ;
public static void main (String args[]){
JFrame myFrame = new JFrame ("Matthew Damon on Mars");
myFrame.setSize(300, 600);
JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER));
JLabel userinp = new JLabel("Enter input: ");
cam = new JSlider(0, 15, 0);
cam.setPaintLabels(true);
enterval.setPreferredSize(new Dimension(100,80));
addtolist = new JButton("Enter");
addtolist.setPreferredSize(new Dimension(50,20));
JTextField enterval1 = new JTextField();
panel.add(addtolist);
Hashtable<Integer, JLabel> table = new Hashtable<Integer, JLabel>();
table.put(0, new JLabel("0"));
table.put(1, new JLabel("1"));
table.put(2, new JLabel("2"));
table.put(3, new JLabel("3"));
table.put(4, new JLabel("4"));
table.put(5, new JLabel("5"));
table.put(6, new JLabel("6"));
table.put(7, new JLabel("7"));
table.put(8, new JLabel("8"));
table.put(9, new JLabel("9"));
table.put(10, new JLabel("A"));
table.put(11, new JLabel("B"));
table.put(12, new JLabel("C"));
table.put(13, new JLabel("D"));
table.put(14, new JLabel("E"));
table.put(15, new JLabel("F"));
cam.setLabelTable(table);
myFrame.add(cam, BorderLayout.SOUTH);
myFrame.add(userinp, BorderLayout.NORTH);
myFrame.add(enterval1, BorderLayout.NORTH);
myFrame.add(panel, BorderLayout.CENTER);
myFrame.setVisible(true);
buttonAction();
}
public static void buttonAction() {
addtolist.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
int x = Integer.parseInt(enterval.getText());
cam.setValue(x);
} catch (NumberFormatException npe) {
// show a warning message
}
}
});
}
}
Your setting x on program creation before the user has had any chance to change its value. Get the text value from within the actionPerformed method which should be after the user has already selected a value, parse it into a number and set the slider with that value.
public void actionPerformed(ActionEvent e) {
try {
int x = Integer.parseInt(enterval.getText());
cam.setValue(x);
} catch (NumberFormatException npe) {
// show a warning message
}
}
Then get rid of all that static nonsense. The only method that should be static here is main, and it should do nothing but create an instance and set it visible.
Note that better than using a JTextField, use a JSpinner or a JFormattedTextField or if you're really stuck, a DocumentFilter to limit what the user can enter
Again, you should put most everything into the instance realm and out of the static realm. This means getting most of that code outside of the main method and into other methods and constructors, that means not trying to access fields or methods from the class, but rather from the instance. For instance, your main method should only create the main instances, hook them up and set them running and that's it. It should not be used to build the specific GUI components. For example:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import javax.swing.*;
#SuppressWarnings("serial")
public class CameraFoo extends JPanel {
// only static field here is a constant.
private static String TEXTS = "0123456789ABCDEF";
private JSpinner spinner = new JSpinner();
private JSlider slider = new JSlider(0, 15, 0);
public CameraFoo() {
List<Character> charList = new ArrayList<>();
Hashtable<Integer, JLabel> table = new Hashtable<>();
for (int i = 0; i < TEXTS.toCharArray().length; i++) {
char c = TEXTS.charAt(i);
String myText = String.valueOf(c);
JLabel label = new JLabel(myText);
table.put(i, label);
charList.add(c);
}
SpinnerListModel spinnerModel = new SpinnerListModel(charList);
spinner.setModel(spinnerModel);
slider.setLabelTable(table);
slider.setPaintLabels(true);
JPanel topPanel = new JPanel();
topPanel.add(spinner);
topPanel.add(new JButton(new ButtonAction("Press Me")));
setLayout(new BorderLayout());
add(topPanel, BorderLayout.PAGE_START);
add(slider);
}
private class ButtonAction extends AbstractAction {
public ButtonAction(String name) {
super(name);
}
#Override
public void actionPerformed(ActionEvent e) {
char ch = (char) spinner.getValue();
int value = TEXTS.indexOf(ch);
slider.setValue(value);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
createAndShowGui();
});
}
private static void createAndShowGui() {
CameraFoo mainPanel = new CameraFoo();
JFrame frame = new JFrame("CameraFoo");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
}
I'm trying to make a program which the user signs up and his information gets output to a file using simple text output?
Here is my whole class..
package malkawi.login;
import java.awt.BorderLayout;
import java.awt.ComponentOrientation;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.*;
import javax.swing.*;
import malkawi.login.JTextFieldLimit;
/**
*
* #author Defiledx1
* sign up
*/
public class SignUp extends JFrame implements EventListener {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
JButton complete = new JButton("Next");
JLabel fname = new JLabel("Name: ");
JLabel Mname = new JLabel("Middle Name: ");
JLabel Lname = new JLabel("Last Name: ");
JLabel user = new JLabel("Username: ");
JLabel pass = new JLabel("Password: ");
JLabel info = new JLabel("Click Next to Continue");
JLabel email = new JLabel("Email: ");
JLabel scode = new JLabel("Secret Code: ");
JTextField fname1 = new JTextField();
JTextField Mname1 = new JTextField();
JTextField Lname1 = new JTextField();
JTextField user1 = new JTextField();
JPasswordField pass1 = new JPasswordField();
JTextField email1 = new JTextField();
JTextField scode1 = new JTextField();
JRadioButton showPass = new JRadioButton("Show Pass");
public SignUp() {
super("Sign Up - Flare By Malkawi");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(600, 400);
setResizable(false);
setVisible(true);
setVisible(true);
setLayout(new GridLayout(0, 2, 10, 10));
setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
/*
* Limitations
*/
fname1.setDocument(new JTextFieldLimit(10));
Mname1.setDocument(new JTextFieldLimit(1));
Lname1.setDocument(new JTextFieldLimit(10));
user1.setDocument(new JTextFieldLimit(15));
email1.setDocument(new JTextFieldLimit(80));
scode1.setDocument(new JTextFieldLimit(5));
/*
* End Of Limitations
*/
/*
* RadioButton Checked : Unchecked
*/
showPass.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
showPassword(e.getStateChange() == 1 ? true : false);
}
});
/*
* End of RadioButton Checked : UnChecked
*/
/*
* Action of registration
*/
complete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
try {
outPutInformation();
} catch (FileNotFoundException | UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
System.out.println("Flare is unable at the moment!");
}
}
});
/*
* End of Action of registration
*/
// Dimension labelSize = info.getPreferredSize();
/*
* Start of placements
*/
//add(info);
add(fname);
add(fname1);
add(Mname);
add(Mname1);
add(Lname);
add(Lname1);
add(user);
add(user1);
add(pass);
add(pass1);
add(email);
add(email1);
add(scode);
add(scode1);
add(complete);
add(showPass);
add(info);
pack();
}
public void showPassword(boolean showP) {
if (showP == true) {
pass1.setEchoChar((char)0);
} else {
pass1.setEchoChar('*');
}
}
/*
* File Output Requirements
*/
String filename = user1.getText();
String firstname = fname1.getText();
String middlename = Mname1.getText();
String lastname = Lname1.getText();
String username = user1.getText();
#SuppressWarnings("deprecation")
String password = pass1.getText();
String hotmail = email1.getText();
String secretcode = scode1.getText();
/*
* File Output done
*/
public void outPutInformation() throws FileNotFoundException, UnsupportedEncodingException {
PrintWriter writer = new PrintWriter(filename+".txt", "UTF-8");
writer.println(firstname);
writer.println(middlename);
writer.println(lastname);
writer.println(username);
writer.println(password);
writer.println(hotmail);
writer.println(secretcode);
writer.close();
}
}
the problem is that it's not outputting anything out.
How is it possible to output the file like 2 folder behind
Thank you!
This is not outputting anything because your variables are initialized before entering anything in the text fields. you need to do like this, or directly write textfield values to the file instead if first saving to variables and then writing to file:
public void outPutInformation() throws FileNotFoundException, UnsupportedEncodingException {
String filename = user1.getText();
String firstname = fname1.getText();
String middlename = Mname1.getText();
String lastname = Lname1.getText();
String username = user1.getText();
#SuppressWarnings("deprecation")
String password = pass1.getText();
String hotmail = email1.getText();
String secretcode = scode1.getText();
PrintWriter writer = new PrintWriter(filename+".txt", "UTF-8");
writer.println(firstname);
writer.println(middlename);
writer.println(lastname);
writer.println(username);
writer.println(password);
writer.println(hotmail);
writer.println(secretcode);
writer.close();
}
I'm using some sample code from the Java website, and the file selector seems to get the file I want, but when I try to update the jframe and other components in the gui I used to call the file selector, nothing changes. I've tried quite a few of the suggested fixes to get things to update, but nothing seems to work. Most of my components are static by the way...
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.awt.event.*;
public class GuiTester extends JFrame {
private static String fileName = "Input File: Please select a file";
//Create a file chooser
private static final JFileChooser fc = new JFileChooser();
private static JButton inputSelectorButton;
private static JButton outputSelectorButton;
private static JFrame frame = new JFrame( "Gui Tester" );
private static JPanel panel = new JPanel();
private static JLabel inputFile = new JLabel( fileName );
public static void main(String[] args) {
go();
}
private static void go() {
inputSelectorButton = new JButton ( "Select Input File" );
outputSelectorButton = new JButton ( "Select Output File" );
Font bigFont = new Font( "sans", Font.BOLD, 22 );
Font smallFont = new Font( "sans", Font.PLAIN, 9 );
panel.setLayout(new BoxLayout( panel, BoxLayout.Y_AXIS ) );
JLabel description0 = new JLabel(" ");
JLabel description6 = new JLabel(" ");
JLabel inputFile = new JLabel( fileName );
inputFile.setFont( smallFont );
inputSelectorButton.addActionListener( new inputSelectorListener() );
JButton startButton = new JButton ( "GO!" );
panel.add(description0);
panel.add(description6);
panel.add( inputFile );
panel.add( inputSelectorButton );
panel.add( outputSelectorButton );
panel.add( startButton );
frame.getContentPane().add( BorderLayout.CENTER, panel );
inputFile.setAlignmentX(JComponent.CENTER_ALIGNMENT);
inputSelectorButton.setAlignmentX(JComponent.CENTER_ALIGNMENT);
outputSelectorButton.setAlignmentX(JComponent.CENTER_ALIGNMENT);
startButton.setAlignmentX(JComponent.CENTER_ALIGNMENT);
frame.setSize(370,400);
panel.setSize(370,400);
frame.setVisible(true);
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
public static class inputSelectorListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == inputSelectorButton) {
int returnVal = fc.showOpenDialog( panel );
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
if ( file.exists() )
fileName = file.getPath();
else
fileName = "File not found, please select a file";
System.out.println(fileName);
inputFile.setText( fileName );
inputFile.validate();
inputFile.repaint();
panel.validate();
panel.repaint();
frame.validate();
frame.repaint();
} else {
System.out.println("Open command cancelled by user.");
}
}
}
}
}
I do not see anywhere you add
inputFile
panel
To anything that is displayable.
You are also shadowing inputFile.
You create an static reference...
private static JLabel inputFile = new JLabel(fileName);
Then in go, you create a local reference...
JLabel inputFile = new JLabel(fileName);
This means that the reference you using in the actionPerformed method is not the same reference that is on the screen.
Do not rely on static to solve reference issues, this will bite you more quickly then you can realise...
You might like to take a look at:
Initial Threads
Code Conventions for the Java Programming Language
You should try to use classes and organize your code better. Below I have redesigned your existing code. I did not add anything, but I did move some stuff around and remove a couple unnecessary variables for this example.
I changed your ActionListener to an AbstractAction, just to let you know. :-p
import java.awt.Container;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.io.File;
import javax.swing.AbstractAction;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
#SuppressWarnings("serial")
public class GuiTester extends JPanel {
// Create a file chooser
private static final JFileChooser fc = new JFileChooser();
private JLabel inputFile;
public GuiTester(int width, int height) {
Font smallFont = new Font("sans", Font.PLAIN, 9);
JLabel description0 = new JLabel(" ");
JLabel description6 = new JLabel(" ");
JButton startButton = new JButton("Enter");
JButton inputSelectorButton = new JButton(new FileChooserAction(
"Select Input File"));
JButton outputSelectorButton = new JButton("Select Output File");
inputFile = new JLabel("Input File: Please select a file");
inputFile.setFont(smallFont);
inputFile.setAlignmentX(JComponent.CENTER_ALIGNMENT);
inputSelectorButton.setAlignmentX(JComponent.CENTER_ALIGNMENT);
outputSelectorButton.setAlignmentX(JComponent.CENTER_ALIGNMENT);
startButton.setAlignmentX(JComponent.CENTER_ALIGNMENT);
add(description0);
add(description6);
add(inputFile);
add(inputSelectorButton);
add(outputSelectorButton);
add(startButton);
setSize(width, height);
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
}
public JLabel getInputFileLabel() {
return inputFile;
}
#Override
public void invalidate() {
super.invalidate();
// Invalidate the label, you really don't need this, but you should
// reference children in here if you want to explicitly invalidate them
// when the parent gets invalidated. The parent is responsible for
// telling its children what to do and when to do it.
inputFile.invalidate();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// This gets called when you repaint, since you are adding children
// to this panel, painting is pointless. You can however fill the
// background if you wish.
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame f = new JFrame("Gui Test");
f.setContentPane(new GuiTester(370, 400));
f.setSize(370, 400);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLocationRelativeTo(null);
}
});
}
public class FileChooserAction extends AbstractAction {
public FileChooserAction(String name) {
super(name);
}
public void actionPerformed(ActionEvent e) {
Container c = ((JButton) e.getSource()).getParent();
GuiTester g = null;
if (c instanceof GuiTester) {
g = (GuiTester) c;
}
int returnVal = fc.showOpenDialog(c);
if (g != null && returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
String fileName = "Input File: Please select a file";
if (file.exists())
fileName = file.getPath();
else
fileName = "File not found, please select a file";
System.out.println(fileName);
g.getInputFileLabel().setText(fileName);
g.validate();
g.repaint();
} else {
System.out.println("Open command cancelled by user.");
}
}
}
}
I've searched through the forums but keep coming up empty for a solution.
I'm making a sort of library with a GUI program. What I want is for it to save entries via a text file. I can create objects fine with the methods I have, and can save them to a file easily. The problem comes from starting up the program again and populating a Vector with values in the text file. The objects I'm adding have a String value, followed by 7 booleans. When I try to load up from file, the String value is empty ("") and all booleans are false.
How do I get it to read the text before starting the rest of the GUI and filling the Vector right?
EDIT: Sorry for being very vague about it all. I'll post the code, but it's about 337 lines long..
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Collections;
import java.util.Scanner;
import java.util.Vector;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
#SuppressWarnings("serial")
public class SteamLibraryGUI extends JFrame implements ActionListener
{
//For main window
private JButton exitButton, addEntry, editEntry, removeEntry;
private JLabel selectGame, gameCount;
private JComboBox<String> gameCombo;
private Vector<Game> gamesList = new Vector<Game>();
private Vector<String> titleList = new Vector<String>();
private int numGames = gamesList.size();
private int selectedGame;
//For add window
private JFrame addFrame;
private JLabel gameTitle = new JLabel("Title:");
private JTextField titleText = new JTextField(60);
private JCheckBox singleBox, coopBox, multiBox, cloudBox, controllerBox, achieveBox, pcBox;
private JButton addGame, addCancel;
//For edit window
private JFrame editFrame;
private JButton editGame, editCancel;
public SteamLibraryGUI()
{
setTitle("Steam Library Organizer");
addEntry = new JButton("Add a game");
editEntry = new JButton("Edit a game");
removeEntry = new JButton("Remove a game");
exitButton = new JButton("Exit");
selectGame = new JLabel("Select a game:");
gameCount = new JLabel("Number of games:"+numGames);
gameCombo = new JComboBox<String>(titleList);
JPanel selectPanel = new JPanel();
selectPanel.setLayout(new GridLayout(1,2));
selectPanel.add(selectGame);
selectPanel.add(gameCombo);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(1,3));
buttonPanel.add(addEntry);
buttonPanel.add(editEntry);
buttonPanel.add(removeEntry);
JPanel exitPanel = new JPanel();
exitPanel.setLayout(new GridLayout(1,2));
exitPanel.add(gameCount);
exitPanel.add(exitButton);
Container pane = getContentPane();
pane.setLayout(new GridLayout(3,1));
pane.add(selectPanel);
pane.add(buttonPanel);
pane.add(exitPanel);
addEntry.addActionListener(this);
editEntry.addActionListener(this);
removeEntry.addActionListener(this);
exitButton.addActionListener(this);
gameCombo.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==addEntry)
addEntry();
if(e.getSource()==editEntry)
editEntry(gamesList.get(selectedGame));
if(e.getSource()==removeEntry)
{
removeEntry(selectedGame);
update();
}
if(e.getSource()==exitButton)
exitProg();
if(e.getSource()==gameCombo)
{
selectedGame = gameCombo.getSelectedIndex();
}
if(e.getSource()==singleBox)
singleBox.isSelected();
if(e.getSource()==coopBox)
coopBox.isSelected();
if(e.getSource()==multiBox)
multiBox.isSelected();
if(e.getSource()==cloudBox)
cloudBox.isSelected();
if(e.getSource()==controllerBox)
controllerBox.isSelected();
if(e.getSource()==achieveBox)
achieveBox.isSelected();
if(e.getSource()==pcBox)
pcBox.isSelected();
if(e.getSource()==addGame)
{
gamesList.add(new Game(titleText.getText(), singleBox.isSelected(), coopBox.isSelected(),
multiBox.isSelected(), cloudBox.isSelected(), controllerBox.isSelected(),
achieveBox.isSelected(), pcBox.isSelected()));
titleList.add(titleText.getText());
addFrame.dispose();
update();
}
if(e.getSource()==addCancel)
addFrame.dispose();
if(e.getSource()==editCancel)
editFrame.dispose();
if(e.getSource()==editGame)
{
gamesList.get(selectedGame).name = titleText.getText();
gamesList.get(selectedGame).single = singleBox.isSelected();
gamesList.get(selectedGame).coop = coopBox.isSelected();
gamesList.get(selectedGame).multi = multiBox.isSelected();
gamesList.get(selectedGame).cloud = cloudBox.isSelected();
gamesList.get(selectedGame).controller = controllerBox.isSelected();
gamesList.get(selectedGame).achieve = achieveBox.isSelected();
gamesList.get(selectedGame).pc = pcBox.isSelected();
titleList.remove(selectedGame);
titleList.add(titleText.getText());
editFrame.dispose();
update();
}
}
public void update()
{
Collections.sort(titleList);
Collections.sort(gamesList);
gameCombo.updateUI();
titleText.setText("");
gameCombo.setSelectedIndex(-1);
numGames = gamesList.size();
gameCount.setText("Number of games:"+numGames);
}
public void addEntry()
{
addFrame = new JFrame("Add Entry");
addFrame.setDefaultCloseOperation(EXIT_ON_CLOSE);
addFrame.getContentPane();
addFrame.setLayout(new GridLayout(3,1));
singleBox = new JCheckBox("Single-Player");
singleBox.setSelected(false);
coopBox = new JCheckBox("Coop");
coopBox.setSelected(false);
multiBox = new JCheckBox("MultiPlayer");
multiBox.setSelected(false);
cloudBox = new JCheckBox("Steam Cloud");
cloudBox.setSelected(false);
controllerBox = new JCheckBox("Controller Support");
controllerBox.setSelected(false);
achieveBox = new JCheckBox("Achievements");
achieveBox.setSelected(false);
pcBox = new JCheckBox("For New PC");
pcBox.setSelected(false);
addGame = new JButton("Add game");
addCancel = new JButton("Cancel");
JPanel titlePanel = new JPanel();
titlePanel.setLayout(new FlowLayout());
titlePanel.add(gameTitle);
titlePanel.add(titleText);
JPanel checkPanel = new JPanel();
checkPanel.setLayout(new FlowLayout());
checkPanel.add(singleBox);
checkPanel.add(coopBox);
checkPanel.add(multiBox);
checkPanel.add(cloudBox);
checkPanel.add(controllerBox);
checkPanel.add(achieveBox);
checkPanel.add(pcBox);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new FlowLayout());
buttonPanel.add(addGame);
buttonPanel.add(addCancel);
addFrame.add(titlePanel);
addFrame.add(checkPanel);
addFrame.add(buttonPanel);
singleBox.addActionListener(this);
coopBox.addActionListener(this);
multiBox.addActionListener(this);
cloudBox.addActionListener(this);
controllerBox.addActionListener(this);
achieveBox.addActionListener(this);
pcBox.addActionListener(this);
addGame.addActionListener(this);
addCancel.addActionListener(this);
addFrame.pack();
addFrame.setVisible(true);
}
public void editEntry(Game g)
{
editFrame = new JFrame("Edit Entry");
editFrame.setDefaultCloseOperation(EXIT_ON_CLOSE);
editFrame.getContentPane();
editFrame.setLayout(new GridLayout(3,1));
singleBox = new JCheckBox("Single-Player");
singleBox.setSelected(g.single);
coopBox = new JCheckBox("Coop");
coopBox.setSelected(g.coop);
multiBox = new JCheckBox("MultiPlayer");
multiBox.setSelected(g.multi);
cloudBox = new JCheckBox("Steam Cloud");
cloudBox.setSelected(g.cloud);
controllerBox = new JCheckBox("Controller Support");
controllerBox.setSelected(g.controller);
achieveBox = new JCheckBox("Achievements");
achieveBox.setSelected(g.achieve);
pcBox = new JCheckBox("For New PC");
pcBox.setSelected(g.pc);
editGame = new JButton("Edit game");
editCancel = new JButton("Cancel");
titleText.setText(g.name);
JPanel titlePanel = new JPanel();
titlePanel.setLayout(new FlowLayout());
titlePanel.add(gameTitle);
titlePanel.add(titleText);
JPanel checkPanel = new JPanel();
checkPanel.setLayout(new FlowLayout());
checkPanel.add(singleBox);
checkPanel.add(coopBox);
checkPanel.add(multiBox);
checkPanel.add(cloudBox);
checkPanel.add(controllerBox);
checkPanel.add(achieveBox);
checkPanel.add(pcBox);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new FlowLayout());
buttonPanel.add(editGame);
buttonPanel.add(editCancel);
editFrame.add(titlePanel);
editFrame.add(checkPanel);
editFrame.add(buttonPanel);
singleBox.addActionListener(this);
coopBox.addActionListener(this);
multiBox.addActionListener(this);
cloudBox.addActionListener(this);
controllerBox.addActionListener(this);
achieveBox.addActionListener(this);
pcBox.addActionListener(this);
editGame.addActionListener(this);
editCancel.addActionListener(this);
editFrame.pack();
editFrame.setVisible(true);
}
public void removeEntry(int g)
{
Object[] options = {"Yes, remove the game", "No, keep the game"};
int n = JOptionPane.showOptionDialog(null, "Are you sure you want to remove this game from the list?",
"Remove game?", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[1]);
if (n==0)
{
gamesList.remove(g);
titleList.remove(g);
}
}
public void exitProg()
{
try
{
PrintWriter out = new PrintWriter("games.txt");
out.flush();
for(int i=0;i<gamesList.size();i++)
{
out.print(gamesList.get(i).toString());
}
out.close();
}
catch (FileNotFoundException e) {}
System.exit(0);
}
public static void main(String[] args)
{
SteamLibraryGUI frame = new SteamLibraryGUI();
frame.pack();
frame.setSize(600,200);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Scanner in = new Scanner("games.txt");
while(in.hasNextLine())
{
String line = in.nextLine();
String[] options = line.split("|");
Game g = new Game(options[0],Boolean.getBoolean(options[1]),
Boolean.getBoolean(options[2]),Boolean.getBoolean(options[3]),
Boolean.getBoolean(options[4]),Boolean.getBoolean(options[5]),
Boolean.getBoolean(options[6]),Boolean.getBoolean(options[7]));
frame.gamesList.add(g);
frame.titleList.add(options[0]);
System.out.println(g.toString());
}
in.close();
}
}
There's also a Game class, but it's simply 1 String, and then 7 booleans.
There were two significant bugs in the code. First, Scanner was constructed with a string parameter (which means that the Scanner scanned the string, not the file named by the string). Second, the pipe character "|" is a regular expression metacharacter. That is important because line.split() splits on regular expressions. Thus, the "|" has to be escaped. The main() function works fine if it is written as follows (with debugging output code included to show that each step is working correctly):
public static void main(String[] args)
{
SteamLibraryGUI frame = new SteamLibraryGUI();
frame.pack();
frame.setSize(600,200);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
try
{
Scanner in = new Scanner(new File("games.txt"));
while(in.hasNextLine())
{
System.out.println("line = ");
String line = in.nextLine();
System.out.println(line);
String[] options = line.split("\\|");
System.out.println("Options = ");
for (String s : options)
{
System.out.println(s);
}
Game g = new Game(options[0],Boolean.getBoolean(options[1]),
Boolean.getBoolean(options[2]),Boolean.getBoolean(options[3]),
Boolean.getBoolean(options[4]),Boolean.getBoolean(options[5]),
Boolean.getBoolean(options[6]),Boolean.getBoolean(options[7]));
frame.gamesList.add(g);
frame.titleList.add(options[0]);
System.out.println(g.toString());
}
in.close();
} catch (IOException x)
{
System.err.println(x);
}
}
There is one other important Gotcha: The method exitProg() writes the "games.txt" file out again before the program finishes. This creates a problem if the file was read incorrectly in the first place because the wrong data will be written back to the file. During testing, this means that even when the reading code has been corrected, it will still read the erroneous data that was written from a previous test run.
My preference in this situation is would be to isolate all the reading and writing code for "game.txt" inside the Game class (which makes it easier to verify that the reading and writing formats are identical) and only write the code to write the data back out once I'd written and tested the reading code, which would avoid this Gotcha.
i have created a Java program to save MAC Addresses to an external File. Below is the code:
import java.io.*;
public class MAC{
public static void main(String[] args) throws IOException{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter the MAC Addres : ");
File file = new File("mac.txt");
FileWriter fstream = new FileWriter("mac.txt",true);
BufferedWriter out = new BufferedWriter(fstream);
out.write(in.readLine());
out.newLine();
out.close();
}
}
I have also created a Swing Application. I am done with the Front End, but now I can't save MAC address to a external file using swing.
In my ActionListener, I am getting the values, but I have no idea how to save the details to a external file.
I am able to print the ActionListener values to the screen, but I want it to be saved in the external file.
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import java.io.*;
public class TextForm extends JPanel {
private JTextField[] fields;
// Create a form with the specified labels, tooltips, and sizes.
public TextForm(String[] labels, int[] widths) {
super(new BorderLayout());
JPanel labelPanel = new JPanel(new GridLayout(labels.length, 1));
JPanel fieldPanel = new JPanel(new GridLayout(labels.length, 1));
add(labelPanel, BorderLayout.WEST);
add(fieldPanel, BorderLayout.CENTER);
fields = new JTextField[labels.length];
for (int i = 0; i < labels.length; i += 1) {
fields[i] = new JTextField();
if (i < widths.length)
fields[i].setColumns(widths[i]);
JLabel lab = new JLabel(labels[i], JLabel.RIGHT);
lab.setLabelFor(fields[i]);
labelPanel.add(lab);
JPanel p = new JPanel(new FlowLayout(FlowLayout.LEFT));
p.add(fields[i]);
fieldPanel.add(p);
}
}
public String getText(int i) {
return (fields[i].getText());
}
public static void main(String[] args) {
String[] labels = { "Enter MAC Address : "};
int[] widths = { 17 };
final TextForm form = new TextForm(labels, widths);
JButton submit = new JButton("Submit");
submit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println(form.getText(0));
}
});
JFrame f = new JFrame("Text Form Example");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(form, BorderLayout.NORTH);
JPanel p = new JPanel();
p.add(submit);
f.getContentPane().add(p, BorderLayout.SOUTH);
f.pack();
f.setVisible(true);
}
}
Thank you.
Copy the working method into the actionPerformed method and swap.
out.write(in.readLine());
For:
out.write(form.getText(0));
Then wrap the lot of it in a try/catch.