[Java] Textarea applet vanuit ander object wijzigen

Pagina: 1
Acties:

  • EnsconcE
  • Registratie: Oktober 2001
  • Laatst online: 02-03 10:21
Mijn project is doordrenkt van de system.out.println's, opzich is dat geen probleem maar het nadeel is dat deze functie de textarea niet wijzigt. Op de plekken waar een return mogelijk is, is deze al aangemaakt. Maar nu wil ik dus dat de system.out.println wordt vervangen door een functie die de textarea wijzigt. Bij het aanmaken van de objecten vertel ik ze al hoe de applet heet en zodoende zouden de functies in de applet aangesproken moeten worden, maar zoals je al raad gebeurt dat niet.

Het gaat om deze functies:
Java:
1
2
3
4
5
6
7
8
9
    public void printLineTextArea(String print)
    {
        textAreaVeld.setText(textAreaVeld.getText() + "\n" + print);
    }
    
    public void printTextArea(String print)
    {
        textAreaVeld.setText(textAreaVeld.getText() + print);
    }


En het object doorverwijzen naar de andere objecten gaat als volgt
Java:
1
GamePanel = new Game(this); 


Java:
1
2
3
4
5
6
    private TheCurse applet;

    public Game(TheCurse applet)
    {
        this.applet = applet;
    }


Het aanroepen doe ik als volgt:
Java:
1
applet.printTextArea(subString2[i2]);

Deze bovenstaande code staat in een klasse die in de klasse game tot een object wordt gemaakt. Zonder de applet werkt alles, in het standaard java textoutputding(sorry weet ff niet hoe die heet), goed.

Het applet heet TheCurse. Is het mogelijk om dat te doen of niet en zo ja hoe? Ik kom er namelijk niet uit met zoeken op google en dit forum.

  • Nick_S
  • Registratie: Juni 2003
  • Laatst online: 13-04 23:48

Nick_S

++?????++ Out of Cheese Error

Worden je functies niet aangesproken? (Controleer door een Sys.out in deze functies toe te voegen), verandert je textarea niet of krijg je een foutmelding?

Probeer bij code snippets ook altijd duidelijk te vermelden uit welke klasse deze komen. Liever iets te veel code, en dat we de context begrijpen als een paar losse flodders. Ik snap nu niet helemaal, welke code welke aanroept en in welke klasse.

'Nae King! Nae quin! Nae Laird! Nae master! We willna' be fooled agin!'


  • Kwistnix
  • Registratie: Juni 2001
  • Laatst online: 15-04 12:56
Niet dat het van invloed is op de werking van het geheel, maar i.p.v. handmatig eerst de volledige tekst in het (J)TextArea op te vragen, dan de nieuwe input er aanvast te plakken en het geheel weer in het
(J)TextArea terug te zetten is lijkt het mij handiger om (J)TextArea.append(String someString) te gebruiken.

  • EnsconcE
  • Registratie: Oktober 2001
  • Laatst online: 02-03 10:21
FallenAngel666 schreef op donderdag 19 januari 2006 @ 13:40:
Niet dat het van invloed is op de werking van het geheel, maar i.p.v. handmatig eerst de volledige tekst in het (J)TextArea op te vragen, dan de nieuwe input er aanvast te plakken en het geheel weer in het
(J)TextArea terug te zetten is lijkt het mij handiger om (J)TextArea.append(String someString) te gebruiken.
Ok ik zal er even naar kijken.
Nick_S schreef op donderdag 19 januari 2006 @ 13:19:
Worden je functies niet aangesproken? (Controleer door een Sys.out in deze functies toe te voegen), verandert je textarea niet of krijg je een foutmelding?

Probeer bij code snippets ook altijd duidelijk te vermelden uit welke klasse deze komen. Liever iets te veel code, en dat we de context begrijpen als een paar losse flodders. Ik snap nu niet helemaal, welke code welke aanroept en in welke klasse.
De applet:
code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.border.TitledBorder; 

public class TheCurse extends JApplet implements ActionListener
{
    // instance variables - replace the example below with your own
    private JTextField inputVeld = new JTextField("textfield",25);
    private TextArea textAreaVeld = new TextArea("Textarea",28,1, TextArea.SCROLLBARS_VERTICAL_ONLY);
    private JButton inputButton = new JButton("Enter");
    
    private JPanel p,pGame,pPlayer;
    private Game GamePanel;
    private Player PlayerPanel;
    private JLabel Label;
    private String[] words;
    private String input;
    private boolean finished = false;

