2013-10-27 7 views
-1

Я обнаружил, что мой код не обновляет текст в JTextArea. Я создаю рамку и добавляю пару панелей. Одна из панелей содержит мою JTextArea. Первоначально я устанавливаю как "". Затем позже нажатием кнопки, среди другого кода, я обновляю JTextArea. Однако обновление не отображается на экране.Текст в JTextArea не обновляется

Вот фрагменты моего кода:

static JFrame window = new JFrame("Valedictorian Voting System"); 
static JTextArea voteNotification = new JTextArea(" "); 

static JPanel options = new JPanel(); 
static JPanel options1 = new JPanel(); 
static JPanel options2 = new JPanel(); 

Тогда в моих главных():

ImageIcon header; 
ImageIcon side; 
ImageIcon side2; 
Image image = new ImageIcon("src\\Header_MICHS.jpg").getImage();  
header = new ImageIcon(image.getScaledInstance(290, 55, java.awt.Image.SCALE_SMOOTH)); 
Image image2 = new ImageIcon("src\\lightningbolt2.png").getImage() ;  
side = new ImageIcon(image2.getScaledInstance(50, 235, java.awt.Image.SCALE_SMOOTH)); 
Image image3 = new ImageIcon("src\\lightningbolt.png").getImage() ; 
side2 = new ImageIcon(image3.getScaledInstance(50, 235, java.awt.Image.SCALE_SMOOTH)); 
JLabel sideLabel2 = new JLabel(side2); 
JLabel sideLabel = new JLabel(side); 
JLabel headerLabel = new JLabel(header); 

//bottom bar add - the text field and Jbutton 
JPanel studentInfo = new JPanel(); 
studentInfo.setLayout(new GridLayout(1,2)); 
studentInfo.add(studentNumber); 
studentInfo.add(studentNumButton); 



//add the val radio buttons to a panel 
JPanel options1 = new JPanel(); 
options1.setLayout(new GridLayout(val2.length,0)); 
for(int i=0; i<val2.length;i++){ 
    options1.add(val2[i]); 
} 

//add the message box to a panel 

options2.setLayout(new GridLayout(1,0)); 
options2.setBackground(Color.WHITE); 
options2.add(voteNotification); 


//add the panels to a panel 

options.setLayout(new GridLayout(1,2)); 
options.add(options1); 
options.add(options2); 

//put the functional things into one panel 
JPanel setup = new JPanel(); 
setup.setLayout(new BorderLayout()); 
setup.add(options, BorderLayout.CENTER); 
setup.add(studentInfo, BorderLayout.SOUTH); 

//put the pictures around the functional things 
JPanel content = new JPanel(); 
content.setLayout(new BorderLayout()); 
content.add(setup, BorderLayout.CENTER); 
content.add(headerLabel, BorderLayout.NORTH); 
content.add(sideLabel, BorderLayout.EAST); 
content.add(sideLabel2, BorderLayout.WEST); 


window.setLayout(new BorderLayout()); 
window.add(content, BorderLayout.CENTER); 
window.setContentPane(content); 
window.setSize(300,310); 
window.setLocation(550,250); 
window.setVisible(true); 
window.setResizable(false); 

Это все работает. Но когда я нажимаю кнопку «Проголосовали» ... все работает, кроме JTextArea, не обновляется.

public static boolean checkSelected(){ 
    stillVotable = checkNum(); 
    boolean selected = false; 
    for(int i = 0; i<numVals; i++){ 
    if(val2[i].isSelected() && stillVotable==true){ 
     votes[i] +=1; 

     voteNotification.setText("Student No.: " + studentNumber.getText() + " voted for: " + val.get(i)); 
     options2.repaint(); 



     System.out.println("Voted for " + val.get(i) + ":" + votes[i]); 
     selected = true; 
     checkWinner();//checks to see if someone won 
     return true; 
     } 
    } 
    if(selected==false && stillVotable==true) 
     JOptionPane.showMessageDialog(null, "You have not selected a Valedictorian!"); 
    else 
     selected=false; 
    return false; 
    } 

Я беспокоюсь, что он должен делать с резьбой, как я не понял описания в некоторых других постах ...

Вот весь код:

import java.awt.*; 
import java.awt.event.*; 
import java.io.*; 
import java.util.*; 
import javax.swing.*; 
public class StandaloneGUIVotingSystem/* extends JApplet*/{ 

    static JFrame window = new JFrame("Valedictorian Voting System"); 
    static HintTextField studentNumber = new HintTextField("Enter student #!"); 
    static JTextArea voteNotification = new JTextArea("This is where your confirmation message will show up."); 
    static ButtonGroup studentGroup; 
    static JRadioButton[] val2; 
    static int[] votes; 

