Why does this code work in Vista but not 7? - java

For some reason every time I have someone run this program in Vista it works flawlessly but as soon as I move it over to a Windows 7 PC it stops in the middle of the ActionListener's Action Performed Method meaning I can click my choices but it will never say size selected.
Is there any way to fix this?
import java.io.*;
import java.util.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class SizerFrame extends JFrame {
ButtonGroup buttons = new ButtonGroup();
JTextField width = new JTextField(2);
JTextField height = new JTextField(2);
double inchesPerTimeline = 2.1;
public SizerFrame()
{
super("Timeline Application");
Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
setBounds(screen.width/2-125,screen.height/2-90,250,180);
getContentPane().setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
int[] gridX = new int[]{0,0,0,0};
int[] gridY = new int[]{0,1,2,3};
int[] gridW = new int[]{1,1,2,5};
String[] titles = new String[]{"6\"","9\"","10\"","Custom"};
String[] actions = new String[]{"6","9","10","C"};
for (int a = 0; a < 4; a++)
{
JRadioButton current = new JRadioButton(titles[a]);
current.setActionCommand(actions[a]);
c.gridx = gridX[a];
c.gridy = gridY[a];
c.gridwidth = gridW[a];
buttons.add(current);
getContentPane().add(current,c);
}
c.gridwidth = 1;
String[] title = new String[]{" ","Width","Height"};
gridX = new int[]{9,10,12};
for (int a = 0; a< 3; a++)
{
c.gridx = gridX[a];
getContentPane().add(new JLabel(title[a]),c);
}
c.gridx = 11;
getContentPane().add(width,c);
c.gridx = 13;
getContentPane().add(height,c);
c.gridx = 11;
c.gridy = 0;
c.gridwidth = 2;
JButton button = new JButton("Done");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ButtonModel x = buttons.getSelection();
String size = "XXX";
System.out.println("Getting screen resolution");
int screenRes = Toolkit.getDefaultToolkit().getScreenResolution();
System.out.println("Successfully got screen resolution");
if (x!=null)
size = x.getActionCommand();
try{
TimeTable.width = new Integer(size)*screenRes;
TimeTable.height = (int)((TimeTable.titleCount+1)*inchesPerTimeline*screenRes);
}
catch(NumberFormatException ex)
{
try{
TimeTable.width = (int)(new Double(width.getText().trim())*screenRes);
TimeTable.height = (int)(new Double(height.getText().trim())*screenRes);
}
catch (NumberFormatException except)
{
return;
}
}
TimeTable.ready = true;
System.out.println("Size selected");
dispose();
}
});
getContentPane().add(button,c);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent winEvt){
System.exit(0);
}
});
setVisible(true);
}
}
Concise explanation :
I have a macro that runs out of Excel in Windows Vista and I tried to distribute it to a Computer running Windows 7. Upon execution the code failed to continue executing after this point i.e. it never printed out the words "Size selected". The rest of the program brings in a csv file from a C:\Users\?\AppData\TimeLineMacroProgram folder and later creates an image in the same directory. But this is the portion of the code that is currently broken. Whenever the GUI pops up I select the option for 9" and click done which should pass in 9 as a parameter and then print out "Size Selected" but it doesn't it only disposes the window. Please help.

Longshot guess:
There is an exit from your action listener if width and height text fields don't have content: you return after two NumberFormatExceptions. This would prevent "Size selected" from being displayed, and not dispose the frame. If you got the output "Successfully got screen resolution" and then it appeared to stop working, this could possibly be why. But if you experience that, and then click something else and then Done, it would print size selected.

Related

Java AWT controls issue

