This question is similar to this : How do you reference a button inside of its actionlistener?
I want to create a simple form containing 8 toggle buttons. if i select the toggle button and click save button, it will write into the text file i.e "Button x, On". Next time i open the form, the form will check in the notepad if Button x is already on. If on, the toggle button will already be selected and vice versa.
I know how to write to and read from the notepad, but i am not sure how to check if i.e the user select button 2 then the code will write into second line " Button2, on"
Here is my code so far to write :
Path path = Paths.get(csvFile);
// check if button x is selected, if yes : <- how to refer to button x ?
BufferedWriter bw = new BufferedWriter(New FileWriter(csvFile, true);
writer.write ("button x,on" + "\r\n");
writer.close
and this is my code when the form is opened :
BufferedReader br = null;
String line = "";
String resFilesplitby = ",";
br = new BufferedReader(new FileReader(csvFile));
while((line = br.readLine()) != null){
String[] condition = line.split(csvFilesplitby);
String power = condition[1];
// check if button x is already selected
if (button x power.equals("on")){
button x.isSelected();
}
}
I manage to found a simple way to solve the problem
By adding the button to an array.
JToggleButton[] buttons = new JToggleButton[8];
buttons[0] = seat1; //this is variable name of my button.
buttons[1] = seat2;
buttons[2] = seat3;
buttons[3] = seat4;
buttons[4] = seat5;
buttons[5] = seat6;
buttons[6] = seat7;
buttons[7] = seat8;
// do the work here
for (JToggleButton btn : buttons){
if(btn.isSelected){
}
}
For simplicity I recommend that you write all of the button statuses at the same time, and write them directly as a boolean value:
//Write the state of all the buttons in a single line:
writer.write (
x1.isSelected() + "," +
x2.isSelected() + "," +
x3.isSelected() + "," +
x4.isSelected() + "," +
x5.isSelected() + "," +
x6.isSelected() + "," +
x7.isSelected() + "," +
x8.isSelected());
Then reading it back as a single line and just compare each of the 8 items split by the ",":
String[] condition = line.split(csvFilesplitby);
if (condition[0].equalsIgnoreCase("true")){
x1.setSelected(true);
}else if (condition[1].equalsIgnoreCase("true")){
x2.setSelected(true);
}else if (condition[2].equalsIgnoreCase("true")){
x3.setSelected(true);
}else if (condition[3].equalsIgnoreCase("true")){
x4.setSelected(true);
}else if (condition[4].equalsIgnoreCase("true")){
x5.setSelected(true);
}else if (condition[5].equalsIgnoreCase("true")){
x6.setSelected(true);
}else if (condition[6].equalsIgnoreCase("true")){
x7.setSelected(true);
}else if (condition[7].equalsIgnoreCase("true")){
x8.setSelected(true);
}
Obviously you should add some error checking and make sure all buttons are deselected before you set if they are selected or not. But I am sure you can work that part out.
Alternatively you can try something like below :
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import javax.swing.*;
public class Ques1 extends JFrame implements ActionListener {
private JPanel panel;
private JToggleButton[] buttons;
public Ques1() {
initComponents();
buttonswork();
}
private void initComponents() {
buttons = new JToggleButton[6];
panel = new JPanel();
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.LINE_AXIS));
panel.setLayout(new FlowLayout(FlowLayout.CENTER, 0, 0));
for (int i = 0; i < buttons.length; i++) {
JToggleButton tb = buttons[i];
tb = new JToggleButton("tb" + (i + 1));
tb.addActionListener(this);
panel.add(tb);
}
getContentPane().add(panel);
pack();
}
private void buttonswork() {
try {
String line = "";
String buttonString = "tb1-0\n"
+ "tb2-0\n"
+ "tb3-0\n"
+ "tb4-1\n"
+ "tb5-1\n"
+ "tb6-0\n";
BufferedReader br = new BufferedReader(new StringReader(buttonString));
while ((line = br.readLine()) != null) {
Component[] components = panel.getComponents();
for (Component c : components) {
if (c instanceof JToggleButton) {
String ac = ((JToggleButton) c).getActionCommand();
((JToggleButton) c).addActionListener(this);
if (ac.equalsIgnoreCase(line.split("-")[0])) {
((JToggleButton) c).setSelected(Integer.parseInt(line.split("-")[1]) == 1);
}
}
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
new Ques1().setVisible(true);
});
}
#Override
public void actionPerformed(ActionEvent e) {
switch (e.getActionCommand()) {
case "tb1":
//do your work here ...
break;
case "tb2":
//do your work here ...
break;
}
}
}
Related
I am trying to create a java applet that uses text fields to add strings to a linked list. I can not get the search button to work. I am trying to get the string specified by the user in the text field and then search the list and print how many times the word has been found if any.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.LinkedList;
import java.util.ListIterator;
/**
* Created by joshuaogunnote on 31/10/2015.
*/
public class Applet2 extends JApplet {
private String text;
private int text1;
JTextField value1, value2;
LinkedList<String> list = new LinkedList<String>();
public JLabel jLabel;
public int count = 0;
I have created this search_count variable to count up how many times the word has been found.
public int search_count = 0;
public void init() {
JLabel prompt = new JLabel("Please enter a word");
JLabel prompt1 = new JLabel("Please enter a certain letter");
value1 = new JTextField(10);
value2 = new JTextField(10);
JPanel textPanel = new JPanel();
textPanel.add(prompt);
textPanel.add(value1);
add(textPanel, BorderLayout.NORTH);
textPanel.add(prompt1);
textPanel.add(value2);
JPanel centrePanel = new JPanel();
text = "";
jLabel = new JLabel(text);
centrePanel.add(jLabel);
add(centrePanel, BorderLayout.CENTER);
JButton but = new JButton("Add word");
JButton but1 = new JButton("Clear");
JButton but2 = new JButton("Remove first occurrence");
JButton but3 = new JButton("Remove all occurrences");
JButton but4 = new JButton("Display all words begging with certain letter");
JButton but5 = new JButton("Search");
JPanel butPanel = new JPanel();
butPanel.add(but);
butPanel.add(but1);
butPanel.add(but5);
butPanel.add(but2);
butPanel.add(but3);
butPanel.add(but4);
add(butPanel, BorderLayout.SOUTH);
but.addActionListener(new ButtonHandler(this));
but1.addActionListener(new ButtonHandler1(this));
but5.addActionListener(new ButtonHandler2(this));
}
class ButtonHandler implements ActionListener {
private Applet2 theApplet;
public ButtonHandler(Applet2 app) {
theApplet = app;
}
public void actionPerformed(ActionEvent e) {
text = theApplet.value1.getText();
try {
text1 = Integer.parseInt(text);
jLabel.setText("ERROR - The string " + "'" + text1 + "'" + " is not a valid word");
} catch (NumberFormatException e1) {
if (text.length() != 0) {
jLabel.setText("Word " + "'" + text + "'" + " has been added to the list");
count = count + 1;
} else {
jLabel.setText("ERROR - Please enter a word");
}
}
}
}
class ButtonHandler1 implements ActionListener {
private Applet2 theApplet;
public ButtonHandler1(Applet2 app) {
theApplet = app;
}
public void actionPerformed(ActionEvent e) {
list.clear();
jLabel.setText("List has been cleared");
count = 0;
}
}
class ButtonHandler2 implements ActionListener {
private Applet2 theApplet;
public ButtonHandler2(Applet2 app) {
theApplet = app;
}
public void actionPerformed(ActionEvent e) {
String text = theApplet.value1.getText();
Here I am trying to use a for loop to iterate through all the strings in the list and increment search_count if a match has been found. It does not however produce the correct answer. I am also trying to produce an ERROR message when the user tries to search for a word that is not in the list. How do I get the search_count variable and how do I get the ERROR message to show at the correct time?
for (int i = 0; i < list.size(); i++) {
if(text.equals(list.get(i))){
search_count = search_count + 1;
} else {
jLabel.setText("ERROR - word is not in the list")
}
jLabel.setText("Word " + "'" + text + "'" + " was found " + search_count + " time(s) in the list");
if (text.length() == 0) {
jLabel.setText("Please enter a word - The total number of words in the list are: " + count);
}
}
}
}
It seems you did not declare count as a variable before you used it in the loop. If the output is not what you want / expect, the condition of the loop gives you something else then what you think it does.
int count = 0;
I am very new to java. I am working on project for class that would look up books in a text file and display information about them. Primarily if the book is in stock or not. The text file is set up like this: {ISBN, Author, Type, Stock}
I have coded a user interface that allows the user to type in ISBN, Author, and Type. Ideally, I would like for the user to just search one of these and return the needed information. However, just searching via ISBN would be acceptable for now. My code right now only takes what is typed into the textboxes and displays it in a large textbox. I am somewhat familiar with reading a text file in but have no idea how I would take the text from a textbox and use it to search the file. Any help would be greatly appreciated.
Here is my code:
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
import java.sql.*;
public class InventoryInterface extends JFrame
{
private static final int FRAME_WIDTH = 600;
private static final int FRAME_HEIGHT = 350;
private JButton btnSearch;
private JButton btnDatabase;
private JButton btnRefresh;
private JLabel lblISBN, lblAuthor, lblType;
private JTextField txtISBN, txtAuthor, txtType;
private JTextArea txtOutput;
public InventoryInterfaceSimple()
{
createComponents();
setSize(FRAME_WIDTH, FRAME_HEIGHT);
}
public void createComponents()
{
btnSearch = new JButton("Search");
lblISBN = new JLabel("ISBN");
lblAuthor = new JLabel("Author");
lblType = new JLabel("Type");
txtISBN = new JTextField(10);
txtAuthor = new JTextField(10);
txtType = new JTextField(10);
txtOutput = new JTextArea(30,30);
txtOutput.setText("");
txtOutput.setEditable(false);
ActionListener action = new InventoryOutput();
btnSearch.addActionListener(action);
JPanel panel = new JPanel();
panel.setLayout(null);
lblISBN.setBounds(10,10,50,25);
txtISBN.setBounds(55,10,125,25);
lblAuthor.setBounds(10,40,50,25);
txtAuthor.setBounds(55,40,125,25);
lblType.setBounds(10,70,50,25);
txtType.setBounds(55,70,125,25);
btnSearch.setBounds(30,130,150,25);
JScrollPane scrollArea = new JScrollPane(txtOutput);
scrollArea.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scrollArea.setBounds(200,10,350,200);
panel.add(scrollArea);
panel.add(lblISBN);
panel.add(txtISBN);
panel.add(lblAuthor);
panel.add(txtAuthor);
panel.add(lblType);
panel.add(txtType);
panel.add(btnSearch);
panel.add(scrollArea);
add(panel);
}
class InventoryOutput implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
String inventoryString = "";
inventoryString += txtISBN.getText() + " - ";
inventoryString += "Author: " + txtAuthor.getText() + " - ";
inventoryString += "Type: " + txtType.getText() + " - ";
txtOutput.append(inventoryString + "\n");
txtISBN.setText("");
txtAuthor.setText("");
txtType.setText("");
}
}
}
you can replace your code with this.. this is a starting point, you can do many improvements to this code, but this will work. change REPOSITORY_FILE_PATH to your data file
class InventoryOutput implements ActionListener {
private final String REPOSITORY_FILE_PATH = "C:\\temp\\book-repo.txt";
private final File REPOSITORY_FILE = new File(REPOSITORY_FILE_PATH);
public void actionPerformed(ActionEvent event) {
String inventoryString = "";
String requestedISBN = txtISBN.getText().trim().toLowerCase();
String requestedAuthor = txtAuthor.getText().trim();
String requestedType = txtType.getText().trim();
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(REPOSITORY_FILE));
String line;
while ((line = reader.readLine()) != null) {
String lineLtrim = line.toLowerCase().replaceAll("^\\{", ""); //{
String lineRtrim = lineLtrim.replaceAll("\\}$", ""); //}
String[] data = lineRtrim.split(","); //ISBN, Author, Type, Stock
if (data.length < 4) {
throw new IllegalArgumentException("bad datafile: All fields must be entered: " + line);
}
if (data[0].equals(requestedISBN)) {
inventoryString += txtISBN.getText() + " - Author: " + data[1] + " - Type: " + data[2] + " - Stock:" + data[3];
txtOutput.append(inventoryString + "\n");
return;
}
}
reader.close();
inventoryString += txtISBN.getText() + " - Not Found";
txtOutput.append(inventoryString + "\n");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
you can just add this main() code to test, ideally you should write unit test-- to cover all cases.
public static void main(String[] args) {
JFrame f = new InventoryInterface();
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.setPreferredSize(new Dimension(600, 600));
f.pack();
f.setVisible(true);
}
data file
{ISBN1234,me,drama,5}
{ISBN1235,me,Tech,0}
{ISBN1236,me,Fiction,2}
{ISBN1237,me,Audio/Kids,4}
Not sure which part you did not get,,
on the listener-- we read the ISBN entered by user String
requestedISBN = txtISBN.getText().trim().toLowerCase(); and convert
it in lower case so, we can compare with lower-cased-data
then we read your data file (line by line)
we then from each line we remove character "{" and "}" // comment
says that
then we get "isbn,author, type, stock" , so we split by ","
split gives us array of string putting each element in array in
order i.e data[0] has isbn, data[1] has author ...etc
we check if the data file is correct by making sure we have all
elements in there i.e if (data.length < 4) {
we throw exception if the size of array is not <4 i.e. we found that
the data file has incorrect data.
then we compare if the input isbn (data[0]) is same as one of the
line element from your data file
if we find a match we display it in the textArea and exit the loop,
if we dont find we display "not Found"
If you wrote the code (listener) yourself, this should be trivial to you.
You could create a private String chosenISBN and set the value of it in the actionPerformed method. Then you can access the value everywhere in the class.
You could even create a getter for the chosenISBN as well, if you need it.
I have and edit button and its supposed to open a different Jframe but for some reason it flashes on screen and goes away. I cant figure it out maybe you guys can. And my delete button deletes the row above the row selected. the frame is at like 250 and the button pressed is on line 323
Button declaration:
btnAdd = new JButton("Add Student");
btnAdd.addActionListener(bh);
btnEdit = new JButton("EDIT");
btnEdit.addActionListener(bh);
btnEdit.setEnabled(false);
btnDelete = new JButton("DELETE");
btnDelete.addActionListener(bh);
btnDelete.setEnabled(false);
btnSort = new JButton("Update");
btnSort.addActionListener(bh);
btnSave = new JButton("SAVE");
btnSave.addActionListener(bh);
btnSave.setActionCommand("Save");
btnAddInput = new JButton("Add Student");
btnAddInput.addActionListener(bh);
btnAddInput.setActionCommand("AddInput");
btnCancel = new JButton("Cancel");
btnCancel.addActionListener(bh);
Frame declaration:
frame1 = new JFrame("Edit Student");
frame1.setVisible(false);
frame1.setResizable(false);
frame1.setDefaultCloseOperation(HIDE_ON_CLOSE);
frame1.add(addPanel, BorderLayout.CENTER);
frame1.add(buttonPanel2, BorderLayout.PAGE_END);
frame1.pack();
Button Handler:
class ButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("Add Student")) {
txtID.setText("");
txtName.setText("");
txtMajor.setText("");
txtGPA.setText("");
txtCampus.setText("");
txtAddress.setText("");
txtPhone.setText("");
txtEmail.setText("");
txtCurrent.setText("");
txtPast.setText("");
txtFuture.setText("");
txtNotes.setText("");
frame1.setTitle("Add Student data"); // title bar name for add
frame1.setVisible(true);
Student student = new Student(txtID.getText(), txtName.getName(), txtMajor.getText(), txtGPA.getText(), txtCampus.getText(), txtAddress.getText(), txtPhone.getText(),txtEmail.getText(), txtCurrent.getText(), txtPast.getText(), txtFuture.getText(), txtNotes.getText());
al.add(student);
try {
Student.saveSerialized(student, txtID.getText());
} catch (IOException ex) {
Logger.getLogger(IAdvise.class.getName()).log(Level.SEVERE, null, ex);
}
} else if (e.getActionCommand().equals("EDIT")) {
frame1.setVisible(true);
txtID.setText(data[rowIndex][0] + "");
txtName.setText(data[rowIndex][1] + "");
txtMajor.setText(data[rowIndex][2] + "");
txtGPA.setText(data[rowIndex][3] + "");
txtCampus.setText(data[rowIndex][4] + "");
txtAddress.setText(data[rowIndex][5] + "");
txtPhone.setText(data[rowIndex][6] + "");
txtEmail.setText(data[rowIndex][7] + "");
txtCurrent.setText(data[rowIndex][8] + "");
txtPast.setText(data[rowIndex][9] + "");
txtFuture.setText(data[rowIndex][10] + "");
txtNotes.setText(data[rowIndex][11] + "");
txtID.setEditable(false);
frame1.setTitle("Enter Student data");
btnAddInput.setActionCommand("Edit2");
btnAddInput.setText("ACCEPT");
} else if (e.getActionCommand().equals("DELETE")) {
int confirm = JOptionPane.showConfirmDialog(frame, "ARE YOU SURE?", "CONFIRM",
JOptionPane.YES_NO_OPTION);
if (confirm == 0) {
rowIndex = table.getSelectedRow();
rowNumber = 0;
noOfStudents--;
for (int i = 0; i <= 10; i++) {
if (rowIndex != i && i <= noOfStudents) {
data[rowNumber][0] = data[i][0];
data[rowNumber][1] = data[i][1];
data[rowNumber][2] = data[i][2];
data[rowNumber][3] = data[i][3];
data[rowNumber][4] = data[i][4];
data[rowNumber][5] = data[i][5];
data[rowNumber][6] = data[i][6];
data[rowNumber][7] = data[i][7];
data[rowNumber][8] = data[i][8];
data[rowNumber][9] = data[i][9];
data[rowNumber][10] = data[i][10];
data[rowNumber][11] = data[i][11];
rowNumber++;
} else if (rowIndex != i && i > noOfStudents) {
data[rowNumber][0] = "";
data[rowNumber][1] = "";
data[rowNumber][2] = "";
data[rowNumber][3] = "";
data[rowNumber][4] = "";
data[rowNumber][5] = "";
data[rowNumber][6] = "";
data[rowNumber][7] = "";
data[rowNumber][8] = "";
data[rowNumber][9] = "";
data[rowNumber][10] = "";
data[rowNumber][11] = "";
rowNumber++;
}
}
if (noOfStudents == 1000) {
btnAdd.setEnabled(false);
}
else {
btnAdd.setEnabled(true);
}
if (noOfStudents == 0) {
btnDelete.setEnabled(false);
btnEdit.setEnabled(false);
} else {
btnDelete.setEnabled(true);
btnEdit.setEnabled(true);
}
rowIndex = table.getSelectedRow();
if (data[rowIndex][0] == null || data[rowIndex][0] == "") {
btnEdit.setEnabled(false);
btnDelete.setEnabled(false);
} else {
btnEdit.setEnabled(true);
btnDelete.setEnabled(true);
}
table.updateUI();
}
Basically, when you call setVisible on a frame, the code will continue running without stopping.
What this is leading to is...
frame1.setVisible(true);
.
.
.
frame1.dispose();
Basically, you make the frame visible, but later in your code, you dispose of it.
What you really want is a modal dialog which, when made visible, will block the code execution until it is closed.
Take a look at How to make dialogs for more details
Review...
Don't extend PlainDocument to perform filtering of fields, instead, use a DocumentFilter. Take a look at Text Component Features and MDP's Weblog
Don't use KeyListener on text fields to performing filter, instead, use a DocumentFilter
Don't call JTable.updateUI. This has nothing to do with updating the UI when it's contents changed and is used to update the look and feel if it changes. Instead, rely on the TableModel and raise appropriate events to tell the table to update itself
Reduce the complexity of your actionPerformed method. Try breaking the logic down into separate methods, maybe even separate ActionListeners or if you really want to try something modular and advanced, take a look at How to use Actions
I did something like you and the result is same with you ,so I can give you a method to take it,
you can get a method to print the look,and frame.setVible(true) can be make to called by a method,
create more frame,and when you want to update or repaint it,you can call a method.
I hope what I says can be make some help to you .
I'm busy writing an hangman application and I'm currently checking if some of the code works... now i haven't gotten to hiding the word part yet so in the place of that code i used an if statement as supplementary code:
if(original.indexOf(button.getText())!=-1){
JOptionPane.showMessageDialog(null, "Your word does contain" + text );
}
else{
JOptionPane.showMessageDialog(null, "There is no" + text );
error++;
}
}
Anyway when I press the buttons that's not in the word it suppose to add to my errors according to
error++;
and it only finds the first letter in the word. One of my words are Dinosaur when i press D it says "Yes, there is a D" but when I press A it says "No, there is no I" where the clearly is
Can someone please help
here's my full code
import java.awt.*;
import java.awt.event.*;
import java.util.Arrays;
import javax.swing.*;
import java.io.*;
import java.util.ArrayList;
import java.util.Random;
import java.util.List;
public final class Hangman extends JFrame implements ActionListener{
String original = readWord();
int error = 0;
String imageName;
JButton btnAddWord = new JButton("Add New Word");
JButton btnRestart = new JButton("Restart");
JButton btnHelp = new JButton("Help");
JButton btnExit = new JButton("Exit");
JLabel word = new JLabel(original);
static JPanel panel1 = new JPanel();
static JPanel panel2 = new JPanel();
static JPanel panel3 = new JPanel();
static JPanel panel4 = new JPanel();
public Hangman(){
Container content =getContentPane();
content.setLayout(new GridLayout(0,1));
if(error >= 0) imageName = "hangman1.jpg";
if(error >= 1) imageName = "hangman2.jpg";
if(error >= 2) imageName = "hangman3.jpg";
if(error == 3) imageName = "hangman4.jpg";
if(error == 4) imageName = "hangman5.jpg";
if(error == 5) imageName = "hangman6.jpg";
if(error == 7) imageName = "hangman7.jpg";
ImageIcon icon = null;
if(imageName != null){
icon = new ImageIcon(imageName);
}
JLabel image = new JLabel();
image.setIcon(icon);
btnAddWord.addActionListener(this);
btnRestart.addActionListener(this);
btnHelp.addActionListener(this);
btnExit.addActionListener(this);
panel2.add(image);
panel3.add(word);
panel4.add(btnAddWord);
panel4.add(btnRestart);
panel4.add(btnHelp);
panel4.add(btnExit);
for(char i = 'A'; i <= 'Z'; i++){
String buttonText = new Character(i).toString();
JButton button = getButton(buttonText);
panel1.add(button);
}
}
public JButton getButton(final String text){
final JButton button = new JButton(text);
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
if(original.indexOf(button.getText())!=-1){
JOptionPane.showMessageDialog(null, "Your word does contain " + text );
}
else{
JOptionPane.showMessageDialog(null, "There is no " + text );
error++;
}
}
});
return button;
}
public String readWord(){
try{
BufferedReader reader = new BufferedReader(new FileReader("Words.txt"));
String line = reader.readLine();
List<String> words = new ArrayList<String>();
while(line != null){
String[] wordsLine = line.split(" ");
boolean addAll = words.addAll(Arrays.asList(wordsLine));
line = reader.readLine();
}
Random rand = new Random(System.currentTimeMillis());
String randomWord = words.get(rand.nextInt(words.size()));
return randomWord;
}catch (Exception e){
return null;
}
}
public void actionPerformed(ActionEvent e){
if(e.getSource() == btnAddWord){
try{
FileWriter fw = new FileWriter("Words.txt", true);
PrintWriter pw = new PrintWriter(fw, true);
String word = JOptionPane.showInputDialog("Please enter a word: ");
pw.println(word);
pw.close();
}
catch(IOException ie){
System.out.println("Error Thrown" + ie.getMessage());
}
}
if(e.getSource() == btnRestart){
}
if(e.getSource() == btnHelp){
String message = "The word to guess is represented by a row of dashes, giving the number of letters and category of the word."
+ "\nIf the guessing player suggests a letter which occurs in the word, the other player writes it in all its correct positions."
+ "\nIf the suggested letter does not occur in the word, the other player draws one element of the hangman diagram as a tally mark."
+ "\n"
+ "\nThe game is over when:"
+ "\nThe guessing player completes the word, or guesses the whole word correctly"
+ "\nThe other player completes the diagram";
JOptionPane.showMessageDialog(null,message, "Help",JOptionPane.INFORMATION_MESSAGE);
}
if(e.getSource() == btnExit){
System.exit(0);
}
}
public static void main (String [] args){
Hangman frame = new Hangman();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 600);
frame.add(panel1, BorderLayout.NORTH);
frame.add(panel2, BorderLayout.CENTER);
frame.add(panel3, BorderLayout.SOUTH);
frame.add(panel4, BorderLayout.SOUTH);
}
}
My first guess is that your text comparison is case sensitive.
"Dinosaur".indexOf("A") is not the same as "Dinosaur".indexOf("a")
I'd suggest converting the text to common case when you compare it.
original.toLowerCase().indexOf(button.getText().toLowerCase())!=-1
This is because you're not correctly checking whether the word that you're reading from the file is in the same case as the text in your JButton. There're a couple of ways to fix this:
As #MadProgrammer suggested. Have a couple of checks to cover both lowercase and uppercase characters.
Standardizing your List<String> words i.e. keep everything in one case when you're reading from the file. That way you don't have to worry much in terms of checking whether its in lowercase or uppercase. So in this case you might want to change: String[] wordsLine = line.split(" "); to String[] wordsLine = line.toLowerCase().split(" "); or String[] wordsLine = line.toUpperCase().split(" "); (depending on which one you're comfortable with). Then your check with a single indexOf() operation looks fine.
The below code is used to create a line graph. I am able to display the integers in the TextArea but i am not able to display the sentences above the integers in the text file. How do i rectify this program?
The screenshot of the text file is given below.
I want the first three lines of the text file also to be printed in the TextArea.
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.GridLayout;
import java.awt.event.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.WindowConstants;
import org.jfree.chart.*;
import org.jfree.chart.plot.*;
import org.jfree.data.xy.*;
public class Pio {
static JFrame frame1 = new JFrame("Graph");
static String URL = null;
static JTextArea txt = new JTextArea();
static JPanel panel = new JPanel();
public static void main(String[] args) throws IOException {
JButton but = new JButton("Open file");
![enter image description here][2]
panel.add(but);
frame1.add(panel, BorderLayout.WEST);
frame1.setVisible(true);
frame1.setSize(1000,400);
but.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
JFileChooser chooser = new JFileChooser();
int ret = chooser.showDialog(null, "Open file");
if (ret == JFileChooser.APPROVE_OPTION)
{
File file = chooser.getSelectedFile();
URL = file.getAbsolutePath();
}
File f = new File(URL);
FileReader inputF = null;
try {
inputF = new FileReader(f);
}
catch (FileNotFoundException e1) {
e1.printStackTrace();
}
BufferedReader in = new BufferedReader(inputF);
int[] a = new int[100];
int[] b = new int[100];
String s=null;
try {
s = in.readLine();
}
catch (IOException e1) {
e1.printStackTrace();
}
int i = 0;
while (s != null && i < 100)
{ // your arrays can only hold 1000 ints
String pair[] = s.split(" ");
a[i] = Integer.parseInt(pair[0]);
b[i] = Integer.parseInt(pair[1]);
i++; // don't forget to increment
try {
s = in.readLine();
}
catch (IOException e1) {
e1.printStackTrace();
}
}
try {
in.close();
}
catch (IOException e1) {
e1.printStackTrace();
}
System.out.println("the output of the file is " + f);
XYSeries data = new XYSeries("Line Graph");
int n = a.length;
for (int j = 0; j < n; j++) {
data.add(a[j], b[j]);
}
XYDataset xY = new XYSeriesCollection(data);
JFreeChart chart=ChartFactory.createXYLineChart(
"line graph",
"Cycles",
"Temperature",
xY,
PlotOrientation.VERTICAL,
true,
true,
true);
ChartPanel p=new ChartPanel(chart);
p.setVisible(true);
p.setLocation(100,100);
p.setSize(500,500);
frame1.add(p,BorderLayout.EAST);
}
});
}
}
there nothing about JTextArea, use constructor JTextArea(int rows, int columns)
put JTextArea to the JScrollPane, this JScrollPane put or the EAST or WEST area
put JPanel with JButton to the SOUTH or NORTH area
if ChartPanel doesn't returns any PrefferedSize (I doubt that), or this value isn't correct, then set for own PrefferedSize, put ChartPanel to the CENTER area
as you saw there any code line about setSize, JFrame has implemented BorderLayout in the API
use pack() instead of setSize()
setLocation() if required
last code lines in the ActionListener (your code logics) must be
frame.validate();
frame.repaint();
frame.pack();
in this form (your code logics) is Swing GUI during FileIO unresponsible for Mouse and Key Events, wrap FileIO to the Runnable#Tread or use SwingWorker for redirecting this long and hard task to the background task
create ChartPanel as local variable (as JFrame) and first code line in the ActionListener must be
.
frame.remove(ChartPanel);
Two display two componenets you can use a JSplitPane.
While loading data into your array append it to a JTextArea (area1 in the sample code)
final JTextArea area1 = new JTextArea();
...
area1.append("X=" + a[i] + " Y=" + b[i] + "\n");
Then rather than adding the chart to the frame add both the Chart and the TextArea to the JSplitPane
ChartPanel p = new ChartPanel(chart);
JSplitPane splitpane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
frame1.add( splitpane , BorderLayout.CENTER );
splitpane.add(p);
splitpane.add(area1);
pane.validate();
frame1.validate();
frame1.repaint();
To append data the the JTextArea use
area1.append("Creating a line graph\n");
area1.append("Selected file " + f + "\n");
while (s != null && i < 100) { // your arrays can only hold 1000 ints
String pair[] = s.split(" ");
try{
a[i] = Integer.parseInt(pair[0]);
b[i] = Integer.parseInt(pair[1]);
area1.append("X=" + a[i] + " Y=" + b[i] + "\n");
} catch (NumberFormatException e) {
area1.append(s + "\n");
}
try {
s = in.readLine();
i++; // don't forget to increment
} catch (IOException e1) {
e1.printStackTrace();
}
}
area1.append("Finished reading data\n");
...
In this example I'm assuming that the headder will fail parseInt and (if is does) appending the String s.