    static JPanel options = new JPanel(); 
    static JPanel options1 = new JPanel(); 
    static JPanel options2 = new JPanel(); 

    static CreateFile creator = new CreateFile(); 
    static FileHandling fileH = new FileHandling(); 

    static int studentsVoting = 0; 
    static int numVals = 0; 
    static int studentsVoted = 0; 
    static boolean stillVotable = false; 
    static String filePath = "src//"; 

    static DynamicArrayOfString studentNum = new DynamicArrayOfString(); 
    static DynamicArrayOfString val = new DynamicArrayOfString(); 

    //Window window; applet stuff 

    //checks the student number entered to confirm a valid vote from a student that has not voted 


    public static boolean checkNum(){ 
    for(int i = 0; i<studentNum.size(); i++){ 
     if(studentNumber.getText().equals(studentNum.get(i))){ 
     return true; 
     } 
    } 
    JOptionPane.showMessageDialog(null, "This is not a valid student number. Please enter a different one!"); 
    return false; 
    } 

    //checks to see if the user has selected a radio button 


    public static boolean checkSelected(){ 
    stillVotable = checkNum(); 
    boolean selected = false; 
    for(int i = 0; i<numVals; i++){ 
     if(val2[i].isSelected() && stillVotable==true){ 
     votes[i] +=1; 

     voteNotification.setText("Student No.: " + studentNumber.getText() + " voted for: " + val.get(i)); 
     options2.repaint(); 



     System.out.println("Voted for " + val.get(i) + ":" + votes[i]); 
     selected = true; 
     checkWinner();//checks to see if someone won 
     return true; 
     } 
    } 
    if(selected==false && stillVotable==true) 
     JOptionPane.showMessageDialog(null, "You have not selected a Valedictorian!"); 
    else 
     selected=false; 
    return false; 
    } 

    //resets the screen for the next user 


    public static void clear(){ 
    studentNumber.setText(""); 
    studentGroup.clearSelection(); 
    studentNumber.showHint(); 
    voteNotification.setText(""); 
    } 

    public static void write(){ 
    //write winner file 
    CreateFile.openFile("Winner.txt"); 
    CreateFile.addToFile("The Results of the Voting Contest are:"); 
    for(int i = 0; i < val.size(); i++){ 
     CreateFile.addToFile(val.get(i) + " has " + votes[i] + " votes."); 
    } 
    CreateFile.closeFile(); 

    //write voter file 
    CreateFile.openFile("Voters.txt"); 
    for(int i = 0; i < studentNum.size(); i++){ 
     CreateFile.addToFile(studentNum.get(i)); 
    } 
    CreateFile.closeFile(); 
    } 

    //removes the person who voted from the text file so they can only vote once 
    public static void removeVoted(){ 
    for(int i = 0; i < val.size(); i++){ 
     if(studentNumber.getText().equals(studentNum.get(i))){ 
     studentNum.remove(i); 
     studentsVoted++; 
     } 
    } 
    } 

    //checks if there is a winner and finishes program if there is 
    public static void checkWinner(){ 

    if (studentsVoted == studentsVoting){ 
     int j=0; 
     int largest = votes[0]; 
     for(int i = 1; i < votes.length; i++){ 
     if(votes[i] > largest){ 
      largest = votes[i]; 
      j = i; 
     } 
     } 
     CreateFile.openFile("Winner.txt"); 
     CreateFile.addToFile("The Results of the Voting Contest are:"); 
     for(int i = 0; i<val.size();i++){ 
     CreateFile.addToFile(val.get(i) + " has " + votes[i] + " votes."); 
     } 
     CreateFile.addToFile("\n"); 
     CreateFile.addToFile("Therefore, the winner is..."); 
     CreateFile.addToFile(""); 
     CreateFile.addToFile(""); 
     CreateFile.addToFile(""); 
     CreateFile.addToFile(val.get(j) + " wins!"); 
     CreateFile.closeFile(); 
     System.exit(0); 
    } 
    } 

