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.");
}
}
}
}
Related
This question already has answers here:
What is the best way to save user settings in java application?
(3 answers)
Closed 2 years ago.
I am trying to save the last chosen file (by the user using JFilechooser) so that the next time the program runs, the file will be automatically opened.
public void actionPerformed(ActionEvent evt) {
JFileChooser fileopen = new JFileChooser();
FileFilter filter = new FileNameExtensionFilter("xml files", "xml");
fileopen.addChoosableFileFilter(filter);
int ret = fileopen.showDialog(null, "Open file");
if (ret == JFileChooser.APPROVE_OPTION) {
File file = fileopen.getSelectedFile();
xmlSetUp(file);
//add save file for next use
}
}
Only the accepted answer to the duplicate question mentions the Java Preferences API, but it doesn't contain any example code. The below code displays a JFrame that contains a JTextField that displays the path to the selected file as well as a JButton. When you activate the JButton, it displays a JFileChooser. Once you select a file, that selection is saved as a [java] preference. The next time you run the same application, the JTextField will initially display the path that was saved in the preferences.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.File;
import java.util.prefs.Preferences;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Remember implements ActionListener, Runnable {
private static final String CHOOSE = "Choose";
private static final String LAST_FILE_CHOSEN = "LAST_FILE_CHOSEN";
private JFrame frame;
private JTextField textField;
private String savedFile;
#Override
public void actionPerformed(ActionEvent event) {
String actionCommand = event.getActionCommand();
switch (actionCommand) {
case CHOOSE:
selectFile();
break;
default:
JOptionPane.showMessageDialog(frame,
actionCommand,
"UNHANDLED",
JOptionPane.WARNING_MESSAGE);
}
}
#Override
public void run() {
showGui();
}
private JButton createButton(String text, int mnemonic, String tooltip) {
JButton button = new JButton(text);
button.setMnemonic(mnemonic);
button.addActionListener(this);
return button;
}
private JPanel createButtonsPanel() {
JPanel buttonsPanel = new JPanel();
buttonsPanel.add(createButton(CHOOSE, KeyEvent.VK_C, "Select file."));
return buttonsPanel;
}
private JPanel createTopPanel() {
JPanel topPanel = new JPanel();
JLabel label = new JLabel("Selected File");
topPanel.add(label);
textField = new JTextField(20);
Preferences prefs = Preferences.userNodeForPackage(getClass());
savedFile = prefs.get(LAST_FILE_CHOSEN, "");
textField.setText(savedFile);
topPanel.add(textField);
return topPanel;
}
private void selectFile() {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
File initial = new File(savedFile);
if (initial.exists()) {
fileChooser.setCurrentDirectory(initial.getParentFile());
}
if (fileChooser.showOpenDialog(frame) == JFileChooser.APPROVE_OPTION) {
File f = fileChooser.getSelectedFile();
String path = f.getAbsolutePath();
textField.setText(path);
if (!savedFile.equals(path)) {
Preferences prefs = Preferences.userNodeForPackage(getClass());
prefs.put(LAST_FILE_CHOSEN, path);
}
}
}
private void showGui() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createTopPanel(), BorderLayout.PAGE_START);
frame.add(createButtonsPanel(), BorderLayout.PAGE_END);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Remember());
}
}
I am working a side project that involves the user entering a file. I know there is the option for them to enter a string representing the text files name and then have the computer search for it but that would mean the file has to be in a certain location on the computer or the user has to enter the whole pathway to the file.
Is there anything similar to file input tag in HTML5 that prompts a window that allows the user to search through their laptop for the file? I've attached a picture of what I mean would be prompted on a mac.
Use file chooser by swing
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class FileChooserTest extends JFrame {
private JTextField filename = new JTextField(), dir = new JTextField();
private JButton open = new JButton("Open"), save = new JButton("Save");
public FileChooserTest() {
JPanel p = new JPanel();
open.addActionListener(new OpenL());
p.add(open);
save.addActionListener(new SaveL());
p.add(save);
Container cp = getContentPane();
cp.add(p, BorderLayout.SOUTH);
dir.setEditable(false);
filename.setEditable(false);
p = new JPanel();
p.setLayout(new GridLayout(2, 1));
p.add(filename);
p.add(dir);
cp.add(p, BorderLayout.NORTH);
}
class OpenL implements ActionListener {
public void actionPerformed(ActionEvent e) {
JFileChooser c = new JFileChooser();
// Demonstrate "Open" dialog:
int rVal = c.showOpenDialog(FileChooserTest.this);
if (rVal == JFileChooser.APPROVE_OPTION) {
filename.setText(c.getSelectedFile().getName());
dir.setText(c.getCurrentDirectory().toString());
}
if (rVal == JFileChooser.CANCEL_OPTION) {
filename.setText("You pressed cancel");
dir.setText("");
}
}
}
class SaveL implements ActionListener {
public void actionPerformed(ActionEvent e) {
JFileChooser c = new JFileChooser();
// Demonstrate "Save" dialog:
int rVal = c.showSaveDialog(FileChooserTest.this);
if (rVal == JFileChooser.APPROVE_OPTION) {
filename.setText(c.getSelectedFile().getName());
dir.setText(c.getCurrentDirectory().toString());
}
if (rVal == JFileChooser.CANCEL_OPTION) {
filename.setText("You pressed cancel");
dir.setText("");
}
}
}
public static void main(String[] args) {
run(new FileChooserTest(), 250, 110);
}
public static void run(JFrame frame, int width, int height) {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(width, height);
frame.setVisible(true);
}
} ///:~
File dialog
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 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();
}
}
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.