I am making a GUI in which i have 6 combo boxes, i read data from a text file to these
combo boxes. My text file has 3 rows and 2 columns, so when i read data only my first 2 combo boxes is getting populated with data that to with the values of the 3rd row of the text file instead of the 1st row and the remaining combo boxes remains empty.As my text file contains 6 values it should display in the 6 combo boxes.Please help
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.util.*;
public class Read extends JPanel {
public Read() {
JPanel buttonPanel = new JPanel();
add(buttonPanel);
buttonPanel.setLayout(new GridLayout(0, 2, 5, 5));
JComboBox comboBox1 = new JComboBox();
comboBox1.addItem("1");
comboBox1.addItem("2");
comboBox1.addItem("4");
JComboBox comboBox2 = new JComboBox();
comboBox2.addItem("1");
comboBox2.addItem("2");
comboBox2.addItem("4");
JComboBox comboBox3 = new JComboBox();
comboBox3.addItem("1");
comboBox3.addItem("2");
comboBox3.addItem("4");
JComboBox comboBox4 = new JComboBox();
comboBox4.addItem("1");
comboBox4.addItem("2");
comboBox4.addItem("4");
JComboBox comboBox5 = new JComboBox();
comboBox5.addItem("1");
comboBox5.addItem("2");
comboBox5.addItem("4");
JComboBox comboBox6 = new JComboBox();
comboBox6.addItem("1");
comboBox6.addItem("2");
comboBox6.addItem("4");
buttonPanel.add(comboBox1);
buttonPanel.add(comboBox2);
buttonPanel.add(comboBox3);
buttonPanel.add(comboBox4);
buttonPanel.add(comboBox5);
buttonPanel.add(comboBox6);
try{
InputStream ips=new FileInputStream("tl.txt");
InputStreamReader ipsr=new InputStreamReader(ips);
BufferedReader br=new BufferedReader(ipsr);
String line;
while ((line=br.readLine())!=null) {
String[] s = line.split(" ");
comboBox1.setSelectedItem(s[0]);
comboBox2.setSelectedItem(s[1]);
}
br.close();
}
catch (Exception e){
e.printStackTrace();
}
}
public static void main(String[] args) {
Read a = new Read();
JFrame f = new JFrame("");
f.getContentPane().add(a);
f.setSize(300,200);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
f.setVisible(true);
}
}
text file
2 4
1 2
4 1
Declare a JCombobox array and store all your JCombobox in the array as below,
JComboBox[] comboBoxs = new JComboBox[6];
comboBoxs[0] = comboBox1;
comboBoxs[1] = comboBox2;
comboBoxs[2] = comboBox3;
comboBoxs[3] = comboBox4;
comboBoxs[4] = comboBox5;
comboBoxs[5] = comboBox6;
Declare a Arraylist and store the data which you read from the file as below,
// Other code goes here.
ArrayList<String> list = new ArrayList<String>();
String line;
while ((line=br.readLine())!=null) {
String[] s = line.split(" ");
list.add(s[0]);
list.add(s[1]);
}
br.close();
Finally loop over each Arraylist and populate the Combobox's.
for(int i = 0; i < comboBoxs.length; i++) {
comboBoxs[i].setSelectedItem(list.get(i));
}
This should do good.
Please look at your code, you are filling data only to combobox 1 and 2, other comboboxes you are not filling any data.
If you want data in other compoboxes, fill them as well in the while loop.
Hope this helps.
thanks
public class Read extends JPanel{
String[] values=new String[6];
JCombobox<String>[] combos=new JCombobox<String>[6];
public Read() {
//Do your layout initialization operations here
this.initCombo();
//Put the logic to add the comboboxes to the UI here
}
public void intiCombo(){
try{
ArrayList<String> tmp=new ArrayList<String>();
InputStream ips=new FileInputStream("tl.txt");
InputStreamReader ipsr=new InputStreamReader(ips);
BufferedReader br=new BufferedReader(ipsr);
String line;
while ((line=br.readLine())!=null) {
String[] s = line.split(" ");
tmp.add(s[0]);
tmp.add(s[1]);
}
br.close();
}
catch (Exception e){
e.printStackTrace();
}
values=tmp.toArray(new String[1]);
for(int i=0;i<conbos.length;i++)combos[i]=new JCombobox(values);
}
//Your main method comes here
}
Related
I need to some help about JTable.I'm trying to read data from "Contact.txt" file and populate my table with that datas.I can get data from file correctly with adding to Object[][] 2D array without any problem.When I try to add this Object array to table not happens any thing.
Sorry for my bad English.
Contacts.txt file include "Name","LastName","Phone Num","Email" s.
And this Class read the text and add it to Object :
public class ReadFromText {
public boolean ReadTable(Object [][] data) {
boolean status = false;
File file = new File("/Users/MacbookPro/Documents/Contacts.txt");
BufferedReader bf = null;
FileReader fileReader = null;
try {
fileReader = new FileReader(file);
bf = new BufferedReader(fileReader);
String textLine = null;
String [] text = null;
for (int i = 0; i < data.length; i++) {
for (int j = 0; j < 4; j++) {
while ((textLine = bf.readLine()) != null) {
text = textLine.split(" ");
data[i][j] = text[j];
status = true;
System.out.println(data[i][j]);
}
}
}
bf.close();
} catch (IOException e) {
System.err.println(e.getMessage());
}
return status;
}
}
This part of code from main Class :
Object [][]datas = new Object[10][4];
ReadFromText r = new ReadFromText(); //new object from ReadData class
if(r.ReadTable(datas)== true){
System.out.println("OK");//just for to be sure
}else{
System.out.println("NO");
}
model = new DefaultTableModel(datas, columNames);
table = new JTable(model);
table.setFont(new Font("Monospaced", Font.PLAIN, 13));
table.setBackground(new Color(245, 245, 245));
table.setRowHeight(25);
table.setMinimumSize(new Dimension(60, 20));
table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
It' return "OK" check it from here
But JTable is empty !!! : look it from this picture
I hope to anyone can help me.THANKS FOR ALL
Your code to read the data from the file is wrong. Think about it for a minute. You start the outer loop with a value of 0, then you have you inner loop with a value of 0 and then you read the entire file using the while loop.
You want your logic to read a single line of data, split that line and add then add the data to the array. So the logic should be something like:
int row = 0;
while ((String textLine = bf.readLine()) != null)
{
String text = textLine.split(" ");
for (int i = 0; i < text.length; i++)
{
data[row][i] = text[i];
}
row++
}
However, you should NOT be using Arrays to hold the data. You should never hardcode the size of a data structure since it does not allow you to add new data. Instead you should be using a Vector to read the data. Then it doesn't matter is you have 10 rows of data or 100.
Using this approach the code would be something like:
Vector data = new Vector();
while ((String textLine = bf.readLine()) != null)
{
String text = textLine.split(" ");
Vector row = new Vector();
for (int i = 0; i < text.length; i++)
{
row.addElement( text[i] );
}
}
So you would need to change the method to return the Vector of data. You would also need to change your "columnNames" to be added to a Vector so you can create the TableModel using the two Vectors.
I hope this answer will help you find the problem. It is also meant to demonstrate the importance of posting an MCVE, like the following:
mport java.awt.Color;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class TestTable extends JFrame {
public TestTable() {
super("Main");
setSize(400, 300);
Object [][]datas = new Object[][]{
{"A1", "A2","A3","A4"},
{"B1", "B2","B3","B4"}
};
Object[] columNames = {"Name","LastName","Phone Num","Email"};
DefaultTableModel model = new DefaultTableModel(datas, columNames );
JTable table = new JTable(model);
table.setBackground(new Color(245, 245, 245));
table.setRowHeight(25);
table.setMinimumSize(new Dimension(60, 20));
table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
add(new JScrollPane(table));
setVisible(true);
}
public static void main(String[] args) {
new TestTable();
}
}
Not only an MCVE helps you get better and faster response, in many cases, like this one, it helps you pin point the problem and solve it by yourself.
Removing everything that is not essential to reproduce the problem, help you (and who ever tries to help) focus on where the problem is.
In this case you can see that eliminating the input part, you can see that the JTable works fine.
i've been stuck on getting one of my JTextArea's to display an array of Strings that represent letters in a word in a hangman game. Once the user guesses a letter, (assuming it's right), it should reflect into the array. Instead, it seems to be only adding the letter that was guessed, and not the blanks or the rest of the array. I want to set the guessed letter equal to the correct index in the array and then have it shown on the screen. Here is my code:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Random;
#SuppressWarnings("serial")
public class GuiClass extends JFrame {
char guess = ' ';
int numGuesses = 0;
char[] letterGuessedAgainst = null;
String wordInPlay = " ";
String[] hangmanScores = null;
ArrayList<Character> wrongGuesses = null;
boolean isGuessSuccessfull = false;
private Container contents;
JRadioButton rbEasy;
JRadioButton rbHard;
ButtonGroup difficultyGroup;
JTextField txtfldWord;
JTextArea txtareaWord;
JLabel difficultyPrompt;
JLabel userDifficulty;
JButton btnStartGame;
JButton btnGuessSubmit;
JButton btnWordGuessSubmit;
JPanel topPanel;
JPanel midPanel;
JLabel topLabel;
JPanel guessPanel;
JPanel letterPanel;
JLabel word;
JTextArea txtareaNumGuesses;
JTextField txtfldGuess;
JTextField txtfldWordGuess;
JTextArea txtareaguessedLetters;
JTextArea txtareaLettersLeft;
public GuiClass(){
super("Hangman GUI");
contents = getContentPane();
//create a new panel & set layout
midPanel = new JPanel();
midPanel.setLayout(new GridLayout(3,3));
//layout manager
topLabel = new JLabel("Welcome to Hangman!");
contents.setLayout(new FlowLayout());
//create new ButtonHandlers
ButtonHandler buttonHandler = new ButtonHandler();
ButtonHandler2 btnHndlrNewGame = new ButtonHandler2();
//create difficulty buttons/labels & add ActionListeners
difficultyPrompt = new JLabel("First, Choose A Difficulty:");
rbEasy = new JRadioButton("Easy");
rbHard = new JRadioButton("Hard");
userDifficulty = new JLabel("Game Difficulty: ");
difficultyGroup = new ButtonGroup();
difficultyGroup.add(rbEasy);
difficultyGroup.add(rbHard);
rbEasy.addItemListener(buttonHandler);
rbHard.addItemListener(buttonHandler);
midPanel.add(topLabel);
midPanel.add(difficultyPrompt);
midPanel.add(rbEasy);
midPanel.add(rbHard);
midPanel.add(userDifficulty);
topPanel = new JPanel();
JLabel btnStartNewGame = new JLabel("Next, Start a new game!");
btnStartGame = new JButton("Start A New Game");
btnStartGame.addActionListener(btnHndlrNewGame);
topPanel.add(btnStartNewGame);
topPanel.add(btnStartGame);
guessPanel = new JPanel();
JLabel lblGuess = new JLabel("Guess: ");
JLabel lblWordGuess = new JLabel("Word Guess: ");
btnGuessSubmit = new JButton("Submit");
btnGuessSubmit.addActionListener(btnHndlrNewGame);
btnWordGuessSubmit = new JButton("Submit");
btnGuessSubmit.addActionListener(btnHndlrNewGame);
txtfldGuess = new JTextField(10);
txtfldWordGuess = new JTextField(10);
guessPanel.add(lblGuess);
guessPanel.add(txtfldGuess);
guessPanel.add(btnGuessSubmit);
guessPanel.add(lblWordGuess);
guessPanel.add(txtfldWordGuess);
guessPanel.add(btnWordGuessSubmit);
letterPanel = new JPanel();
JLabel lblGuessedLetters = new JLabel("Guessed Letters:");
JLabel lblLettersInWord = new JLabel("Letters Left:");
JLabel lblNumGuesses = new JLabel("Guess Number: ");
txtareaNumGuesses = new JTextArea(5,5);
txtareaNumGuesses.setEditable(false);
txtareaguessedLetters = new JTextArea(5,15);
txtareaguessedLetters.setEditable(false);
txtareaLettersLeft = new JTextArea(5,15);
txtareaLettersLeft.setEditable(false);
letterPanel.add(lblGuessedLetters);
letterPanel.add(txtareaguessedLetters);
letterPanel.add(lblLettersInWord);
letterPanel.add(txtareaLettersLeft);
letterPanel.add(lblNumGuesses);
letterPanel.add(txtareaNumGuesses);
JPanel wordPanel = new JPanel();
word = new JLabel("Word is: ");
//txtfldWord = new JTextField(10);
txtareaWord = new JTextArea(20,20);
//txtfldWord.setEditable(false);
txtareaWord.setEditable(false);
wordPanel.add(word);
//wordPanel.add(txtfldWord);
wordPanel.add(txtareaWord);
//add contents of panels to the container
contents.add(midPanel);
contents.add(topPanel);
contents.add(guessPanel);
contents.add(letterPanel);
contents.add(wordPanel);
setSize(800,600);
setVisible(true);
}//end constructor
private class ButtonHandler implements ItemListener{
public void itemStateChanged(ItemEvent ie){
if (ie.getSource()==rbEasy){
userDifficulty.setText("Game Difficulty: Easy");
}//end if
if (ie.getSource()==rbHard){
userDifficulty.setText("Game Difficulty: Hard");
}//end if
}//end method
}//end ButtonHandler inner class
private class ButtonHandler2 implements ActionListener{
public void actionPerformed(ActionEvent ae){
if (ae.getSource()==btnStartGame){
if (rbEasy.isSelected()){
ArrayList<String> easyHmWords = new ArrayList<String>();
String filename = "easyhangmanwords.txt";
BufferedReader infile = null;
try {
infile = new BufferedReader(new FileReader(filename));
}//end try
catch (FileNotFoundException e) {
e.getMessage();
}//end catch
String re = "";
try {
while ((re=infile.readLine())!=null){ // reading one line
easyHmWords.add(re);
}//end while
System.out.println("words in file: "+easyHmWords);
}//end try
catch (IOException e) {
e.getMessage();
}//end while
try {
infile.close();
}//end try
catch (IOException e) {
e.getMessage();
}//end catch
wordInPlay = "";
int randomNumber = 0;
Random rand = new Random();
int maxRandomNumber = 0;
word.setText("Word is: Set");
//System.out.println("Okay, the word is set!");
maxRandomNumber = easyHmWords.size();
System.out.println("Size of arraylist: "+easyHmWords.size());
randomNumber = rand.nextInt(maxRandomNumber);
System.out.println("random num: "+randomNumber);
wordInPlay = easyHmWords.get(randomNumber);
System.out.println("word in play: "+wordInPlay);
//figures out how many letters the word has
int lettersInWord = wordInPlay.length();
System.out.println("Letters in word: "+lettersInWord);
//creates an array of hangman scores which is the size of the letters in the word
hangmanScores = new String[lettersInWord];
//for loop to iterate through the array and assign "_" to the spaces
for (int i = 0; i < hangmanScores.length; i++) {
hangmanScores[i] = " _ ";
}//end for
for (int i = 0; i < hangmanScores.length; i++){
//txtareaWord.setText(hangmanScores[i]);
//txtfldWord.append(hangmanScores[i]);
txtareaWord.append((hangmanScores[i]));
}//end for
}//end if
}//end if
if(btnGuessSubmit == ae.getSource()){ //getting problems in this if statement
guess = txtfldGuess.getText().charAt(0);
letterGuessedAgainst = wordInPlay.toCharArray();
for (int i = 0; i < letterGuessedAgainst.length; i++) {//goes through the letters of the word in play
***if(letterGuessedAgainst[i]==guess){//if a letter matches up,
hangmanScores[i] = Character.toString(guess);
isGuessSuccessfull = true;
}//end if
}//end for
for (int k =0; k < hangmanScores.length; k++){//displays the ______ in the text area
txtareaWord.setText((hangmanScores[k]));***
System.out.print(hangmanScores[k]);//testing purposes
}//end for
numGuesses++;
txtareaNumGuesses.setText(" "+numGuesses);
}//end for
if(isGuessSuccessfull = false){
wrongGuesses.add(guess);
txtareaguessedLetters.append(wrongGuesses+"");
}//end if
}//end method
}//end private inner class
public static void main (String[] args){
GuiClass estGUI = new GuiClass();
estGUI.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}//end main method
}//end class
this is the part of the code that doesn't display the correct parts of the array:
***if(letterGuessedAgainst[i]==guess){//if a letter matches up,
hangmanScores[i] = Character.toString(guess);
isGuessSuccessfull = true;
}//end if
}//end for
for (int k =0; k < hangmanScores.length; k++){
txtareaWord.setText((hangmanScores[k]));***
Basically, you are calling setText every time you want to add a new character to the JTextArea in question, this is, first, clearing any existing text and then adding the new String, which, in this case, is the last thing you entered.
There are a few ways you could fix this, but because you want to remove the existing text first and then replace it, it's probably better to build a buffer of what you want and apply it all in a single step...
StringBuilder sb = new StringBuilder(hangmanScores.length);
for (int k = 0; k < hangmanScores.length; k++) {//displays the ______ in the text area
sb.append(hangmanScores[k]);
System.out.print(hangmanScores[k]);//testing purposes
}//end for
txtareaWord.setText(sb.toString());
You also seem to have attached multiple ActionListeners to your button, as each time I clicked it, it counted for two guesses...
I have a code that reads a multiple text files from a folder and I need to put them in a table.So far,everything is good except that every line from my text files are displayed in a different table.I know that the problem is that the table receives each line separately.I tried to create an object and fill it and then call inside the table but I couldn't make it work so if anyone can tell me the solution that would be great. Also I need to be able to compare the values and find an average,so if you have any tips for that to,would be great
here's an example of my text file
17/10/2012 10:00:06.67 [RX] - E usbR<LF>
817EE765FF53-53<LF>
817AA765FF53-34<LF>
817CC765FF53-25<LF>
00<LF>
E qEnd<LF>
and this is what I need to get in the table
ID RSSI
817EE765FF53 53
817AA765FF53 34
817CC765FF53 25
here is the code
import java.awt.BorderLayout;
import java.io.*;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
public class Foldersearch1
{
public static void main(String[] args)
{
// Directory path here
String path = "C:/Users/Nikica/Desktop/text files";
String files;
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++)
{
if (listOfFiles[i].isFile())
{
files = listOfFiles[i].getName();
if (files.endsWith(".txt") || files.endsWith(".TXT"))
{
System.out.println(files);
();
String currentLine="";
File textFile = new File(folder.getAbsolutePath() + File.separator + files);
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream(textFile);
try (DataInputStream in = new DataInputStream(fstream)) {
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
String line;
//Read File Line By Line
// int p=0;
// Object[][] Table=null;
while ((strLine = br.readLine()) != null) {
processLine(strLine);
Table(strLine);
// Print the content on the console
//System.out.println (strLine);
}
}
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
}
}
public static void processLine(String line) {
// skip header & footer
if (line.startsWith("17/10/2012 10:00:06.67 [RX] - E usbR<LF>") || line.startsWith("E qEnd<LF>")) {return;}
String ID = line.substring(0, 12);
String RSSI = line.substring(13, 15);
System.out.println("ID [" + ID + "]\t RSSI [" + RSSI +"]");
}
public static void Table(String line) {
JFrame frame = new JFrame("proba");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
if (line.startsWith("17/10/2012 10:00:06.67 [RX] - E usbR<LF>") || line.startsWith("E qEnd<LF>")) return;
String ID = line.substring(0, 12);
String RSSI = line.substring(13, 15);
Object rowData[][] = { { ID, RSSI } };
Object columnNames[] = { "ID", "RSSI" };
JTable table = new JTable(rowData, columnNames);
JScrollPane scrollPane = new JScrollPane(table);
frame.add(scrollPane, BorderLayout.CENTER);
frame.setSize(300, 150);
frame.setVisible(true);
}
}
To make your code work with minimal changes, Create a Vector with the rowdata, and use the constructor public JTable(Vector rowData, Vector columnNames). The following code snippet should give you an idea on how to do it.
Vector<String> columnNames = new Vector<String>();
columnNames.add("ID");
columnNames.add("RSSI");
Vector<Vector<String>> rowData = new Vector<Vector<String>>();
for(int i=0; i<20; i++) {
Vector<String> row = new Vector<String>();
row.add("ID_" + i);
row.add("RSSI_" + i);
rowData.add(row);
}
JTable table = new JTable(rowData, columnNames);
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.