Currently, I learn Java guI, swing.
I would like to link the j1('open' button) in Yam class with a Open_Button Class's function.
If I write a file name in "textField" which is a global variable in Yam class, and press the 'open', the "TextArea" has to show an output the opened file's content.
but somehow it doesn't work. I think the open_button class's function is not connected with the "textField" in Yam class.
But I really can't find what's wrong.
(sorry for my poor Engish..;( i'll show you full code. I want to follow Minimal, Complete, and Verifiable rull but I really don't know where is wrong part..)
Yam class )
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.File.*;
import java.io.*;
import java.nio.file.*;
public class Yam extends JFrame {
Container contentPane;
JButton j1, j2, j3, j4, j5, j6;
JTextField textField;
JTextField textField_1;
TextArea textArea, textArea_1;
public Yam() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
contentPane = getContentPane();
contentPane.setLayout(null);
textField = new JTextField();
textField.setBounds(14, 12, 240, 24);
contentPane.add(textField);
textField.setColumns(20);
j1 = new JButton("Open");
j1.setBounds(294, 11, 105, 27);
j1.addActionListener(new AB());
contentPane.add(j1);
textField_1 = new JTextField();
textField_1.setBounds(14, 48, 240, 24);
contentPane.add(textField_1);
textField_1.setColumns(20);
j2 = new JButton("Save");
j2.setBounds(294, 47, 105, 27);
contentPane.add(j2);
textArea = new TextArea();
textArea.setBounds(10, 105, 405, 190);
contentPane.add(textArea);
j3 = new JButton("Compile");
j3.setBounds(10, 319, 87, 25);
j3.addActionListener(new AB());
contentPane.add(j3);
j4 = new JButton("Save Errors");
j4.setBounds(111, 319, 87, 25);
contentPane.add(j4);
j5 = new JButton("Delete");
j5.setBounds(217, 319, 87, 25);
contentPane.add(j5);
j6 = new JButton("Clear");
j6.setBounds(321, 319, 87, 25);
j6.addActionListener(new AB());
contentPane.add(j6);
textArea_1 = new TextArea();
textArea_1.setBounds(10, 391, 405, 253);
contentPane.add(textArea_1);
setSize(506, 698);
setVisible(true); }
class AB implements ActionListener {
private TextArea args;
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
CmdClass cmd = new CmdClass();
Open_button open = new Open_button();
JFrame f = new JFrame("what");
if(source == j1) {
}
else if(source == j2) {
}
else if(source == j3) {
if(cmd.main(args))
textArea_1.append("Compile Success\n");
}
else if(source == j4) { }
else if(source == j5) { }
else {
textField.setText(" ");
textField_1.setText(" ");
textArea.setText(" ");
textArea_1.setText(" "); }}}
public static void main(String[] args) {
new Yam();
}
public static String getFileName() {
// TODO Auto-generated method stub
return null;}}
Open_button class)
import java.io.*;
import java.nio.file.*;
import java.io.File;
public class Open_button {
Path Path;
public void main(String Str_paths){
Yam y = new Yam();
Str_paths = y.textField.getText();
Path = FileSystems.getDefault().getPath(Str_paths);
File file = Path.toFile();
if(Path.toFile() != null)
y.textArea.append("file exist!");
else {
y.textArea_1.append("file not exist");
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(Str_paths));
String line;
while ((line = br.readLine()) != null) {
y.textArea.append(line);
}
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e2) {
e2.printStackTrace();
}
}
}
}
I think you want for some reason to open and read a file which the filepath is designated on the jtextfield; Simplest way would be:
JButton openButton = new JButton("Open File");
openButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String thePath = textfield.getText();
File theFile = new File(thePath);
...read..write..
}
});
I would declare this directly on the Yam class;
From what I have seen, your code has two issues: first, there are two Yam (y) instances (the one declared in OpenButton class is different than the one located above) and, second, you assume that the file is readable and always located on Filesystem view...I think you should also consider a JFileChooser dialog.
Regards, André
Related
I am trying to add a "profile picture" to a user's profile page. Basically, I have it to where they can select a file from their computer and upload it to the application, and it will display their profile picture. However it is not working, I think that it currently cannot display it, but generates it incorrectly.
Here is my code
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.ObjectInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import javax.swing.JFileChooser;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
class createProfilePage extends JFrame implements ActionListener {
Container container = getContentPane();
JLabel name = new JLabel("Name: ");
JTextField nameField = new JTextField();
JLabel age = new JLabel("Age: ");
JTextField ageField = new JTextField();
JLabel interest = new JLabel("Interests: ");
JTextField interestField = new JTextField();
JLabel aboutMe = new JLabel("About me: ");
JTextField aboutMeField = new JTextField();
JLabel phoneNum = new JLabel("Phone Number: ");
JTextField phoneNumberField = new JTextField();
JButton submit = new JButton("Save Profile");
JButton deleteProfile = new JButton("Delete Profile");
JButton uploadPic = new JButton("Upload Profile Picture");
createProfilePage()
{
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
//setting container
setLayoutManager();
setLocationAndSize();
addComponents();
addActionEvent();
setTitle("Welcome");
setSize(600, 500);
}
public void setLayoutManager() {
container.setLayout(null);
}
public void setLocationAndSize()
{
//Setting location and Size of each components using setBounds() method.
name.setBounds(50,100,100,30);
age.setBounds(50,170,100,30);
phoneNum.setBounds(50,240,100,30);
interest.setBounds(50,310,100,30);
aboutMe.setBounds(50,380,100,30);
submit.setBounds(350, 240, 150, 30);
deleteProfile.setBounds(350,310,150,30);
uploadPic.setBounds(350,380,150,30);
nameField.setBounds(150,100,150,30);
ageField.setBounds(150,170,150,30);
phoneNumberField.setBounds(150,240,150,30);
interestField.setBounds(150,310,150,30);
aboutMeField.setBounds(150,380,150,30);
}
public void addComponents() {
container.add(name);
container.add(age);
container.add(phoneNum);
container.add(interest);
container.add(aboutMe);
container.add(nameField);
container.add(ageField);
container.add(phoneNumberField);
container.add(interestField);
container.add(aboutMeField);
container.add(submit);
container.add(deleteProfile);
container.add(uploadPic);
}
public void addActionEvent() {
submit.addActionListener(this);
deleteProfile.addActionListener(this);
uploadPic.addActionListener(this);
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == submit) {
String name = nameField.getText();
String age = ageField.getText();
String phoneNum = phoneNumberField.getText();
String interest = interestField.getText();
String aboutMe = aboutMeField.getText();
try {
Socket socket = new Socket("localhost", 4242);
ObjectInputStream reader = new ObjectInputStream(socket.getInputStream());
//creating user object to send to the server
User user = new User();
} catch (IOException b) {
b.printStackTrace();
}
JOptionPane.showMessageDialog(this, "Profile Creation Successful");
} else if (e.getSource() == deleteProfile) {
String name = null;
String age = null;
String phoneNum = null;
String interest = null;
String aboutMe = null;
JOptionPane.showMessageDialog(this, "Profile Deletion Successful");
} else if (e.getSource() == uploadPic) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));
int result = fileChooser.showOpenDialog(getParent());
if (result == JFileChooser.APPROVE_OPTION) {
try {
File file = fileChooser.getSelectedFile();
//ImageDrawer drawer = new ImageDrawer();
Toolkit toolkit = Toolkit.getDefaultToolkit();
String stringFile = file.toString();
Image image = toolkit.getImage(stringFile);
Path path = Paths.get(stringFile);
Path imagePath = path.toAbsolutePath();
String newStr = imagePath.toString();
BufferedImage picture = ImageIO.read(new File(newStr));
JLabel picLabel = new JLabel(new ImageIcon(picture));
picLabel.setBounds(350, 170, 150, 30);
add(picLabel);
} catch (IOException g) {
JOptionPane.showMessageDialog(null,"ERROR");
}
}
}
}
}
Well it 'works' now. This code can open and display an image the user selects. The layout is still broken(1), as hinted by Upload Profile Pict.... That guessed width and cut off text on this computer is one of the many reasons to use layout managers, padding & borders to position elements in a GUI.
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;
import javax.swing.*;
final class createProfilePage extends JFrame implements ActionListener {
Container container = getContentPane();
JLabel name = new JLabel("Name: ");
JTextField nameField = new JTextField();
JLabel age = new JLabel("Age: ");
JTextField ageField = new JTextField();
JLabel interest = new JLabel("Interests: ");
JTextField interestField = new JTextField();
JLabel aboutMe = new JLabel("About me: ");
JTextField aboutMeField = new JTextField();
JLabel phoneNum = new JLabel("Phone Number: ");
JTextField phoneNumberField = new JTextField();
JLabel picLabel = new JLabel();
JButton submit = new JButton("Save Profile");
JButton deleteProfile = new JButton("Delete Profile");
JButton uploadPic = new JButton("Upload Profile Picture");
createProfilePage() {
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
//setting container
setLayoutManager();
setLocationAndSize();
addComponents();
addActionEvent();
setTitle("Welcome");
setSize(600, 500);
}
public void setLayoutManager() {
container.setLayout(null);
}
public void setLocationAndSize() {
//Setting location and Size of each components using setBounds() method.
name.setBounds(50, 100, 100, 30);
age.setBounds(50, 170, 100, 30);
phoneNum.setBounds(50, 240, 100, 30);
interest.setBounds(50, 310, 100, 30);
aboutMe.setBounds(50, 380, 100, 30);
submit.setBounds(350, 240, 150, 30);
deleteProfile.setBounds(350, 310, 150, 30);
uploadPic.setBounds(350, 380, 150, 30);
nameField.setBounds(150, 100, 150, 30);
ageField.setBounds(150, 170, 150, 30);
phoneNumberField.setBounds(150, 240, 150, 30);
interestField.setBounds(150, 310, 150, 30);
aboutMeField.setBounds(150, 380, 150, 30);
picLabel.setBounds(350, 50, 150, 150);
}
public void addComponents() {
container.add(name);
container.add(age);
container.add(phoneNum);
container.add(interest);
container.add(aboutMe);
container.add(nameField);
container.add(ageField);
container.add(phoneNumberField);
container.add(interestField);
container.add(aboutMeField);
container.add(picLabel);
container.add(submit);
container.add(deleteProfile);
container.add(uploadPic);
}
public void addActionEvent() {
submit.addActionListener(this);
deleteProfile.addActionListener(this);
uploadPic.addActionListener(this);
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == uploadPic) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));
int result = fileChooser.showOpenDialog(getParent());
if (result == JFileChooser.APPROVE_OPTION) {
try {
File file = fileChooser.getSelectedFile();
BufferedImage picture = ImageIO.read(file);
picLabel.setIcon(new ImageIcon(picture));
add(picLabel);
} catch (IOException ioe) {
ioe.printStackTrace();
JOptionPane.showMessageDialog(null, "ERROR");
}
}
}
}
public static void main(String[] args) {
Runnable r = () -> {
new createProfilePage().setVisible(true);
};
SwingUtilities.invokeLater(r);
}
}
Personally, I'd take a different approach to the look of this. A toolbar at top for all the buttons. the two columns of labels and fields on the left as seen there, but with the label text aligned right, and the fields different sizes as per need. Maybe even make the "About me:" a text area, rather than a field. Then, to the right of the label/field combos, the rest of the width
and height devoted to the picture label. It would be shown in a
scroll pane (unless the pictures are all the same size).
I have posted two screenshots below of my GUI. The content of screenshot #1 opens before that of two (in other words, the user is given the ability to select a document before they are brought to the "main page" (with the buttons like mean gdp, and mean pop). How can I edit my code so that the user is shown the main page and they are only given the ability to select a document after they have clicked the button "select csv file"? I know that this has to do with nested code but I would like to have another eye look through what I've done.
Thanks
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.Scanner;
import java.awt.event.ActionEvent;
import java.awt.Color;
import javax.swing.JTextField;
import javax.swing.JLabel;
public class Frame1 {
private JFrame frame;
private JTextField txtCountryChosen;
/**
* Launch the application.
*/
public static void main(String[] args) {
File file;
Scanner fileIn;
int response;
JFileChooser chooser=new JFileChooser("");
chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
response= chooser.showOpenDialog(null);
if(response== JFileChooser.APPROVE_OPTION) {
file = chooser.getSelectedFile();
try {
fileIn= new Scanner(file);
if(file.isFile()) {
while(fileIn.hasNextLine()) {
String line=fileIn.nextLine();
System.out.println(line);
}
}
else {
System.out.println("That wasn't a file!");
}
fileIn.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(result==JFileChooser.APPROVE_OPTION) {
File file=jFileChooser.getSelectedFile();
try {
FileOutputStream fileoutputStream=
new FileOutputStream(file);
//fileoutputStream.flush();
//fileoutputStream.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
csv_select.setBounds(130, 62, 150, 25);
frame.getContentPane().add(csv_select);
JButton btnNewButton_1 = new JButton("Mean GDP");
btnNewButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnNewButton_1.setBounds(0, 154, 97, 25);
frame.getContentPane().add(btnNewButton_1);
JButton btnNewButton_2 = new JButton("Mean GDP_per_capita");
btnNewButton_2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnNewButton_2.setBounds(250, 154, 170, 25);
frame.getContentPane().add(btnNewButton_2);
JButton btnNewButton_3 = new JButton("Mean pop");
btnNewButton_3.setBounds(109, 154, 120, 25);
frame.getContentPane().add(btnNewButton_3);
txtCountryChosen = new JTextField();
txtCountryChosen.setBounds(12, 100, 116, 22);
frame.getContentPane().add(txtCountryChosen);
txtCountryChosen.setColumns(10);
JButton btnNewButton_4 = new JButton("Select country");
btnNewButton_4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnNewButton_4.setBounds(270, 99, 150, 25);
frame.getContentPane().add(btnNewButton_4);
JButton btnNewButton_5 = new JButton("Print Results in Txt File");
btnNewButton_5.setBounds(131, 201, 200, 20);
frame.getContentPane().add(btnNewButton_5);
JLabel lblNewLabel = new JLabel("Statistics Manager");
lblNewLabel.setBounds(158, 13, 157, 36);
frame.getContentPane().add(lblNewLabel);
}
}```
Im trying to sort my GUI so it will be able to use the methods from the other classes
in the JProject i also want to call it from the main.
The action listeners i had just learnt today so i need feedback on what to do there as well.
Any Ideas??
It would be a great help to get some insight on this!
(I am new to stack so my code posted in the explanation and in the actual script idk
why).
package test;
import javax.swing.JPanel;
import javax.swing.JLabel;
import com.jgoodies.forms.factories.DefaultComponentFactory;
import java.awt.Container;
import java.awt.SystemColor;
import java.awt.Color;
import javax.swing.JRadioButton;
import java.awt.Font;
import java.io.File;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.JComboBox;
import javax.swing.JButton;
import java.util.ArrayList;
import java.util.Scanner;
//Main Method
public class TextUI{
protected StormTracker var;
public TextUI(StormTracker var)
{
this.var=var;
}
public static void main(String[] args)
{
ShowGUI gui = new SHOWGUI();
while(gui.running)
if(gui.buttonPress == -1)
continue;
StormTracker obj = new StormTracker("config.txt");
WeatherAuthority wa = new WeatherAuthority("stormfile.txt");
int xcoord=0;
int ycoord=0;
TextUI uiobj = new TextUI(obj);
Scanner scan = new Scanner(System.in);
while(true){
System.out.println("---------------------------------------------------------------");
System.out.println("Welcome to the StormTracker Application.");
System.out.println("Type the following commands to carry out the associated actions.");
System.out.println("\n");
System.out.println("----------------------{Commands Menu}---------------------
-------");
System.out.println("(1) NEW STORM x y");
System.out.println("(2) UPGRADE <name of storm>");
System.out.println("(3) DOWNGRADE <name of storm>");
System.out.println("(4) TICK");
System.out.println("(5) EXIT");
System.out.println("----------------------------------------------------------------");
String option=scan.nextLine();
if (option.substring(0,4).equals("TICK")){
obj.tick();
continue;
}
if (option.substring(0,9).equals("NEW STORM")){
if(option.length()==13){
xcoord = Integer.parseInt(option.substring(10,11));
ycoord = Integer.parseInt(option.substring(12,13));
}
else if (option.length()==14){
if (option.substring(11,12).equals(" ")){
xcoord = Integer.parseInt(option.substring(10,11));
ycoord = Integer.parseInt(option.substring(12,14));
}
else{
xcoord = Integer.parseInt(option.substring(10,12));
ycoord = Integer.parseInt(option.substring(13,14));
}
}
else if (option.length()==15){
xcoord = Integer.parseInt(option.substring(10,12));
ycoord = Integer.parseInt(option.substring(13,15));
}
obj.newstorm(xcoord,ycoord);
}
if (option.substring(0,7).equals("UPGRADE")){
String storm_name = option.substring(8);
obj.upgrade(storm_name);
}
if (option.substring(0,9).equals("DOWNGRADE")){
String storm_name = option.substring(10);
obj.downgrade(storm_name);
}
}
}
//GUI Class
public ShowGUI extends JPanel {
private JTextField textField;
private JTextField textField_1;
private JTextField textField_2;
private JTextField textField_3;
private JTextField textField_4;
System.out.println("GUI Successfully Loaded");
createAndShow();
setToolTipText("Select Storm");
setBackground(Color.WHITE);
}
private void createAndShow(){
JPanel mainFrame = new JPanel("Storm Tracker V1.0");
}
private void addComponents(Container pane){
pane.setLayout(null);
JLabel lblStormTrackerV = DefaultComponentFactory.getInstance().createTitle("
Storm Tracker V1.0");
lblStormTrackerV.setBackground(SystemColor.activeCaption);
lblStormTrackerV.setFont(new Font("Calibri", Font.PLAIN, 22));
lblStormTrackerV.setBounds(162, 11, 430, 41);
add(lblStormTrackerV);
JRadioButton rdbtnMap = new JRadioButton("MAP");
rdbtnMap.setBounds(283, 59, 72, 23);
add(rdbtnMap);
JRadioButton rdbtnBulletin = new JRadioButton("Bulletin");
rdbtnBulletin.setBounds(406, 60, 72, 23);
add(rdbtnBulletin);
textField = new JTextField();
textField.setBounds(61, 103, 72, 20);
add(textField);
textField.setColumns(10);
textField_1 = new JTextField();
textField_1.setBounds(61, 134, 72, 20);
add(textField_1);
textField_1.setColumns(10);
JTextPane txtpnX = new JTextPane();
txtpnX.setText("X:");
txtpnX.setBounds(23, 103, 28, 20);
add(txtpnX);
JTextPane txtpnY = new JTextPane();
txtpnY.setText("Y:");
txtpnY.setBounds(23, 134, 12, 20);
add(txtpnY);
JTextPane txtpnSpeed = new JTextPane();
txtpnSpeed.setText("Speed:");
txtpnSpeed.setBounds(10, 165, 41, 20);
add(txtpnSpeed);
textField_2 = new JTextField();
textField_2.setBounds(61, 165, 72, 20);
add(textField_2);
textField_2.setColumns(10);
textField_3 = new JTextField();
textField_3.setBounds(61, 196, 72, 20);
add(textField_3);
textField_3.setColumns(10);
JTextPane txtpnSpeed_1 = new JTextPane();
txtpnSpeed_1.setText("Speed:");
txtpnSpeed_1.setBounds(10, 196, 41, 20);
add(txtpnSpeed_1);
JTextPane txtpnBearing = new JTextPane();
txtpnBearing.setText("Bearing:");
txtpnBearing.setBounds(10, 227, 41, 20);
add(txtpnBearing);
textField_4 = new JTextField();
textField_4.setBounds(61, 227, 72, 20);
add(textField_4);
textField_4.setColumns(10);
File input = new File(new
FileReader("C:\\Users\\620086793\\Documents\\test\\src\\test"));
List<String> strings = new ArrayList<String>();
try {
String line = null;
while (( line = input.readLine()) != null){
strings.add(line);
}
}
catch (FileNotFoundException e) {
System.err.println("Error, file " + "C:\\Users\\620086793\\Documents\\test\\src\\test" + " didn't exist.");
}
finally {
input.close();
}
String[] lineArray = strings.toArray(new String[]{});
JComboBox comboBox = new JComboBox(lineArray);
JComboBox comboBox = new JComboBox();
comboBox.setToolTipText("Select Storm");
comboBox.setEditable(true);
comboBox.setBounds(20, 60, 113, 20);
add(comboBox);
JButton btnUpdate = new JButton("UPDATE");
btnUpdate.setFont(new Font("Calibri", Font.BOLD, 11));
btnUpdate.setBounds(10, 273, 110, 28);
add(btnUpdate);
JButton btnNewButton = new JButton("NEW STORM\r\n");
btnNewButton.setFont(new Font("Calibri", Font.BOLD, 11));
btnNewButton.setBounds(10, 312, 110, 28);
add(btnNewButton);
addActionListeners();
pane.add(rdbtnMap);
pane.add(rdbtnBulletin);
pane.add(textField);
pane.add(textField_1);
pane.add(textField_2);
pane.add(textField_3);
pane.add(textField_4);
pane.add(comboBox);
pane.add(btnUpdate);
pane.add(btnNewButton);
}
//Im not sure how to properly add the action listeners i first learned about them
today.
private void addActionListeners(){
rdbtnMap.addActionListener(new ActionListener){
public void actionPerformed(ActionEvent ){
}
}
rdbtnBulletin.addActionListener(){
public void actionPerformed(ActionEvent ){
}
}
textField.addActionListener(){
public void actionPerformed(ActionEvent ){
}
}
textField_2.addActionListener(){
public void actionPerformed(ActionEvent ){
}
}
textField_3.addActionListener(){
public void actionPerformed(ActionEvent ){
}
}
textField_4.addActionListener(){
public void actionPerformed(ActionEvent ){
stormTracker.tick = textField_4;
}
}
comboBox.addActionListener(){
public void actionPerformed(ActionEvent ){
}
}
btnUpdate.addActionListener(){
public void actionPerformed(ActionEvent ){
obj.upgrade() = btnUpdate;
return btnUpdate;
}
}
btnNewButton.addActionListener(){
public void actionPerformed(ActionEvent ){
}
}
}
My code with java GUI adds to an arraylist from a file.txt I have in a button the code that compares the code introduced in a textfield with the position in the araylist with an if else. But enter what you enter always goes through the else never through the if.
If I add the components manually as in Arraylist ArrayList <String> answer = new ArrayList <String> ();
then if else works.
But it seems that if I compare the text of the textfield with the
ArrayList <String> answer1 = new ArrayList <String> ();, the if does not work does not do well the comparison
The question is that I need to ask the user 266 questions The user must enter the answers, if the answer is not correct, an incorrect reply message should come out
but I can not get the if else to work with an arraylist loaded with a file.text here is my code.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.awt.event.ActionEvent;
import javax.swing.JTextArea;
public class question_answer extends JFrame {
private JPanel contentPane;
private JTextField textField;
private JButton btnAnswer;
private JLabel lblNewLabelcuestion;
private JLabel LabelTextF;
private JLabel labelArraylistPos;
private JLabel lblNewLabelTF;
private JLabel lblNewLabelAL;
static int count = 0;
private JLabel lblNewLabel_1;
private static JTextArea textArea;
private JLabel lblNewLabel;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
question_answer frame = new question_answer();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public question_answer() {
File archive = null;
FileReader fr = null;
//This works
/*
* ArrayList<String> question = new ArrayList<String>();
* question.add("What is your name?");
* question.add("What is your surname?");
* question.add("What is your age?");
* ArrayList<String> answer = new ArrayList<String>();
* answer.add("Pedro");
* answer.add("Rodriguez");
* answer.add("46");
*/
ArrayList<String> answer1 = new ArrayList<String>();
try {
archive = new File("C:\\answer.txt");
String line;
fr = new FileReader(archive);
BufferedReader br = new BufferedReader(fr);
while ((line = br.readLine()) != null) {
answer1.add(line);
}
br.close();
} catch (IOException e) {
System.out.println(e);
}
finally {
try {
if (fr != null) {
fr.close();
}
} catch (IOException e) {
}
}
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 567, 400);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
lblNewLabelcuestion = new JLabel("New label");
lblNewLabelcuestion.setBounds(60, 56, 360, 24);
contentPane.add(lblNewLabelcuestion);
lblNewLabelTF = new JLabel("New label");
lblNewLabelTF.setBounds(60, 292, 56, 16);
contentPane.add(lblNewLabelTF);
LabelTextF = new JLabel("TextField");
LabelTextF.setBounds(60, 263, 56, 16);
contentPane.add(LabelTextF);
lblNewLabelAL = new JLabel("New label");
lblNewLabelAL.setBounds(170, 292, 56, 16);
contentPane.add(lblNewLabelAL);
labelArraylistPos = new JLabel("Arraylist Position");
labelArraylistPos.setBounds(170, 263, 110, 16);
contentPane.add(labelArraylistPos);
textField = new JTextField();
textField.setBounds(340, 139, 116, 22);
contentPane.add(textField);
textField.setColumns(10);
lblNewLabelcuestion.setText(answer1.get(count));
btnAnswer = new JButton("answer");
lblNewLabelAL.setText(answer1.get(count));
btnAnswer.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String line1;
for (int j = 0; j < answer1.size(); j++) {
line1 = answer1.get(j);
textArea.append(line1);
}
lblNewLabelcuestion.setText(answer1.get(count));
lblNewLabelAL.setText(answer1.get(count));
lblNewLabelTF.setText(textField.getText());
String c = answer1.get(count);
String Tf = textField.getText();
if (Tf.equals(c)) {
lblNewLabel_1.setText("Good");
} else {
lblNewLabel_1.setText("Wrong");
}
count += 1;
}
});
btnAnswer.setBounds(340, 198, 97, 25);
contentPane.add(btnAnswer);
lblNewLabel_1 = new JLabel("New label");
lblNewLabel_1.setBounds(45, 153, 256, 16);
contentPane.add(lblNewLabel_1);
textArea = new JTextArea();
textArea.setBounds(345, 273, 181, 67);
contentPane.add(textArea);
lblNewLabel = new JLabel("achive.text content");
lblNewLabel.setBounds(340, 244, 116, 16);
contentPane.add(lblNewLabel);
}
}
`
In any text editor, when you press enter, the the editor enters what is called a line break. This character is invisible but it tells the editor where to make a new line. You need to remove these characters from your lines. Good news is you only have to add one line of code to achieve this! Where you have:
while ((line = br.readLine()) != null) {
answer1.add(line);
}
Replace it with:
while ((line = br.readLine()) != null) {
line = line.replace(System.getProperty("line.separator"), “”);
answer1.add(line);
}
The above code will replace any line separator defined by the OS with an empty string, thereby making your compared strings equal.
The solution was String c = answer1.get(count).trim();
This is my first post!
I'm trying to implement the combo box made in the TutCombo program into the ExamGradesGUI + ExamGrades one. As you can see in the TutCombo program, there is the 'String subjectUnitTxt'. Ideally, I would like this to replace the 'subjectUnitTxt' in the ExamGradesGUI program, but having the functionality of the combo box and being able to be saved to the file along with firstName, lastName and examMark. If someone could tell me how to do this, that would be great. Sorry if I have added too much code. Thanks
I got this to work by making some minor changes in your code (see attached code). Search for "unitCombo".
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class ExamGradesGUI {
public static void main(String[] args) {
new ExamGradesGUI();
}
String[] firstName = new String[20];
String[] lastName = new String[20];
String[] subjectUnit = new String[20];
double[] examMark = new double[20];
private JLabel firstNameLbl, lastNameLbl, unitLbl, markLbl;
private JTextField firstNameTxt, lastNameTxt, subjectUnitTxt, examMarkTxt;
private JComboBox<String> unitCombo;
private JButton btnClear, btnSave, btnOpen, btnExit;
private JPanel panel;
private JFrame frame;
public ExamGradesGUI(){
buildFrame();
buildFields();
buildButtons();
frame.setVisible(true);
frame.add(panel);
}
public void buildFrame(){
frame = new JFrame("GradeEnter");
frame.setSize(650,450);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel = new JPanel();
panel.setLayout(null);
panel.setBackground(Color.white);
}
public void buildFields(){
// Labels, User Input + Location
firstNameTxt = new JTextField(10);
firstNameTxt.setBounds(180, 80, 150, 20);
panel.add(firstNameTxt);
String str = firstNameTxt.getText();
if(str.matches("[-a-zA-Z]*"))
{
}
else
{
JOptionPane.showMessageDialog(null, "Please enter amount donating");
}
lastNameTxt = new JTextField(10);
lastNameTxt.setBounds(180, 110, 150, 20);
panel.add(lastNameTxt);
subjectUnitTxt = new JTextField(10);
String[] courses = {"Computing","Forensic","Business"};
unitCombo = new JComboBox<String>(courses);
//subjectUnitTxt.setBounds(180, 140, 150, 20);
//panel.add(subjectUnitTxt);
unitCombo.setBounds(180, 140, 150, 20);
panel.add(unitCombo);
// IF HAVE TIME: Turn Combo Box into GUI - Refer to testgui.java
examMarkTxt = new JTextField(10);
examMarkTxt.setBounds(180, 170, 150, 20);
panel.add(examMarkTxt);
firstNameLbl = new JLabel("First Name:");
firstNameLbl.setBounds(70, 80, 100, 20);
panel.add (firstNameLbl);
lastNameLbl = new JLabel("Last Name:");
lastNameLbl.setBounds(70, 110, 100, 20);
panel.add (lastNameLbl);
unitLbl = new JLabel("Unit:");
unitLbl.setBounds(70, 140, 100, 20);
panel.add (unitLbl);
markLbl = new JLabel("Mark:");
markLbl.setBounds(70, 170, 100, 20);
panel.add (markLbl);
}
public void buildButtons() {
btnClear = new JButton ("Reset Fields");
btnClear.setBounds(55, 220, 110, 20);
btnClear.addActionListener(new ClearButtonListener());
panel.add (btnClear);
btnSave = new JButton ("Save");
btnSave.setBounds(155, 220, 70, 20);
btnSave.addActionListener(new SaveButton());
panel.add (btnSave);
btnOpen = new JButton ("Open 'GradeEnter.txt' ");
btnOpen.setBounds(90, 250, 200, 20);
btnOpen.addActionListener(new OpenButton());
panel.add (btnOpen);
btnExit = new JButton ("Exit");
btnExit.setBounds(255, 220, 70, 20);
btnExit.addActionListener(new ExitButton());
panel.add (btnExit);
}
public void setText() {
firstNameTxt.setText("");
lastNameTxt.setText("");
subjectUnitTxt.setText("");
examMarkTxt.setText("");
}
public void getText() {
int i = 0;
i++;
firstName[i] = firstNameTxt.getText();
lastName[i] = lastNameTxt.getText();
subjectUnit[i] = unitCombo.getItemAt(unitCombo.getSelectedIndex());
examMark[i] = Double.parseDouble(examMarkTxt.getText());
}
private class ClearButtonListener implements ActionListener {
public void actionPerformed (ActionEvent e) {
setText();
}
}
private class SaveButton implements ActionListener {
public void actionPerformed(ActionEvent e) {
getText();
setText();
ExamGrades save = new ExamGrades();
save.fileOpen();
save.addRecords(firstName, lastName, subjectUnit, examMark);
JOptionPane.showMessageDialog(null, "Entry Saved!");
save.fileClose();
}
}
private class OpenButton implements ActionListener {
public void actionPerformed(ActionEvent e) {
try {
JOptionPane.showMessageDialog(null, "'GradeEnter.txt' opening in Java!");
Thread.sleep(2); // Adds a 2 second delay so user can read dialog message
Runtime.getRuntime().exec("eclipse GradeEnter.txt" );
} catch (Exception NoFileFound) {
System.out.println("Couldn't open or find the file.");
}
}
}
class ExitButton implements ActionListener{
public void actionPerformed(ActionEvent e) {
int n = JOptionPane.showConfirmDialog(frame,
"Are you sure you want to exit?",
"Exit?",
JOptionPane.YES_NO_OPTION);
if(n == JOptionPane.YES_OPTION){
System.exit(0);
}
}
}
}