    public void init()
    {
        this.resize(500,500);
        words = null;
        input = "";
        Container p = getContentPane();
        Color background = new Color(238,238,238);

        p.setLayout(new GridLayout(0,2));
        p.setBackground(background);

        JPanel pGame = new JPanel();
        pGame.setLayout(new BorderLayout(10,10));
        p.add(pGame);
        pGame.setBorder(new TitledBorder("(?)"));
        pGame.setBackground(background);

        JPanel pGameNorthPanel = new JPanel();
        pGameNorthPanel.setLayout(new GridLayout());
        pGame.add(pGameNorthPanel, BorderLayout.NORTH);
        pGameNorthPanel.add(textAreaVeld);
                    
        JPanel pGameWestPanel = new JPanel();
        pGameWestPanel.setLayout(new FlowLayout());
        pGame.add(pGameWestPanel, BorderLayout.WEST);
        pGameWestPanel.add(inputVeld);
                    
        JPanel pGameEastPanel = new JPanel();
        pGameEastPanel.setLayout(new FlowLayout());
        pGame.add(pGameEastPanel, BorderLayout.EAST);
        pGameEastPanel.add(inputButton);
                    
        inputButton.addActionListener(this);
        
        GamePanel = new Game(); 

        
        inputVeld.setText ("");
        textAreaVeld.setText(GamePanel.printWelcome());
        
    }

    public void actionPerformed(ActionEvent e)
    {
        if (e.getSource() == inputButton) {
            
            if (!finished) {
                
                if (inputVeld.getText() != "") {
//                    textAreaVeld.setText(textAreaVeld.getText() + "\n>" + inputVeld.getText());
                    printLineTextArea(">" + inputVeld.getText());
                    Command command = GamePanel.getParser().getCommand(inputVeld.getText());
//                    textAreaVeld.setText(textAreaVeld.getText() + "\n" + GamePanel.processCommand(command));
                    printLineTextArea(GamePanel.processCommand(command));
                    inputVeld.setText("");
                    //setSelectionEnd()
                }
                else {
                    textAreaVeld.setText (textAreaVeld.getText() + "\nDo what?");
                }
            }
            else {
                textAreaVeld.setText (textAreaVeld.getText () + "Thank you for playing.  Good bye.");

            }
        } 
    }
    
    public void printLineTextArea(String print)
    {
        textAreaVeld.setText(textAreaVeld.getText() + "\n" + print);
    }
    
    public void printTextArea(String print)
    {
        textAreaVeld.setText(textAreaVeld.getText() + print);
    }
}


De klasse game, deze stuurt de applet door aan elke klasse die het nodig heeft, de game maakt alles maar dat heb ik eruit gelaten i.v.m. de hoeveelheid. De belangrijkste onderdelen heb ik erin laten staan.
code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
public class Game 
{
    private Player player;
    private Parser parser;
    private TheCurse applet;

    /**
     * Create the game and initialise its internal map.
     */
    public Game()
    {
        parser = new Parser();
        createPlayer();
        createScenario();
        this.applet = applet;
    }
    
    /**
     * Creer de speler en geef hem een naam en gewicht
     * dat hij maximaal kan dragen.
     */
    private void createPlayer()
    {
        player = new Player(5000);
    }
    
    /**
     * Create all the Rooms and link their exits together.
     * Maak daarbij alle items en als het moet Items waarmee het Item
     * gecombineerd moet worden. Alle mogelijkheden moeten wel
     * ingevoerd worden!
     */
    private void createScenario()
    {
       
        Room endRoom = new EndRoom("at the end", "Designed by: #" + 
                                                 "Naam1#" +
                                                 "Naam2#" +
                                                 "The END#", 1000, applet);

        player.setCurrentRoom(entrance);
    //
    }

    /**
     * Print out the opening message for the player.
     */
    public String printWelcome()
    {
        return "\nWelcome to the Curse of Toetanchamon!\n" +
               "The Curse of Toetanchamon is a new, incredibly exciting adventure game.\n" +
               "To find the end you will have to concur some obstakles, good luck! You are going to need it.\n" +
               "Type 'help' if you need help.\n\n" + player.getCurrentRoomLongDescription();
    }
    
