1. My code runs but the text panels won't display properly in the panel until i hide the frame and open it again or click min/max.
2. Can someone suggest the kind of layout i need to keep letters of each word together so it doesn't wrap to the next line but i do need to have more than one line/rows for long phrases. I tried gridlayout before but it stretched the letter panels and i couldn't reduce the height of them no matter how i lower the size I set for it.

/**
 * @(#)PhrasePanel.java
 *
 *
 * @author 
 * @version 1.00 2009/8/16
 */
 
import java.util.*;
 
import javax.swing.JFrame;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.border.*;
import java.util.Random;
import java.io.*;

public class PhrasePanel extends JFrame implements ActionListener {
	
	public String phrases[] = {"Why doesn't this code display properly?", "How long will it take to learn Java", "Have a very very Good Evening?"};
	

	int index = 0;
	
	LetterPane letterPanel[] = new LetterPane[100];
	
	int LetterLength = 0;
	int row = 0;
	Dimension pSize = new Dimension(0,0);
	
	JPanel phrasePanel = new JPanel();
	JPanel textPanel = new JPanel();
	JPanel myPanel = new JPanel();
	int gWidth;
	int gHeight;

    public PhrasePanel() {
    	super("Phrase Panel");
    	Container contentPane = getContentPane();
 
    	pSize = contentPane.getPreferredSize();
   
    	JPanel top = phraseInterface();
    	JPanel bottom = controlPanel();
    	myPanel.add(top);
    	myPanel.add(bottom);
    	contentPane.add(myPanel);
    }
    public JPanel phraseInterface(){
		phrasePanel.setLayout(new FlowLayout());
		phrasePanel.setPreferredSize(new Dimension(1000,180));
		phrasePanel.setLocation(0,0);
		phrasePanel.setBackground(Color.blue);
		phrasePanel.setBorder(BorderFactory.createLineBorder(Color.black,2));
		return phrasePanel;
	}
    
    JPanel displayPanel(){
    
    	JPanel viewPhrase = new JPanel();
    	viewPhrase.setLayout(null);
    	viewPhrase.setSize(500,300);
    	viewPhrase.setLocation(0,0);
    	
    	return viewPhrase;
    }
    
   public void loadPhrase(Phrase p){
		
		unLoadPhrase();
		row = 0;
	
		phrasePanel.add(Box.createRigidArea(new Dimension(0,50)));
		phrasePanel.add(textPanel);

		Word aword;
		Letter myChar;
		int LetterLength = 0;
		for(int i=0; i<p.words.size(); i++){
	
			aword = p.words.get(i);
	
			int len = aword.len;
			
			int tooBig = LetterLength+len;
	
			if(tooBig >= 30){
				row++;
				LetterLength=0;
			}
			
			for(int j=0; j<len; j++){
		
				myChar = aword.letters[j];
			
		
				letterPanel[i] = new LetterPane(Color.white, ""+myChar.letter);
			
				phrasePanel.add(Box.createVerticalGlue());
				
				letterPanel[i].setPreferredSize(new Dimension(25,25));
				letterPanel[i].setBorder(BorderFactory.createLineBorder(Color.black,2));
				
				letterPanel[i].setMaximumSize(letterPanel[i].getPreferredSize());
				
				phrasePanel.add(Box.createVerticalGlue());
		
				phrasePanel.add(letterPanel[i]);
				LetterLength++;		
	
			}
			
			phrasePanel.add(Box.createRigidArea(new Dimension(20,20)));
		}

		try {
    		Thread.sleep(50);
    	}
    	catch(InterruptedException f) {}

		phrasePanel.paintImmediately(0, 0, phrasePanel.getWidth(), phrasePanel.getHeight());

	}
	
	public void unLoadPhrase(){
		
		Component[] arrayComponents = textPanel.getComponents();
	
		for( int i=0; i< arrayComponents.length;i++){
		
	
			textPanel.remove(arrayComponents[i]);
		}
		unLoadTextPanel();
	}
	
	public void unLoadTextPanel(){

		Component[] arrayComponents = phrasePanel.getComponents();

		for( int i=0; i< arrayComponents.length;i++){
			phrasePanel.remove(arrayComponents[i]);
		}
	}
	
   	public void set(Color c, String s){
   		JLabel label = new JLabel(s);
		setBackground(c);
		label.setText(s);
	}
    
    JPanel controlPanel(){
    	JPanel controlPhrase = new JPanel();
    	controlPhrase.setLayout(new BoxLayout(controlPhrase, BoxLayout.X_AXIS));

    	JButton start = new JButton("Start");
    	JButton previous = new JButton("Previous");
    	JButton next = new JButton("Next");
    	JButton exit = new JButton("Exit");
    	start.addActionListener(this);
    	previous.addActionListener(this);
    	next.addActionListener(this);
    	exit.addActionListener(this);
    	controlPhrase.add(start);
    	controlPhrase.add(previous);
    	controlPhrase.add(next);
    	controlPhrase.add(exit);
    	return controlPhrase;
    }

    
    public void actionPerformed(ActionEvent e){
    	String actionName = e.getActionCommand();
    	if(actionName == "Start"){
    		index = 0;
    		loadPhrase(new Phrase(phrases[index]));
    	}
    	else if(actionName == "Previous"){
    		index = Math.abs(index-1)%3;
    		loadPhrase(new Phrase(phrases[index]));
    	}
    	else if(actionName == "Next"){
    		index = (index+1)%3;
    		loadPhrase(new Phrase(phrases[index]));
    	}
    	else if(actionName == "Next"){
    		index = Math.abs(index-1)%3;
    		loadPhrase(new Phrase(phrases[index]));
    	}
		else if(actionName == "Exit"){
			dispose();
		}
    }
    
