i am trying to implement GUI features to my java coding which i am trying out for the first time. But i tried a "Create Player Feature" in my code but it is not writing to file can someone help? thanks
private class createListener implements ActionListener{
public void actionPerformed(ActionEvent event){
JFrame frame = new JFrame("Create Player");
JPanel panel = new JPanel();
JPanel mainpanel = new JPanel();
JButton create;
JLabel welcome = new JLabel("Create Player");
JLabel name = new JLabel("Enter Player Name");
nameP = new JTextField();
JLabel pass = new JLabel("Enter Player Password");
password = new JTextField();
JLabel chips = new JLabel("Enter Player Chips");
chipsP = new JTextField();
buttonCreate = new JButton("Create Player");
setSize(400,350);
setLocation(500,280);
panel.setLayout(new GridLayout(0,1,10,10));
panel.add(name);
panel.add(nameP);
panel.add(pass);
panel.add(password);
panel.add(chips);
panel.add(chipsP);
panel.add(buttonCreate);
mainpanel.add(panel);
getContentPane().removeAll();
getContentPane().add(mainpanel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
buttonCreate.addActionListener(new createListener());
}
}
private class playerListener implements ActionListener{
public void actionPerformed(ActionEvent event){
String username = nameP.getText();
String userpass = password.getText();
String hasheduserP = Utility.getHash(userpass);
String userchip = chipsP.getText();
String userContent = username + "|" + hasheduserP + "|" + userchip;
File file = new File("players.dat");
try{
//adding of user details
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("players.dat", true)));
out.println(userContent);
out.close();
JOptionPane.showMessageDialog(null,"User Created");
} catch (IOException ex){
System.out.println("Error Writing to File");
}
}
}
The file related part of your code works without any problem.
Hint: Improve it like this:
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class SOPlayground {
public static void main(String[] args) throws Exception {
String userContent = "foo";
try {
try (PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("/tmp/players.dat", true)))) {
out.println(userContent);
}
} catch (IOException ex) {
System.err.println("Error Writing to File: " + ex.getMessage());
}
}
}
The content of /tmp/players.dat now is
foo
Related
I have a process to convert XML to CSV file. My converter code is working fine. However, I have created a UI window to get the input file and output file paths with a Convert Button to trigger conversion.
Now I want to add a Progress indicator when the conversion is taking place. I have come up with the simple solution to show a label on pane and change its Text when the conversion task is in progress.
But the label text is not changing. Here is the code. Appreciate your help.
`import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class InputGUI extends JFrame implements ActionListener {
JTextField xmlInputPath = new JTextField("C:\\InputFile.xml", 30);
JTextField csvOutputPath = new JTextField("C:\\OutputFile.csv", 30);
JTextField parentNode = new JTextField(20);
JButton convertButton = new JButton("Convert");
JLabel progressLabel = new JLabel("");
public InputGUI() {
super("XML to CSV Converter");
setBounds(400, 300, 500, 200);
setDefaultCloseOperation(EXIT_ON_CLOSE);
JPanel pane = new JPanel();
JLabel xmlInputLabel = new JLabel("XML Input File Path: ", SwingConstants.LEFT);
JLabel csvInputLabel = new JLabel("CSV Output File Path: ", SwingConstants.LEFT);
JLabel parentNodeName = new JLabel("Parent Node Tag: ", SwingConstants.LEFT);
parentNodeName.setHorizontalTextPosition(SwingConstants.LEFT);
pane.add(xmlInputLabel);
pane.add(xmlInputPath);
pane.add(csvInputLabel);
pane.add(csvOutputPath);
pane.add(parentNodeName);
pane.add(parentNode);
pane.add(convertButton);
pane.add(progressLabel);
convertButton.addActionListener(this);
add(pane);
setVisible(true);
}
private static void setLookAndFeel() {
try {
UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
setLookAndFeel();
new InputGUI();
}
#Override
public void actionPerformed(ActionEvent e) {
try {
progressLabel.setText("Converting...");
String inputPath = xmlInputPath.getText();
String outputPath = csvOutputPath.getText();
String elementTagName = parentNode.getText();
inputPath = inputPath.replace("\\", "\\\\");
outputPath = outputPath.replace("\\", "\\\\");
XmlToCsvFileUsingSTAX convert = new XmlToCsvFileUsingSTAX();
convert.xmlToCsvFileConverter(inputPath, outputPath, elementTagName);
Message msg = new Message();
progressLabel.setText("");
msg.successMessage();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}`
I've got an error while validating username and password in this Java Swing code:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.util.*;
public class LoginForm extends JFrame implements ActionListener {
private JButton login;
private JTextField name;
private JPasswordField pw;
private LoginForm() {
super("Log in");
login = new JButton("Log in");
name = new JTextField(20);
pw = new JPasswordField(20);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new BorderLayout());
JPanel fields = new JPanel(new BorderLayout());
fields.add(name, "North");
fields.add(new JScrollPane(), "Center");
fields.add(pw, "South");
add(fields, "Center");
add(new JPanel(), "South");
add(new JPanel(), "North");
JPanel j = new JPanel();
j.setSize(100, 400);
j.add(login);
//j.add(new JLabel("|\n|\n|-> Username"));
setSize(600, 400);
add(j, "West");
login.addActionListener(this);
setVisible(true);
}
public static void main(String[] args) {
new LoginForm();
}
public void actionPerformed(ActionEvent evt) {
if (evt.getSource() == login) {
if (!validUser(name.getText(), pw.getPassword())) JOptionPane.showMessageDialog(null, "This user not exists.\nFor create a user,\n edit 'database.lfrm' file."
, "Error!", JOptionPane.ERROR_MESSAGE);
else JOptionPane.showMessageDialog(null, "This user is valid! Congraulations!");
} else throw new RuntimeException("Event source isn't be a " + login.toString());
}
private static boolean validUser(String name, char[] pwd) {
boolean res = false;
try {
BufferedReader br = new BufferedReader(new FileReader("database.lfrm"));
String all = "", lines[], user[], line;
while ((line = br.readLine()) != null) all += line;
lines = all.split("\n");
user = Arrays.asList(lines).get(Arrays.asList(lines).indexOf(name + " $ " + new String(pwd))).split(" $ ");
if (user == new String[]{name, new String(pwd)}) res = true;
} catch (IOException e) {e.printStackTrace();}
return res;
}
}
I compiled and run this code, and I had this "error":
"
This user not exists.
For create a user, edit 'database.lfrm' file.
"
My 'database.lfrm' file is likes this:
"
JavaUser $ adimn
"
I guess the problem is here:
if (user == new String[]{name, new String(pwd)}) res = true;
When you do this, you are checking if "user" and the String[] element are the same object, which is not true, because the String[] element is a different object you are creating just for this validation.
What you want to check is if the contents of the "user" array and the next array are the same, which you can solve replacing this line by:
if (Arrays.equals(user, new String[] {name, new String(pwd)})) res = true;
How do I add,remove and search for items in an arraylist when using GUI? I would like to add user input into the programs arraylist.
Also how do I CHECK TO SEE IF A FILE CALLED INFO.TXT EXISTS -- IF IT DOES -- SET ALL INFO IN info.txt FILE INTO TEXTAREA -- See below:
import java.awt.*;
import java.awt.event.*;
import java.io.BufferedWriter;
import java.io.FileWriter;
import javax.swing.*;
import java.io.File;
import java.io.*;
import static java.lang.System.out;
public class FinalMainFrame extends
JFrame {
BufferedReader br = null;
private Container pane;
private JTextField textField;
public FinalMainFrame() {
pane=getContentPane();
pane.setLayout(null);
JMenuBar menuBar = new JMenuBar();
JMenu menuFile = new JMenu();
JMenuItem menuFileExit = new
JMenuItem();
menuFile.setText("File");
menuFileExit.setText("Exit");
menuFileExit.addActionListener
( (ActionEvent e) -> {
FinalMainFrame.this.windowClosed();
});
menuFile.add(menuFileExit);
menuBar.add(menuFile);
setTitle("Final Project...");
setJMenuBar(menuBar);
setSize(new Dimension(250, 200));
JLabel label = new JLabel("Enter Info:");
label.setFont(new Font("Serif",
Font.PLAIN, 18));
pane.add(label);
label.setLocation(0, 10);
label.setSize(100, 30);
textField = new JTextField(20);
pane.add(textField);
textField.setSize(100, 30);
textField.setLocation(120, 10);
JButton button1 = new JButton("Save");
pane.add(button1);
button1.setLocation(30, 70);
button1.setSize(150, 50);
button1.addActionListener
(
new ActionListener() {
public void
actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(
null,"You pressed: " +
e.getActionCommand() );
try{
FileReader read = new
FileReader("info.txt");
BufferedReader br = new
BufferedReader(read);
String txt = "";
String line = br.readLine();
while (line != null){
txt += line;
line = br.readLine();
out.println(line);
}
String text = textField.getText();
FileWriter stream = new
FileWriter("info.txt");
try (BufferedWriter out = new
BufferedWriter(stream)) {
out.write(text);
}
JOptionPane.showMessageDialog(
null,"You entered: " + text );
}
catch (Exception ex) {}
}
}
);
this.addWindowListener
(
new WindowAdapter() {
public void
windowClosing(WindowEvent e) {
FinalMainFrame.this.windowClosed();
}
}
);
}
protected void windowClosed() {
System.exit(0);
}
}
When talking about GUI you should think of events. So add user input to your arraylist on a click event or etc.
So I wrote the following code:
package myProject;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.PrintWriter;
import java.util.Scanner;
import javax.swing.*;
public class GuiTest extends JFrame{
/**
*
*/
private static final long serialVersionUID = 1L;
JTextField user = new JTextField();
JTextField pass = new JTextField();
JLabel title = new JLabel("Login");
JLabel usernameGui = new JLabel("Username:");
JLabel passwordGui = new JLabel("Password:");
public String userName;
public String passWord;
//Non GUI variables
public String username;
public String password;
File dir = new File("C:\\Users\\User\\Desktop\\account1.txt");
public boolean pressed = false;
public GuiTest(){
JFrame window = new JFrame("Position");
//window.setSize(600, 600);
window.setBounds(500,200,600,600);
window.setResizable(false);
window.setVisible(true);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(null);
window.add(panel);
//Labels
panel.add(title);
title.setBounds(290, 110, 100, 100);
panel.add(usernameGui);
usernameGui.setBounds(150,200,150,30);
panel.add(passwordGui);
passwordGui.setBounds(150,240,150,30);
//Text fields
panel.add(user);
user.setBounds(230,240,150,30);
panel.add(pass);
pass.setBounds(230,200,150,30);
//Button
JButton btn = new JButton("Login");
btn.setBounds(250, 290, 100, 30);
panel.add(btn);
btn.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
userName = user.getText();
passWord = pass.getText();
pressed = true;
System.out.println(passWord+" "+password+" "+userName+" "+username);
//System.out.println(mn.passWord+" "+mn.password+" "+mn.userName+" "+mn.username);
}
});
}
public static void main(String[] args){
GuiTest test = new GuiTest();
GuiTest mn = new GuiTest();
try{
mn.Write("MyUser", "MyPass");
Scanner scan = new Scanner(mn.dir);
String text = scan.nextLine();
scan.close();
System.out.println(text);
String[] sep = text.split(" ");
mn.username = sep[0];
mn.password = sep[1];
System.out.println("User: " + mn.username + " pass: " + mn.password);
}catch(Exception e){
System.out.println("Error! File didn't create.");
}
Scanner usernameIn = new Scanner(System.in);
Scanner passwordIn = new Scanner(System.in);
String userIn = usernameIn.nextLine();
String passIn = passwordIn.nextLine();
if(mn.userName.equals(mn.username) && mn.passWord.equals(mn.password)){
System.out.print("Access Granted");
}else{
System.out.println("Access Denied");
System.out.println(mn.passWord+" "+mn.password+" "+mn.userName+" "+mn.username);
}
}
public void Write(String user, String pass){
String userONE = user;
String passONE = pass;
try{
PrintWriter file = new PrintWriter(dir);
file.print(userONE+" "+passONE);
file.close();
}catch(Exception e){
System.out.println("Error! File didn't create.");
}
}
}
When I run it two windows pop up (instead of 1) and I cant test the input as both of them somehow use the variables i guess. Does anyone know how to fix it?
Thanks in advance.
When I run it two windows pop up (instead of 1)
Since you are creating two objects of same class.
GuiTest test = new GuiTest();
GuiTest mn = new GuiTest();
Just remove one of them GuiTest test = new GuiTest();. Since you are not using test object.
I have created a program where I can input data in JTextField and on hitting save button I use a JFileChooser to save the data in a .txt file where each JTextField is in a new line. I also created a button that pops up a JFileChooser to browse for that file and populate its corresponding cells.
I am new to GUIs, the code I wrote is not working. I tried different variations and cannot seem to get it. Can someone point me in the right direction please.
The input is
john
Doe
st. Jude
100
Here is the code
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.table.DefaultTableModel;
import java.util.Scanner
import java.util.Vector;
import java.awt.event.*;
import java.awt.*;
import java.text.DecimalFormat;
import java.io.*;
//import javax.swing.filechooser;
import javax.swing.filechooser.FileFilter;
public class Charity
{
#SuppressWarnings("deprecation")
public static void main(String[] args)
{
JFrame frame = new JFrame("Learning Team Charity Program");
Container cp = frame.getContentPane();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Charities
final String[] charityArray = {"St.Jude", "CHOC", "Cancer Research", "AIDs Foundation", "Crohns Foundation"};
final JComboBox selector = new JComboBox(charityArray);
JPanel first = new JPanel();
first.setLayout(new FlowLayout());
first.add(selector);
// User input JLabels and JTextFields
JLabel nameLabel = new JLabel("First Name: ");
final JTextField name = new JTextField();
JLabel lastLabel = new JLabel("Last Name: ");
final JTextField lastname = new JTextField();
JLabel donationAmount = new JLabel("Donation Amount: ");
final JTextField donation = new JTextField();
JPanel second = new JPanel();
second.setLayout(new GridLayout(4,2));
second.add(nameLabel); second.add(name);
second.add(lastLabel); second.add(lastname);
second.add(donationAmount); second.add(donation);
// Donate & Exit Buttons
JButton donateButton = new JButton("Donate");
JButton saveButton = new JButton("Save");
JButton exitButton = new JButton("Exit");
JButton openButton= new JButton("Open File");
JPanel third = new JPanel();
third.setLayout(new FlowLayout());
third.add(donateButton);
third.add(saveButton);
third.add(openButton);
third.add(exitButton);
// JTable display
final DefaultTableModel model = new DefaultTableModel();
JTable table = new JTable(model);
model.addColumn("First Name");
model.addColumn("Last Name");
model.addColumn("Charity");
model.addColumn("Donation");
table.setShowHorizontalLines(true);
table.setRowSelectionAllowed(true);
table.setColumnSelectionAllowed(true);
JScrollPane scrollPane = JTable.createScrollPaneForTable(table);
JPanel fourth = new JPanel();
fourth.setLayout(new BorderLayout());
fourth.add(scrollPane, BorderLayout.CENTER);
// Button Events
exitButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.exit(1);
}
});
openButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e){
JFileChooser openChooser = new JFileChooser();
int openStatus = openChooser.showOpenDialog(null);
if(openStatus == JFileChooser.APPROVE_OPTION){
try{
File myFile = openChooser.getSelectedFile();
BufferedReader br = new BufferedReader(new FileReader(myFile));
String line;
while((line = br.readLine())!= null){
model.addRow(line.split(","));
}//end while
br.close();
}//end try
catch(Exception e2){
JOptionPane.showMessageDialog(null, "Buffer Reader Error");
}//end catch
}
}
private void setValueAt(String line, int row, int col) {
// TODO Auto-generated method stub
}
});
saveButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e){
JFileChooser fileChooser = new JFileChooser();
int status = fileChooser.showSaveDialog(null);
if (status == JFileChooser.APPROVE_OPTION)
{
fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("Text", ".txt", "txt"));
//fileChooser.setFileFilter(new FileFilter("txt"));
PrintWriter output;
try {
File file = fileChooser.getSelectedFile();
output = new PrintWriter(file +".txt");
for(int row = 0; row<table.getRowCount(); row++){
for(int col = 0; col<table.getColumnCount();col++){
output.println(table.getValueAt(row, col).toString());
}
output.println();
}
output.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
});
donateButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
DecimalFormat df = new DecimalFormat("##,###.00");
try
{
Object[] rows = new Object[]{name.getText(), lastname.getText(), selector.getSelectedItem(),
donation.getText()};
model.addRow(rows);
name.setText("");
lastname.setText("");
donation.setText("");
}
catch (Exception ex)
{
JOptionPane.showMessageDialog(null, "Enter a Dollar Amount", "Alert", JOptionPane.ERROR_MESSAGE);
return;
}
}
});
// Frame Settings
frame.setSize(470,300);
//frame.setLocation(300,200);
cp.setLayout(new BoxLayout(cp, BoxLayout.Y_AXIS));
cp.add(first);
cp.add(second);
cp.add(third);
cp.add(fourth);
frame.setVisible(true);
}
}
I understand I have to pass a value in the parenthesis after the addRow.
People don't know what that means because the code you posted here doesn't have an addRow(...) method.
I see you posted a second question 2 hours later: https://stackoverflow.com/questions/30951407/how-to-properly-read-a-txt-file-into-a-a-row-of-a-jtable.
Keep all the comments in one place so people understand what is going on.
Also, posting a few random lines of code doesn't help us because we don't know the context of how the code is used. For example, I have no idea what how you created the "model" variable. I don't know if you ever added the model to the table.
Post a proper SSCCE when posting a question so we have the necessary information. The file chooser is irrelevant to the problem because we don't have access to your real file. So instead you need to post hard coded data. An easy way to do this is to use a StringReader.
Here is a working example that shows how to read/parse/load a file into a JTable:
import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;
import java.io.*;
public class SSCCE extends JPanel
{
public SSCCE()
{
try
{
DefaultTableModel model = new DefaultTableModel(0, 4);
String data = "1 2 3 4\na b c d\none two three four";
BufferedReader br = new BufferedReader( new StringReader( data ) );
String line;
while ((line = br.readLine()) != null)
{
String[] split = line.split(" ");
model.addRow( split );
}
JTable table = new JTable(model);
add( new JScrollPane(table) );
}
catch (IOException e) { System.out.println(e); }
}
private static void createAndShowGUI()
{
JFrame frame = new JFrame("SSCCE");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new SSCCE());
frame.setLocationByPlatform( true );
frame.pack();
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
}
}
All you need to do is change the code to use a FileReader instead of the StringReader.
I figured it out. Thanks for all those that tried to help.
openButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e){
JFileChooser openChooser = new JFileChooser();
int openStatus = openChooser.showOpenDialog(null);
if(openStatus == JFileChooser.APPROVE_OPTION){
try{
File myFile = openChooser.getSelectedFile();
//BufferedReader br = new BufferedReader(new FileReader(myFile));
Scanner br = new Scanner(new FileReader(myFile));
String line;
while((line = br.nextLine())!= null){
Object[] myRow = new Object[]{line,br.nextLine(), br.nextLine(), br.nextLine()};
model.addRow(myRow);
// line = br.readLine();
if(br.nextLine()== " "){
line=br.nextLine();
}
}//end while
br.close();
}//end try
catch(Exception e2){
return;
}//end catch
}
}
});