    /**
     *  Main play routine.  Loops until end of play.
     */
    public void play() 
    {
        System.out.println(printWelcome());

        // Enter the main command loop.  Here we repeatedly read commands and
        // execute them until the game is over.
                
         String finished = "false";
         while (!finished.equals("true")) {
             Command command = javaParser.getCommand();
             finished = processCommand(command);
             System.out.println(finished);
         }
         System.out.println("Thank you for playing.  Good bye.");
    }
    
    /**
     * Given a command, process (that is: execute) the command.
     * If this command ends the game, true is returned, otherwise false is
     * returned.
     */
    public String processCommand (Command command)
    {
        String returnText = "";
        
        if (command.isUnknown()) {
            returnText = "I don't know what you mean...";
        }
        else {
            String commandWord = command.getCommandWord(); 

            if (commandWord.equals("help")) {
                returnText = printHelp();
            }
            else if (commandWord.equals("quit")) {
                returnText = quit(command);
            }
        }
        return returnText;
    }
    
    
    /**
     * Retourneerd het aangemaakte object parser
     */
    public Parser getParser()
    {
        return parser;
    }
    
    // implementations of user commands:

    /**
     * Print out some help information.
     * Here we print some stupid, cryptic message and a list of the 
     * command words.
     */
    private String printHelp() 
    {
        return "\nYou are alone and wandering around the pyramid of Toetanchamon.\n\nYour command words are:\n\n" + parser.commands.getCommandList ();
    }

    /** 
     * "Quit" was entered. Check the rest of the command to see
     * whether we really quit the game. Return true, if this command
     * quits the game, false otherwise.
     */
    private String quit(Command command) 
    {
        if(command.hasSecondWord()) {
            return "Quit what?";
        }
        else {
            return "true";  // signal that we want to quit
        }
    }
}


En de klasse endroom, deze is een sub van room maar de gegevens daarin zijn niet belangrijk. mocht iemand het toch wel ff willen inzien zeg het dan ff
code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
public class EndRoom extends Room
{
    // instance variables - replace the example below with your own
    private String credits;
    private String thisDescription;
    private int pause;
    private TheCurse applet;
    
    
    /**
     * Constructor for objects of class EndRoom
     */
    public EndRoom(String description, String credits, int pause, TheCurse applet)
    {
        // initialise instance variables
        super(description);
        thisDescription = "You are " + description;
        this.credits = credits;
        this.pause = pause;
        this.applet = applet;
    }

    /**
     * Deze functie neemt het over van de get long description van de hoofdklasse,
     * door een # in te geven in de aanmaak van deze klasse als object krijg je 
     * een pause ook aangegeven tijdens het creeeren van deze klasse als object.
     */
    public String getLongDescription()
    {
        String returnString = "";
        
        if (!thisDescription.equals("")) {
            applet.printLineTextArea(thisDescription + "\n");
        }
        
        if (!credits.equals("")) {
            String[] subString = credits.split("#"); 

            for (int i = 0; i < subString.length; i++) {
                String subString2[] = subString[i].split("");
                
                for (int i2 = 0; i2 < subString2.length; i2++) {
                    applet.printTextArea(subString2[i2]);
                    
                    try {
                        Thread.sleep(50);
                    }
                    catch (InterruptedException e) {
                        // ignoring exception at the moment
                    }
                }

                applet.printLineTextArea("");
                
                try {
                    Thread.sleep(pause);
                }
                catch (InterruptedException e) {
                    // ignoring exception at the moment
                }
            }
        }
        
        credits = "";
        thisDescription = "";
        
        return returnString;
    }
}

  • Robtimus
  • Registratie: November 2002
  • Laatst online: 17:03

Robtimus

me Robtimus no like you

Je kan ook een workaround maken.
Je creeert een sub class van java.io.PrintStream (of java.io.OutputStream, waarmee je dan een PrintStream creeert) waarmee je de text van je TextArea aanpast als je er iets naartoe print. Vervolgens gebruik je System.setOut om van die printstream je nieuwe "System.out" van te maken. Alles dat je daarna naar System.out print gaat dan niet meer via de console maar via je zelf gezette printstream.

Ooit zelf zoiets geprobeerd, ik heb het alleen nog niet echt goed getest:
Java:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
public class TextOutputStream extends OutputStream
{
    /**
     * The default initial buffer size.
     */
    public static final int BUFFER_SIZE = 32;
    
    /**
     * The text component to write to.
     */
    private JTextComponent text;
    
    /**
     * The buffer to write to. Upon flushing it is converted to a string and
     * written to the text component.
     */
    private byte[] buffer;
    
    /**
     * The number of valid bytes in the buffer.
     */
    private int count;
    