    public static void main(String[] args){
    	JFrame frame = new PhrasePanel();
    	frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
    	frame.setSize(1200,800);
    	frame.setVisible(true);
    }
}
class LetterPane extends JPanel {
	JLabel label;
	
	public LetterPane(Color c, String s) {
		setLayout(null);
		setBackground(c);
		label = new JLabel(s);
		label.setHorizontalAlignment(SwingConstants.CENTER);
		setSize(32,32);
		setLayout(new BorderLayout());
		setBorder(BorderFactory.createLineBorder(Color.black,2));
		add(label);
		
		Dimension d = getPreferredSize();
		d.width += 8;
		d.height += 8;
		setPreferredSize(d);
	}
	public void set(Color c, String s){
		setBackground(c);
		label.setText(s);
	}
	
	public Color getColor() {
		return getBackground(); 
	}
	public String getText(){
		return label.getText();
	}
}

class Letter
{
   char letter;
   boolean show;    // the letter is hidden if this field is false
   
   public Letter (char c)
   { 
       letter = c; 
       if (c >= 'A' && c <= 'Z')
       { show = false; }           // hide all letters
       else
       { show = true; }            // show all characters that are not letters
   }
}

class Word
{
    Letter [ ] letters;
    int len;
    
    public Word (String s)
    {
      len = s.length ( );
      letters = new Letter [len];
      for (int i = 0; i < len; ++i)
      { letters [i] = new Letter (s.charAt (i)); }
    }
  
  
    // count the occurrence of c in this word, and set field show to true 
    public int countOccurrence (char c)
    {
        int count = 0;
        {
            for (int i = 0; i < len; ++i)
            {
                Letter c1 = letters [i];
                if (c1.letter == c && c1.show == false)
                { ++ count; letters [i].show = true;}
            }
        }
        return count;
    }
    
    // show the word
    
    void open ( )
    {
      for (int i = 0; i < len; ++i)
      { letters [i].show = true; }
    }
}
class Phrase
{
   // a phrase is represented by a Vector of Words and well as a String
   Vector <Word> words = new Vector <Word> ( );
   private String rep;
   
   public Phrase (String s)
   {
       rep = s;
       Scanner reader = new Scanner (rep);
       while (reader.hasNext ( ))
       { words.add (new Word (reader.next ( ).trim ( ))); }
   }

   public int countLetter (char c)  // count the number of occurrence of c, and set "show" of c to true
   { 
       int count = 0;
       for (int i = 0; i < words.size ( ); ++i)
       { count += words.get (i).countOccurrence (c); }
       return count;  
   }
 
   public void open ( )
   {
       for (int i = 0; i < words.size ( ); ++i)
       { words.get (i).open ( ); }
   }
   
   public String toString ( )
   { return rep; }
}

class Player
{
   int accum;     // amount accumulated in the game
   int amount;    // amount accumulated in the current round
}

Recommended Answers

All 4 Replies

Put this line at the bottom of actionPerformed :

validate ();

That way you want have to minimize, maximize, etc.

Regarding the Layout, I haven't had a chance to look at that yet.

Thanks very much. I don't know why but i first read your post, i didn't know that was a solution to my first problem. I thought you said you didn't look at it yet.

I wish i posted earlier and joined this site sooner. It's too bad because it was already past the deadline and the course policy does not accept late assignments.

I can't say how depressed i was about it.

So thank you so much for taking the time to look at and i rate you appropriately. Even though i wasn't able to hand it in without the glitch, at least i know what the problem was.

Prof is not available for out of class help.

and12

Put this line at the bottom of actionPerformed :

validate ();

That way you want have to minimize, maximize, etc.

Regarding the Layout, I haven't had a chance to look at that yet.

You're welcome. Sorry you didn't notice it in time.

Regarding the Layout, I looked at it, but couldn't figure out how to give good advice that didn't require a complete overhaul of the program. Layouts are sort of a personal preference sort of thing. I think I know how I would have approached the problem, but I wasn't sure of your background with Layout Managers and I thus didn't know how to write up good advice accordingly. I should have at least wrote back and said that though. Sorry.

Anyway, here are a few links that may be of use to you if you haven't seen them before.

Layout:

http://java.sun.com/docs/books/tutorial/uiswing/
http://java.sun.com/docs/books/tutorial/uiswing/layout/using.html

And validate:

http://java.sun.com/javase/6/docs/api/java/awt/Container.html#validate()

From this page (scroll down):

validate

public void validate()

Validates this container and all of its subcomponents.

The validate method is used to cause a container to lay out its subcomponents again. It should be invoked when this container's subcomponents are modified (added to or removed from the container, or layout-related information changed) after the container has been displayed.

If this Container is not valid, this method invokes the validateTree method and marks this Container as valid. Otherwise, no action is performed.

Overrides:
validate in class Component

When you maximize and minimize or resize, Java calls validate automatically. You can do it yourself, though, which is what I suggested in the last post. It's a fairly common problem, so if things don't lay out correctly, but do after a maximize or minimize, there's a decent chance that you need to call validate, so keep that in mind for the future.

Yes, I won't forget validate(); now. I am so disappointed that all needed was that one line:'( . Well i guess that's part of learning.

Thanks for those links. I was only wondering there was specific layout that would let you control when a row should go to the next line or something. I suppose not.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.