    //retrieves the initial information 
    public static void retrieve(){ 
    //takes the student numbers and adds them to the dynamic array called studentNum 
    fileH.openFile("Voters.txt"); 
    fileH.readFile(); 
    studentsVoting = fileH.length(); 
    for(int i = 0; i<studentsVoting;i++){ 
     studentNum.put(i, fileH.get(i)); 
    } 
    fileH.closeFile(); 

    //gets the valedictorian names and puts them in the array val 
    fileH.openFile("Valedictorians.txt"); 
    fileH.readFile(); 
    numVals = fileH.length(); 

    //for testing 
    System.out.println(numVals); 


    for(int i = 0; i < numVals;i++){ 
     val.put(i, fileH.get(i)); 

     //for testing 
     System.out.println(val.get(i)); 
    } 
     val2 = new JRadioButton[numVals]; 
     votes = new int[numVals]; 

    fileH.closeFile(); 

    //takes the number of votes and places them in the votes array 
    fileH.openFile("Winner.txt"); 
    fileH.readFile(); 
    int h = 0; 
    for(int i = 9; i<fileH.length(); i += 4){ 

     System.out.println(fileH.get(i)); 

     votes[h]= Integer.parseInt(fileH.get(i)); 

     //for testing 
     System.out.println("Votes for:" + val.get(h) + " are: "+ votes[h]); 


     h++; 
    } 
    fileH.closeFile(); 

    } 


    //if the user hits the vote button this method will run the steps needed to accomplish that goal 
    public static void voted(){ 
    checkSelected();//checks student number, and adds a vote to the person selected 
    removeVoted(); // removes the person who voted so that each person can only vote once 



    clear();//clears the studentNumber and val selected 
    write();// writes the updated info to the files Voters and Winner 
    checkWinner(); //checks to see if the vote was the last 

    } 

    public static void main(String[] args){ 
    retrieve(); 


    studentGroup = new ButtonGroup(); 

    //initalizes the names of each val on to radio buttons 
    //adds each radio button to the button group and sets the background to white for a clear gui look 
    for(int i = 0; i<numVals;i++){ 
     val2[i] = new JRadioButton(val.get(i)); 
     studentGroup.add(val2[i]); 
     val2[i].setBackground(Color.WHITE); 
    } 

    voteNotification.setEditable(false); 


    //vote button - allows the user to let the program know that they are done entering their student number and selecting a person for their vote 
    JButton studentNumButton = new JButton("Vote!"); 
    studentNumButton.addActionListener(new SelectionCounter()); 

//this code could be added to show a picture of each valedictorian *******EXTRA************ 
    // John.setRolloverEnabled(true); 
    // John.setRolloverIcon(icon); 

    //images 
    //int NEW_WIDTH = 50; 
    //int NEW_HEIGHT = 235; 
    //int NEW_WIDTH2 = 290; 
    //int NEW_HEIGHT2 = 55; 


    ImageIcon header; 
    ImageIcon side; 
    ImageIcon side2; 
    Image image = new ImageIcon("src\\Header_MICHS.jpg").getImage();  
    header = new ImageIcon(image.getScaledInstance(290, 55, java.awt.Image.SCALE_SMOOTH)); 
    Image image2 = new ImageIcon("src\\lightningbolt2.png").getImage() ;  
    side = new ImageIcon(image2.getScaledInstance(50, 235, java.awt.Image.SCALE_SMOOTH)); 
    Image image3 = new ImageIcon("src\\lightningbolt.png").getImage() ; 
    side2 = new ImageIcon(image3.getScaledInstance(50, 235, java.awt.Image.SCALE_SMOOTH)); 
    JLabel sideLabel2 = new JLabel(side2); 
    JLabel sideLabel = new JLabel(side); 
    JLabel headerLabel = new JLabel(header); 

    //bottom bar add - the text field and Jbutton 
    JPanel studentInfo = new JPanel(); 
    studentInfo.setLayout(new GridLayout(1,2)); 
    studentInfo.add(studentNumber); 
    studentInfo.add(studentNumButton); 



    //add the val radio buttons to a panel 
    JPanel options1 = new JPanel(); 
    options1.setLayout(new GridLayout(val2.length,0)); 
    for(int i=0; i<val2.length;i++){ 
     options1.add(val2[i]); 
    } 

    //add the message box to a panel 

    options2.setLayout(new GridLayout(1,0)); 
    options2.setBackground(Color.WHITE); 
    options2.add(voteNotification); 


    //add the panels to a panel 

    options.setLayout(new GridLayout(1,2)); 
    options.add(options1); 
    options.add(options2); 

    //put the functional things into one panel 
    JPanel setup = new JPanel(); 
    setup.setLayout(new BorderLayout()); 
    setup.add(options, BorderLayout.CENTER); 
    setup.add(studentInfo, BorderLayout.SOUTH); 

    //put the pictures around the functional things 
    JPanel content = new JPanel(); 
    content.setLayout(new BorderLayout()); 
    content.add(setup, BorderLayout.CENTER); 
    content.add(headerLabel, BorderLayout.NORTH); 
    content.add(sideLabel, BorderLayout.EAST); 
    content.add(sideLabel2, BorderLayout.WEST); 


    window.setLayout(new BorderLayout()); 
    window.add(content, BorderLayout.CENTER); 
    window.setContentPane(content); 
    window.setSize(300,310); 
    window.setLocation(550,250); 
    window.setVisible(true); 
    window.setResizable(false); 
    } 
    private static class SelectionCounter implements ActionListener{ 
    public void actionPerformed(ActionEvent e){ 
     voted(); 
    } 
    }//end of SelectionCounter class 