    /**
     * Creates a text output stream. Its buffer has an initial capacity of
     * {@link #BUFFER_SIZE}.
     * 
     * @param textComponent The text component to write to.
     */
    public TextOutputStream(JTextComponent textComponent)
    {
        this(textComponent, BUFFER_SIZE);
    }
    
    /**
     * Creates a text output stream.
     * 
     * @param textComponent
     * @param size The initial size of the internal buffer.
     */
    public TextOutputStream(JTextComponent textComponent, int size)
    {
        super();
        text = textComponent;
        buffer = new byte[size];
        count = 0;
    }

    /** 
     * Writes the specified byte to this byte array output stream.
     * The argument will be cast to byte, i.e. only the eight lower bits are
     * stored. 
     *
     * @param   b   the byte to be written.
     * @see OutputStream#write(int)
     */
    public synchronized void write(int b)
    {
        int newcount = count + 1;
        if (newcount > buffer.length)
        {
            byte[] newbuf = new byte[2 * buffer.length];
            System.arraycopy(buffer, 0, newbuf, 0, count);
            buffer = newbuf;
        }
        buffer[count] = (byte)b;
        count = newcount;
    }
    
    /**
     * Writes the internal buffer to the text component.
     */
    public synchronized void flush()
    {
        String newText = text.getText() + new String(buffer, 0, count);
        text.setText(newText);
        // the text has been written now, so clear the buffer
        // we don't need to spend time actually clearing or deallocation
        // (through the garbage collector) the buffer, just set the counter
        // to 0
        count = 0;
    }
}
Met natuurlijk een append in die laatste method ipv wat ik daar deed.

Voordeel van deze manier van werken is dat alleen je main class / applet hoeft te weten wat System.out nu eigenlijk betekent. De rest gebruikt het gewoon.


Let er trouwens wel op dat deze methode niet goed vanuit threads gebruikt kan worden aangezien je het zetten van de text dan via SwingUtilities.invokeAndWait en SwingUtilities.invokeLater moet doen.

[ Voor 7% gewijzigd door Robtimus op 19-01-2006 21:32 ]

More than meets the eye
There is no I in TEAM... but there is ME
system specs


  • EnsconcE
  • Registratie: Oktober 2001
  • Laatst online: 02-03 10:21
Ik begrijp je in zoverre dat ik nu een TextArea in de TextOutputStream stop. Deze lijkt mij dan gewijzigd te worden wanneer ik System.out.write aanroep? De PrintStream lukt me niet vanwege dat je die moet aanmaken met PrintStream(string/object/file...). Wat ook niet werkt is System.out omdat hij zegt dat het geen java.io.PrintStream is.