I'd like to create a calculator using Java AWT library, however I'm having problems putting a label and a textfield on the same row. Also, everything is mixing up. When I run the program, at first it shows 2 labels and 2 textfields on the same row, but if I resize it, the labels, buttons & textfields are one on top of another. Could you please help me?
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class Calculator extends Frame {
public static void main(String[] args) {
Frame frame= new Frame();
frame.setTitle("Mini Calculator App");
frame.setVisible(true);
frame.setSize(300,300);
LayoutManager gridBagLayout = new GridBagLayout();
frame.setLayout(gridBagLayout);
Label firstNumber = new Label("Add a number");
frame.add(firstNumber);
TextField numar1 = new TextField();
frame.add(numar1);
Label secondNumber = new Label("Add another number");
frame.add(secondNumber);
TextField numar2 = new TextField();
frame.add(numar2);
Choice operatie = new Choice();
operatie.add("+"); operatie.add("-");
operatie.add("*"); operatie.add("/");
frame.add(operatie);
Button calcul = new Button("Calculate");
frame.add(calcul);
Label result = new Label("Result is");
frame.add(result);
GridBagConstraints afisare;
afisare = new GridBagConstraints();
afisare.gridx = 0;
afisare.gridy = 0;
frame.add(firstNumber, afisare);
afisare = new GridBagConstraints();
afisare.gridx = 0;
afisare.gridy = 1;
afisare.gridwidth = 10;
afisare.gridheight = 10;
frame.add(numar1, afisare);
afisare = new GridBagConstraints();
afisare.gridx = 1;
afisare.gridy = 0;
frame.add(secondNumber, afisare);
afisare = new GridBagConstraints();
afisare.gridx = 1;
afisare.gridy = 1;
frame.add(numar2, afisare);
afisare = new GridBagConstraints();
afisare.gridx = 2;
afisare.gridy = 1;
frame.add(operatie, afisare);
afisare = new GridBagConstraints();
afisare.gridx = 4;
afisare.gridy = 0;
frame.add(result, afisare);
frame.addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
enter image description here
enter image description here

ScrollPane adding to grid layout

in my code I am calling a few items(my buttons with their names leading to different project. The names and everything are taken from a database)
I want a J ScrollPane to surround my buttons, what can I do? I just want the buttons to be called inside the scroll pane. Here is my code
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class AdminClass implements ActionListener {
ProjectButton[] buttons = new ProjectButton[35];
//Creating data field for unique Ids in the form of array list
ArrayList<Integer> uniqueIDList = new ArrayList<Integer>();
String[] projectNames;
int[] uniqueIds;
Connection conn1 = null;
Statement stmt1 = null;
JFrame frame = new JFrame("Admin Panel");
private JPanel panel = new JPanel();
JButton btnNewButton = new JButton("Add New Project");
public AdminClass() {
panel.setLayout(new GridLayout(10, 1));
panel.add(new JLabel("Welcome to Admin Panel"));
btnNewButton.addActionListener(this);
panel.add(btnNewButton);
panel.add(new JLabel("Existing Projects"));
conn1 = sqliteConnection.dbConnector();
try{
Class.forName("org.sqlite.JDBC");
conn1.setAutoCommit(false);
stmt1 = conn1.createStatement();
ResultSet rs1 = stmt1.executeQuery( "SELECT * FROM Project;" );
List<String> projectNameList = new ArrayList<String>();
while ( rs1.next() ){
int id = rs1.getInt("uniqueid");
String projectName = rs1.getString("name");
projectNameList.add(projectName);
uniqueIDList.add(id);
}
// Converting array list to array
projectNames = new String[projectNameList.size()];
projectNameList.toArray(projectNames);
uniqueIds = convertIntegers(uniqueIDList);
rs1.close();
stmt1.close();
conn1.close();
}
catch ( Exception e1 ) {
JOptionPane.showMessageDialog(null, e1);
}
// Adding buttons to the project
try{
for (int i = 0; i < projectNames.length; i++){
buttons[i] = new ProjectButton(projectNames[i]);
buttons[i].setId(uniqueIds[i]);
panel.add(buttons[i]);
buttons[i].addActionListener(this);
}
}
catch (Exception e2){
JOptionPane.showMessageDialog(null, e2);
}
frame.add(panel);
frame.setVisible(true);
frame.setSize(500, 500);
}
public void actionPerformed(ActionEvent e) {
for (int j = 0; j < buttons.length; j ++){
if (e.getSource() == buttons[j]){
AdminStatus sc = new AdminStatus(buttons[j].getId());
frame.dispose();
}
}
if (e.getSource() == btnNewButton){
frame.dispose();
WindowProjectAdmin wpa = new WindowProjectAdmin();
}
}
//Method to convert integar array list to integar array
public int[] convertIntegers(List<Integer> integers)
{
int[] ret = new int[integers.size()];
for (int i=0; i < ret.length; i++)
{
ret[i] = integers.get(i).intValue();
}
return ret;
}
}
This may seem very normal but it's really not, for some reason they are not visible or are not called inside a scroller. Please edit my code maybe?
Start by adding the buttons to their own container, this way you can control the layout of the buttons separately from the rest of the UI
JPanel panelFullOfButtons = new JPanel();
try {
for (int i = 0; i < projectNames.length; i++) {
buttons[i] = new ProjectButton(projectNames[i]);
buttons[i].setId(uniqueIds[i]);
panelFullOfButtons.add(buttons[i]);
buttons[i].addActionListener(this);
}
} catch (Exception e2) {
JOptionPane.showMessageDialog(null, e2);
}
Then add the "main" panel to the NORTH position of the frame and the "buttons" panel to the CENTER
frame.add(panel, BorderLayout.NORTH);
frame.add(new JScrollPane(panelFullOfButtons), BorderLayout.CENTER);
Mind you, in this case, I'd be very tempted to use something like a JList instead. See How to Use Lists for more details
I have done the same, can you tell me what's wrong?
// Problem #1...
JScrollPane pane = new JScrollPane();
pane.add(buttonPanel);
//...
// Problem #2...
panel.add(pane);
frame.add(panel);
These are competing with each other, moving the content around and overlapping with existing content...
public AdminClass() {
panel.setLayout(new GridLayout(3, 1));
panel.add(new JLabel("Welcome to Admin Panel"));
btnNewButton.addActionListener(this);
panel.add(btnNewButton);
panel.add(new JLabel("Existing Projects"));
List<String> projectNameList = new ArrayList<String>();
for (int index = 0; index < 1000; index++) {
projectNameList.add("Project " + index);
}
projectNames = projectNameList.toArray(new String[0]);
// Adding buttons to the project
buttons = new JButton[projectNameList.size()];
try {
for (int i = 0; i < projectNames.length; i++) {
buttons[i] = new JButton(projectNames[i]);
btnPnl1.add(buttons[i]);
buttons[i].addActionListener(this);
}
} catch (Exception e2) {
JOptionPane.showMessageDialog(null, e2);
}
frame.add(panel, BorderLayout.NORTH);
frame.add(new JScrollPane(btnPnl1), BorderLayout.CENTER);
frame.setVisible(true);
frame.setSize(500, 500);
}
In this case I'd prefer to use either a JList to show the projects or a WrapLayout for laying out the buttons
Its useless to create a GridLayout like this: panel.setLayout(new GridLayout(10, 1));. If you declare the rows as a non zero value, the column count will be ignored. When you declare the maximum number of rows as ten, you force the eleventh component to be added in a second column (then a third, a forth and so on). Use panel.setLayout(new GridLayout(0, 1)); instead to force the only one column and frame.add(new JScrollPane(panel)); to create the ScrollPane.
But note that GridLayout will try to shrink your components the maximum as possible to fit the container size before scrolling is enabled.
I just want the button part to be inside J Scroll Pane
If you just want the JButton's (those added within the loop):
Create a new JPanel that you add the buttons to
Add (1) to a JScrollPane
Add (2) to panel
For example:
JPanel buttonPanel = new JPanel(new FlowLayout());
for (int i = 0; i < projectNames.length; i++){
buttons[i] = new ProjectButton(projectNames[i]);
buttons[i].setId(uniqueIds[i]);
panel.add(buttons[i]);
buttonPanel[i].addActionListener(this);
}
JScrollPane scroller = new JScrollPane(buttonPanel);
panel.add(scroller);
You might also consider using a different Component that doesn't require a JScrollPane, of course depending upon your needs - for instance a JComboBox.

JRadioButtons before every line

I have this program that reads questions with multiple choice answers from a text file and then displays a random set of them in a JOptionPane (very question in a new Pane). In my text file the questions and the 4 options of answers are all in one line and then I divide them into new lines. Now I want to try to add JRadioButtons before every single answer. Is there someone who can help me. Thank you very much in advance. Here is my code:
Random random = new Random();
for (int i = 0; i < newRanQues; i++) {
int randIndex = random.nextInt(32) + 0;
String randomQuestion = questions.get(randIndex);
randomQuestions.add(randomQuestion);
String different = randomQuestion.replaceAll(";", "\n");
{
JOptionPane.showMessageDialog(null, different, "Question", JOptionPane.INFORMATION_MESSAGE);
JRadioButton answerA = new JRadioButton("A) " + answer[0]);
JRadioButton answerB = new JRadioButton("B) " + answer[1]);
JRadioButton answerC = new JRadioButton("C) " + answer[2]);
JRadioButton answerD = new JRadioButton("D) " + answer[3]);
ButtonGroup group = new ButtonGroup();
group.add(optionA);
group.add(optionB);
group.add(optionC);
group.add(optionD);
return;
}
This should do it:
import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
public class RadioButtonExample {
public static void main(String[] args) {
init();
}
private static void init() {
// create the jframe
JFrame jframe = new JFrame("Question");
// create the answers
String[] answer = { "red", "green", "yellow", "blue, no, red, no... arrrrrg" };
// create the radio buttons
JRadioButton answerA = new JRadioButton("A) " + answer[0]);
JRadioButton answerB = new JRadioButton("B) " + answer[1]);
JRadioButton answerC = new JRadioButton("C) " + answer[2]);
JRadioButton answerD = new JRadioButton("D) " + answer[3]);
// create the button group
ButtonGroup group = new ButtonGroup();
group.add(answerA);
group.add(answerB);
group.add(answerC);
group.add(answerD);
// add the question to the jframe
jframe.add(new JLabel("What is your favorite colour?"), BorderLayout.NORTH);
// create gridbag layout and constraints
GridBagLayout gbl = new GridBagLayout();
// create the panel using the gbl
JPanel pan = new JPanel(gbl);
// create the constraints
GridBagConstraints cons = new GridBagConstraints();
cons.gridwidth = 1;
cons.fill = GridBagConstraints.HORIZONTAL;
// answer 1
cons.gridx = 0;
cons.gridy = 1;
pan.add(answerA, cons);
// answer 1
cons.gridx = 0;
cons.gridy = 2;
pan.add(answerB, cons);
// answer 1
cons.gridx = 0;
cons.gridy = 3;
pan.add(answerC, cons);
// answer 1
cons.gridx = 0;
cons.gridy = 4;
pan.add(answerD, cons);
// add the panel to the jframe
jframe.add(pan, BorderLayout.CENTER);
// show the jframe
jframe.setSize(400, 400);
jframe.setVisible(true);
}
}

Displaying an array of Strings in a JTextArea

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...

Java JTree freezing when file is re-selected

I have a JTree that I use as a file tree. If I choose a new file, and select the same one as was already selected, the tree freezes up for some reason. It should be removing the old JScrollPane containing the tree and replacing it with a new one, and it works fine if I select a different file, but not with the same one. The rest of the GUI still works, it's just the tree that freezes. Here is the relevant code:
if ("browse".equals(e.getActionCommand())) {
returnVal = fc.showOpenDialog(DSAuto.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
filename = file.getAbsolutePath();
l1.setText("Job Location: " + filename);
c.fill = GridBagConstraints.BOTH;
c.weightx = 1.0;
c.gridx = 0;
c.gridy = 1;
c.gridwidth = 10;
c.gridheight = 9;
c.ipady = 0;
if (rm)
pane.remove(ft1);
else
pane.remove(sp1);
if (rm2) {
pane.remove(l3);
rm2 = false;
}
if (!(file.isDirectory() || file.isFile())) {
l3 = new JLabel("404 File Not Found");
pane.add(l3, c);
rm2 = true;
} else {
ft1 = new FileTree(file);
ft1.all = allB;
pane.add(ft1, c);
rm = true;
}
}
}
I can supply the code for the FileTree class, as well, if that is needed.
It should be removing the old frame and replacing it with a new one
You can't add/remove a JFrame from a JFrame so I don't know what that comment means.
Don't remove/add components? If you want to update an existing component then change the model. That is:
tree.setModel(...);
Or if you do remove/add components, then you need to use:
panel.revalidate();
panel.repaint();

Categories