    public static class FileHandling{ 
    private Scanner file; 
    static DynamicArrayOfString temp; 
    String name; 

    public void openFile(String name){ 
     try{ 
     file = new Scanner(new File(filePath + name)); //gets name=file u want to read 
     } 
     catch(Exception e){ 
     System.out.println("Could not find file!"); 
     } 
    } 

    public void readFile(){ // retrieves one input from the file for each line 
     temp = new DynamicArrayOfString(); 
     for(int i = 0; file.hasNext(); i++){ 
     temp.put(i,file.next()); 
     System.out.printf("%s%n", temp.get(i)); 
     } 
    } 

    public int length(){ 
     return temp.size(); 
    } 

    public boolean hasNext(){ 
     return file.hasNext(); 
    } 

    public String get(int position) { 
     if (position >= temp.size()) 
     return "Nothing"; 
     else{ 
     String answer = temp.get(position); 
     //System.out.println(temp.get(position)); 
     return answer; 
     } 
    } 

    public void closeFile(){ 
     file.close(); 
    } 
    }//end of FileHandling 


    private static class CreateFile{ 
    private static Formatter file2; 

    public static void openFile(String name){ 
     try{ 
     file2 = new Formatter(filePath + name); 
     } 
     catch(Exception e){ 
     System.out.println("you have an error"); 
     } 
    } 
    public static void addToFile(String number){ 
     file2.format("%s%n", number); 
    } 
    public static void closeFile(){ 
     file2.close(); 
    } 
    }//end of CreateFile 

    static class HintTextField extends JTextField implements FocusListener { 

    private final String hint; 
    private boolean showingHint; 

    public HintTextField(final String hint) { 
     super(hint); 
     this.hint = hint; 
     this.showingHint = true; 
     super.addFocusListener(this); 
    } 

    public void focusGained(FocusEvent e) { 
     if(this.getText().isEmpty()) { 
     super.setText(""); 
     showingHint = false; 
     } 
    } 

    public void focusLost(FocusEvent e) { 
     if(this.getText().isEmpty()) { 
     super.setText(hint); 
     showingHint = true; 
     } 
    } 

    public String getText() { 
     return showingHint ? "" : super.getText(); 
    } 
    public void showHint(){ 
     super.setText(hint); 
    this.showingHint=true; 
    } 
+0

Недостаточно кода для понимания. Если бы вы опубликовали весь свой код, это было бы намного лучше. – tbodt

+0

Чтобы лучше помочь, опубликуйте [SSCCE] (http://sscce.org/). @tbodt Итак, вы готовы искать ошибки в 600+ LOC, распространяемых через полдюжины классов? Вы будете в «избранной группе». Большинство из нас предпочли бы SSCCE. –

+0

@AndrewThompson Если бы я увидел 1000 строк кода в вопросе переполнения стека, я бы упал в обморок. Я не думал, что будет очень много кода. – tbodt

ответ

1

Одна из панелей содержит мою JTextArea. Первоначально я устанавливаю как "".

Что произойдет, если вы изначально задали текстовую область с помощью какого-либо текста? Вы видите текст?

Я предполагаю, что вы не видите текст из-за того, как вы создали текстовое поле:

static JTextArea voteNotification = new JTextArea(" "); 

Может попробовать:

static JTextArea voteNotification = new JTextArea(2, 30); 

поэтому текстовая область имеет разумный предпочтительный размер ,

+0

Если я помещаю текст в текстовую область в начале, он появляется. Он просто не обновляется даже при переходе через код. – Chris

+0

Я отправлю весь код, когда вернусь к своему компьютеру. – Chris

+0

Если текстовая область не обновляется, это означает одну из двух вещей: 1) вы блокируете EDT, чтобы графический интерфейс никогда не мог перекрасить себя или 2) у вас нет ссылки на текстовую область, что означает, что у вас есть определил его дважды. – camickr

Смежные вопросы