Is het na de System.out ook zo dat ik overal Systemm.out.write kan aanroepen en zo wordt alles in het tekstvak gezet? Of moet ik textOutput.write doen(omdat dat de naam van m'n veld is?

Ik ben net 10 week bezig met Java, vandaar dat ik nog niet helemaal snap wat je moet doen.

De append werkt overigens alleen als je gebruik maakt van een JTextArea of TextArea, JTextComponent bevat deze methode niet.

[edit]
Te snel gesproken, ik heb nu dit
textOutput = new TextOutputStream(textAreaVeld);
System.setOut(new PrintStream(textOutput, true));
en daarmee compileert hij iig wel, wat al een stap voor mij is. Maar nu hetvolgende probleem; access denied in java.lang.runtimepermission setio.
Ik heb de policy aangepast wat niet mocht baten(misschien doe ik het fout) maar dat lijkt me ook niet verstandig om te doen.

[ Voor 33% gewijzigd door EnsconcE op 20-01-2006 09:14 ]


  • Robtimus
  • Registratie: November 2002
  • Laatst online: 17:03

Robtimus

me Robtimus no like you

EnsconcE schreef op vrijdag 20 januari 2006 @ 08:46:
Ik begrijp je in zoverre dat ik nu een TextArea in de TextOutputStream stop. Deze lijkt mij dan gewijzigd te worden wanneer ik System.out.write aanroep? De PrintStream lukt me niet vanwege dat je die moet aanmaken met PrintStream(string/object/file...). Wat ook niet werkt is System.out omdat hij zegt dat het geen java.io.PrintStream is.

Is het na de System.out ook zo dat ik overal Systemm.out.write kan aanroepen en zo wordt alles in het tekstvak gezet? Of moet ik textOutput.write doen(omdat dat de naam van m'n veld is?
PrintStream heeft een constructor die een OutputStream verwacht. Daar kun je deze dus perfect aan meegeven.
Java:
1
2
3
TextOutputStream tos = new TextOutputStream(textarea);
PrintStream ps = new PrintStream(tos);
System.setOut(ps);
De append werkt overigens alleen als je gebruik maakt van een JTextArea of TextArea, JTextComponent bevat deze methode niet.
Ah ok, dat wist ik niet, ik gebruik nooit JTextComponent apart, ik ga meteen voor JTextArea of JTextField.

More than meets the eye
There is no I in TEAM... but there is ME
system specs


  • EnsconcE
  • Registratie: Oktober 2001
  • Laatst online: 02-03 10:21
Haha ok, je hebt het hetzelfde als ik. Maar het bezorgt mij een nieuw probleem.

En hoe zit dat eigenlijk met de System.out. Kan ik dan in alle objecten System.out aanroep terwijl deze naar het textvak schrijft of moet ik ps.print doen?

  • Robtimus
  • Registratie: November 2002
  • Laatst online: 17:03

Robtimus

me Robtimus no like you

Als jij System.setOut(ps) doet, dan is ps je nieuwe System.out. System.out.println() is dan exact hetzelfde als ps.println(). Voor die objecten maakt het ook niet zo veel uit waar naartoe geprint wordt, of System.out nou de console is of een text area is niet hun probleem, als de user het maar te zien krijgt.

More than meets the eye
There is no I in TEAM... but there is ME
system specs


  • EnsconcE
  • Registratie: Oktober 2001
  • Laatst online: 02-03 10:21
IceManX schreef op vrijdag 20 januari 2006 @ 20:51:
Als jij System.setOut(ps) doet, dan is ps je nieuwe System.out. System.out.println() is dan exact hetzelfde als ps.println(). Voor die objecten maakt het ook niet zo veel uit waar naartoe geprint wordt, of System.out nou de console is of een text area is niet hun probleem, als de user het maar te zien krijgt.
Helaas:
exception: java.security.AccessControlException: access denied (java.lang.RuntimePermission setIO)
Daarbij zou ik de java.policy moeten gaan aanpassen en dat lijkt me niet verstandig.

Verwijderd

Je meldt in een van je vorige post dit:
EnsconcE schreef op donderdag 19 januari 2006 @ 11:45:
En het object doorverwijzen naar de andere objecten gaat als volgt
Java:
1
GamePanel = new Game(this); 

Java:
1
2
3
4
5
6
    private TheCurse applet;

    public Game(TheCurse applet)
    {
        this.applet = applet;
    }
Maar in de code die je laatst opgeeft staat er:
Java:
1
GamePanel = new Game();

en in de constructor Game() die je ook iets raars:
Java:
1
this.applet = applet;

hoewel er geen argument applet wordt meegegeven. Er zal dus ergens een NullPointerException optreden wanneer je later die applet variabele gaat gebruiken...

  • Robtimus
  • Registratie: November 2002
  • Laatst online: 17:03

Robtimus

me Robtimus no like you

EnsconcE schreef op zaterdag 21 januari 2006 @ 11:52:
Helaas:
exception: java.security.AccessControlException: access denied (java.lang.RuntimePermission setIO)
Daarbij zou ik de java.policy moeten gaan aanpassen en dat lijkt me niet verstandig.
Stik.
Klopt ja, in applets mag je niet zoveel met je filesystem doen.

More than meets the eye
There is no I in TEAM... but there is ME
system specs


  • EnsconcE
  • Registratie: Oktober 2001
  • Laatst online: 02-03 10:21
Verwijderd schreef op zaterdag 21 januari 2006 @ 12:29:
Je meldt in een van je vorige post dit:

[...]

Maar in de code die je laatst opgeeft staat er:
Java:
1
GamePanel = new Game();

en in de constructor Game() die je ook iets raars:
Java:
1
this.applet = applet;

hoewel er geen argument applet wordt meegegeven. Er zal dus ergens een NullPointerException optreden wanneer je later die applet variabele gaat gebruiken...
Sorry, dat is de verkeerde code. Ik heb wel degelijk
Java:
1
GamePanel = new Game(this);

anders kon ik hem ook niet compilen.

Maar ik heb nu i.p.v. m'n variabele applet aplet genoemd en nu doet hij het wel :?.

Dat ik dat niet eerder geprobeerd heb 8)7.
Pagina: 1