Observer Pattern used with Java socket programing not working - java

I have a problem with my Observer pattern when I'm trying to update the client view based on the data that comes from the server.
The code that sends messages to the client:
package model;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class PlayerThread extends Thread{
private BufferedReader inFromClient;
private PrintWriter outToClient;
private Socket socket;
public PlayerThread(Socket socket) throws IOException{
this.socket = socket;
inFromClient = new BufferedReader(new InputStreamReader(socket.getInputStream()));
outToClient = new PrintWriter(socket.getOutputStream(), true);
outToClient.println("Hey");
}
public void run(){
// needs to be implemented
}
}
The code that takes care of recieving data on the client side:
package connection;
import java.io.BufferedReader;
import mediator.ModelManager;
public class ClientRecieverThread extends Thread {
private ModelManager model;
private BufferedReader inFromServer;
public ClientRecieverThread(ModelManager model, BufferedReader inFromServer) {
this.model = model;
this.inFromServer = inFromServer;
}
#Override
public void run() {
String message = null;
try {
while (true) {
message = inFromServer.readLine();
//System.out.println(message);
model.setMessage(message);
}
} catch (Exception e) {
}
}
}
and the code that contains the observer pattern that I use on the client side:
package model;
public class MessageHandler {
private String message;
public MessageHandler(){
message = "Welcome";
}
public void setMessage(String message){
this.message = message;
}
public String getMessage(){
return this.message;
}
}
package mediator;
import java.io.IOException;
import java.net.UnknownHostException;
import java.util.Observable;
import model.MessageHandler;
import connection.Proxy;
public class ModelManager extends Observable{
private MessageHandler messageHandler;
private Proxy proxy; // establish the connection with the server
public ModelManager() throws UnknownHostException, IOException{
proxy = new Proxy(this);
messageHandler = new MessageHandler();
}
public synchronized void setMessage(String message){
setChanged();
messageHandler.setMessage(message);
notifyObservers(message);
}
public String getMessage(){
return messageHandler.getMessage();
}
public void send(String message){
proxy.send(message);
}
}
package view;
import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.util.Observable;
import java.util.Observer;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import model.Board;
public class View extends JPanel implements Observer{
private JFrame frame;
private Board board;
private Rectangle[][] squares;
private JLabel messageLabel;
public View(){
initComponents();
initVariables();
addComponents();
}
private void initComponents() {
frame = new JFrame("TicTacToe");
frame.setSize(500, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
messageLabel = new JLabel("");
messageLabel.setHorizontalAlignment(SwingConstants.CENTER);
messageLabel.setVerticalAlignment(SwingConstants.CENTER);
this.setSize(300,300);
}
private void initVariables() {
board = new Board(3,3, 100);
squares = new Rectangle[board.getRow()][board.getCol()];
for (int i = 0; i < squares.length; i++){
for (int j = 0; j < squares[i].length; j++){
squares[i][j] = new Rectangle();
}
}
}
private void addComponents() {
frame.add(messageLabel, BorderLayout.NORTH);
frame.add(this);
frame.setVisible(true);
}
private void drawBoard(Graphics g, Board board) {
int positionX = this.getWidth()/2 - (board.getCellSize() + board.getCellSize()/2);
int positionY = 50;
Graphics2D g2d = (Graphics2D) g;
for (int i = 0; i < board.getRow(); i++) {
for (int j = 0; j < board.getCol(); j++) {
squares[i][j] = new Rectangle(positionX, positionY, 100, 100);
positionX += 100;
g2d.draw(squares[i][j]);
}
positionY += board.getCellSize();
positionX = this.getWidth()/2 - (board.getCellSize() + board.getCellSize()/2);
}
}
public void paintComponent(Graphics g){
drawBoard(g, board);
}
public void update(Observable o, Object arg) {
System.out.println((String)arg);
}
}
The connection between the ModelManager and the View is done in the Controller class like this (model.addObserver(view));
The prolem is that I don't understand why the view doesn't get updated, although the data gets recieved by the client.
Thank you in advance! :)

You need to call the method notifyObservers(); when the model is changed, this is will notify the observers added to the model.
So inside the setMessage(String message), do the coding:
if(this.message!=message){
this.message = message;
notifyObservers();
}

Related

Threads. Stopping Server

Recently I was doing multithreaded chat application. Now I am struggling with server. I am trying to stop the server by introducing new field online, but it doesn't help.
import view.ChatHub;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Array;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Set;
import java.util.HashSet;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ChatServer extends Thread {
// All client names, so we can check for duplicates upon registration.
private static Set<String> names = new HashSet<>();
// The set of all the print writers for all the clients, used for broadcast.
private static Set<PrintWriter> writers = new HashSet<>();
private ChatHub frame;
private int port;
private boolean online;
private ExecutorService pool;
public ChatServer(int port) throws IOException {
System.out.println("The chat server is running...");
this.frame = new ChatHub(this);
this.port = port;
this.online = true;
this.pool = Executors.newFixedThreadPool(500);
this.start();
}
#Override
public void run() {
while (this.online) {
try (ServerSocket listener = new ServerSocket(this.port)) {
this.pool.execute(new Handler(listener.accept(), this.names, this.writers));
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void stopChatServer() {
this.pool.shutdown();
this.online = false;
}
public Set<String> getNames() {
return this.names;
}
public Set<PrintWriter> getWriters() {
return this.getWriters();
}
public ChatHub getFrame() {
return this.frame;
}
public int getPort() {
return this.port;
}
}
Here I am trying to close the server:
import Client.ChatClient;
import Server.ChatServer;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class ChatHub extends JFrame{
JTextField textField;
JTextArea messageArea;
public ChatHub(ChatServer server) {
new JFrame("Chatter");
this.textField = new JTextField(50);
this.messageArea = new JTextArea(16,50);
this.textField.setEditable(true);
this.messageArea.setEditable(false);
this.getContentPane().add(this.textField, BorderLayout.SOUTH);
this.getContentPane().add(new JScrollPane(this.messageArea), BorderLayout.CENTER);
this.pack();
// this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
server.stopChatServer();
}
});
this.setVisible(true);
}
public void appendMessage(String line) {
messageArea.append(line + "\n");
}
public JTextField getTextField() {
return this.textField;
}
public JTextArea getMessageArea() {
return this.messageArea;
}
public void nameAccepted(String line) {
this.setTitle("Chatter - " + line.substring(13));
textField.setEditable(true);
}
}
Also I tried to have method run with while just printing some String. But when it left run method the program was still working. Any suggestions? Thanks in advance.
Also I tried to implement run() as the following:
#Override
public void run() {
while (this.online) {
System.out.println("Some String");
}
System.out.println(this.isAlive() + "\n");
}
And it does output true in the end.
Maybe you have another problem here (Swing Related):
Your new JFrame("Chatter") just creates a new JFrame and does nothing with it. You have to call super("Chatter"); to call the super constructor
Try
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE)
Have you tried to declare your online property as volatile?
private volatile boolean online = true;
If you do not declare a property as volatile, the JIT compiler can assume that your boolean property will not be changed by another thread. So it may optimize your run method to
public void run() {
if (!online)
return;
while(true) {
try(/*...*/) {
// ...
} catch(/*...*/) {
// ...
}
}
}

How to use method from another class without having the class

I have a method showMessage() that appends a string onto a JTextArea and i want to call it in my "class in the class" (ServerThread). How can i accomplish this without having Main main; or Main main = new Main();
public class Main extends JFrame {
private static final long serialVersionUID = 1L;
private JTextArea chatWindow;
private List<Integer> ports = new ArrayList<Integer>();
public Main() throws IOException {
super("ServerConsole");
chatWindow = new JTextArea();
chatWindow.setEditable(false);
JScrollPane scrollPane = new JScrollPane(chatWindow);
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane.setBounds(0, 20, 596, 200);
add(scrollPane);
setLayout(null);
setSize(600, 300);
setResizable(false);
setVisible(true);
getContentPane().setBackground(Color.white);
Socket s = null;
ServerSocket ss2 = null;
showMessage("Server Listening......\n");
try {
ss2 = new ServerSocket(3175);
} catch (IOException e) {
e.printStackTrace();
showMessage("Server error");
}
while (true) {
try {
s = ss2.accept();
showMessage("connection Established\n");
ports.add(s.getPort());
ServerThread st = new ServerThread(s);
st.start();
}
catch (Exception e) {
e.printStackTrace();
showMessage("Connection Error");
}
}
}
public void showMessage(final String m) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
chatWindow.append(m);
}
});
}
}
class ServerThread extends Thread {
private ObjectOutputStream output;
private ObjectInputStream input;
Socket s = null;
private static LinkedHashMap<Integer, String> playerCoords = new LinkedHashMap<Integer, String>();
public ServerThread(Socket s) {
this.s = s;
}
public void run() {
}
}
Example: in the run method i want to have something like main.showMessage(string) without having a Main object declared.
Just declare your method as static
public static void showMessage(final String m)
That way, you can call it like this -
Main.showMessage("Some String");
declare both showMessage method and chatWindow field static. Then you can call as Main.showMessage("whatever") where you want.
But a more elegant solution will be communicating these two singletons over listeners.
Declare an interface MessageListener with a method say onMessage(String message)
interface MessageListener {
public void onMessage(String message);
}
in ServerThread keep a list of MessageListeners and in run method invoke them
class ServerThread extends Thread {
// class content
static List<MessageListener> messageListeners = new ArrayList<>();
public void run() {
for (MessageListener messageListener : messageListeners) {
messageListener.onMessage("the message");
}
}
}
then make your Main class implementing MessageListener and in onMessage method call showMessage, also do not forget to register ServerThreads listener registry
public class Main extends JFrame implements MessageListener {
// class content
public Main() throws IOException {
super("ServerConsole");
ServerThread.messageListeners.add(this);
// other content
}
// class content
#Override
public void onMessage(String message) {
showMessage(message);
}
}
that's all. then the whole code looks like:
import java.awt.Color;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.ScrollPaneConstants;
import javax.swing.SwingUtilities;
public class Main extends JFrame implements MessageListener {
private static final long serialVersionUID = 1L;
private JTextArea chatWindow;
private List<Integer> ports = new ArrayList<Integer>();
public Main() throws IOException {
super("ServerConsole");
ServerThread.messageListeners.add(this);
chatWindow = new JTextArea();
chatWindow.setEditable(false);
JScrollPane scrollPane = new JScrollPane(chatWindow);
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane.setBounds(0, 20, 596, 200);
add(scrollPane);
setLayout(null);
setSize(600, 300);
setResizable(false);
setVisible(true);
getContentPane().setBackground(Color.white);
Socket s = null;
ServerSocket ss2 = null;
showMessage("Server Listening......\n");
try {
ss2 = new ServerSocket(3175);
} catch (IOException e) {
e.printStackTrace();
showMessage("Server error");
}
while (true) {
try {
s = ss2.accept();
showMessage("connection Established\n");
ports.add(s.getPort());
ServerThread st = new ServerThread(s);
st.start();
}
catch (Exception e) {
e.printStackTrace();
showMessage("Connection Error");
}
}
}
public void showMessage(final String m) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
chatWindow.append(m);
}
});
}
#Override
public void onMessage(String message) {
showMessage(message);
}
}
interface MessageListener {
public void onMessage(String message);
}
class ServerThread extends Thread {
private ObjectOutputStream output;
private ObjectInputStream input;
Socket s = null;
private static LinkedHashMap<Integer, String> playerCoords = new LinkedHashMap<Integer, String>();
static List<MessageListener> messageListeners = new ArrayList<>();
public ServerThread(Socket s) {
this.s = s;
}
public void run() {
for (MessageListener messageListener : messageListeners) {
messageListener.onMessage("the message");
}
}
}

JAVA - class and it's object, super

This is the class Gui.
import java.awt.BorderLayout;
import javax.swing.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.beans.PropertyChangeListener;
import javax.swing.JButton;
public class Gui extends JFrame{
Principal obiect;
public JButton heads = new JButton("Heads");
public JButton tails = new JButton("Tails");
public static JTextField display;
public JTextField comboul;
public JPanel panel = new JPanel();
public int predictie;
public Gui(){
super("HeadsOrTails");
panel.setLayout(new BorderLayout(100, 100));
panel.add(heads,BorderLayout.LINE_START);
panel.add(tails,BorderLayout.LINE_END);
panel.add(display,BorderLayout.CENTER); //HERE IS ERROR
panel.add(comboul,BorderLayout.PAGE_START);
}
public void dacaHeads(){
if(heads.getModel().isPressed()) predictie = 0;
}
public void dacaTails(){
if(tails.getModel().isPressed()) predictie = 1;
heads.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
dacaHeads();
obiect.flip();
if(predictie == obiect.returnStatus() ){
String s = comboul.getText();
int combo = Integer.valueOf(s);
s = Integer.toString(++combo);
comboul.setText(s);}
else{
String z = "0";
comboul.setText(z);
}
}
});
tails.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
dacaTails();
obiect.flip();
if(predictie == obiect.returnStatus() ){
String s = comboul.getText();
int combo = Integer.valueOf(s);
s = Integer.toString(++combo);
comboul.setText(s);}
else{
String z = "0";
comboul.setText(z);
}
}
});
}}
This is class Principal.
import javax.swing.*;
import java.util.Random;
public class Principal extends Gui {
public int combo;
public static Random bulion = new Random();
public static boolean sansa;
public static boolean input;
public int status;
//STATUS 0 = HEADS;
//STATUS 1 = TAILS;
public static void main(String[] args) {
Gui lee = new Gui(); //HERE IS ERROR
Principal obiect = new Principal();
lee.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
lee.setSize(500,500);
lee.setVisible(true);
}
public int flip(){
boolean sansa2 ;
sansa2 = bulion.nextBoolean();
if(sansa2){
status = 0;
display.setText("Heads");
}
else{
status = 1;
display.setText("Tails");
}
return status;
}
public int returnStatus(){
return status;
}
}
These are the errors :
FIXED:
//Exception in thread "main" java.lang.StackOverflowError
//at Gui.(Gui.java:19) // Super
//at Principal.(Principal.java:3) //public class Principal extends Gui
//at Gui.(Gui.java:9) //Principal obiect = new Principal()
NOW:
Exception in thread "main" java.lang.NullPointerException
at Gui.<init>(Gui.java:23)
at Principal.main(Principal.java:14)
It's my first post so i am sorry if you don't understand.I'll post more information if you need.
When you create a Gui instance, it creates a Principal instance (since the Gui class has a Prinicipal instance variable - Principal obiect = new Principal();) which is also a Gui instance, so you get an infinite chain of constructor calls, leading to StackOverflowError.
To avoid it change
Principal obiect = new Principal();
to
Principal obiect;
and initialize this instance after the Gui instance is created (i.e. after the call to Gui lee = new Gui(); in your main method).
For example, add to Gui class :
public void setPrincipal (Principal object)
{
this.object = object;
}
And in your main :
Gui lee = new Gui();
lee.setPrincipal (new Principal());

Swing,JTextAreas are blank

Class principal :
import javax.swing.*;
import java.util.Random;
public class Principal extends Guii {
public int combo;
public static Random bulion = new Random();
public static boolean sansa;
public static boolean input;
public int status;
//STATUS 0 = HEADS;
//STATUS 1 = TAILS;
public static void main(String[] args) {
Guii lee = new Guii();
Principal obiect = new Principal();
}
public int flip(){
boolean sansa2 ;
sansa2 = bulion.nextBoolean();
if(sansa2){
status = 0;
display.setText("Heads");
}
else{
status = 1;
display.setText("Tails");
}
return status;
}
public int returnStatus(){
return status;
}
}
Class Guii :
import java.awt.BorderLayout;
import javax.swing.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.beans.PropertyChangeListener;
import javax.swing.JButton;
import java.awt.Dimension;
public class Guii extends JFrame{
Principal obiect;
public JButton heads = new JButton("Heads");
public JButton tails = new JButton("Tails");
public JTextArea display = new JTextArea();
public JTextArea comboul = new JTextArea();
private JPanel panel;
public int predictie;
public Guii(){
super("Heads or Tails");
setContentPane(panel);
pack();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);}
public void dacaHeads(){
if(heads.getModel().isPressed()) predictie = 0;
}
public void dacaTails(){
if(tails.getModel().isPressed()) predictie = 1;
heads.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e){
dacaHeads();
obiect.flip();
if(predictie == obiect.returnStatus() ){
String s = comboul.getText();
int combo = Integer.valueOf(s);
s = Integer.toString(++combo);
comboul.setText("asdsaad");}
else{
String z = "0";
comboul.setText("asdasda");
}
}
});
tails.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e){
dacaTails();
obiect.flip();
if(predictie == obiect.returnStatus() ){
String s = comboul.getText();
int combo = Integer.valueOf(s);
s = Integer.toString(++combo);
comboul.setText(s);}
else{
String z = "0";
comboul.setText(z);
}
}
});}
The problem is that the window opens, i see everything but nothing happens when i press the buttons.
I used gui designer from intellij idea.
Thank you.
//Sorry for the second question.Deleted it.
I don't know if it is a mistake of writing your code but your function dacaTails(), which add the listener to the button, seems to be never called. You should put the addActionListener's functions in the constructor method, I think.

Use wait() in Java

I need to create a new JFrame in a new Thread.. When I close the JFrame I need to return a String.
The problem is that the wait() method "doesn't wait" the "notify()" of new Thread.
Thank's for your answer.
import java.awt.Button;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.LayoutManager;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class FinestraTesto extends Thread {
JLabel jdescr;
JTextArea testo;
JPanel pannelloTasti;
JButton bottoneInvio;
JButton bottoneAnnulla;
JFrame finestraTestuale;
JPanel panAll;
static Boolean pause = true;
String titolo;
String descrizione;
private static String testoScritto = "";
public String mostra() {
// Create a new thread
Thread th = new Thread(new FinestraTesto(titolo, descrizione));
th.start();
synchronized (th) {
try {
// Waiting the end of th.
th.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return testoScritto;
}
public void run() {
synchronized (this) {
System.out.println("Fatto 1 thread");
finestraTestuale = new JFrame(titolo);
finestraTestuale.setPreferredSize(new Dimension(600, 200));
finestraTestuale.setSize(600, 200);
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
finestraTestuale.setLocation(
dim.width / 2 - finestraTestuale.getSize().width / 2,
dim.height / 2 - finestraTestuale.getSize().height / 2);
panAll = new JPanel();
panAll.setLayout(new BoxLayout(panAll, BoxLayout.Y_AXIS));
bottoneInvio = new JButton("Conferma");
bottoneAnnulla = new JButton("Annulla");
pannelloTasti = new JPanel();
testo = new JTextArea();
testo.setPreferredSize(new Dimension(550, 100));
testo.setSize(550, 100);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setViewportView(testo);
jdescr = new JLabel(descrizione);
jdescr.setPreferredSize(new Dimension(550, 50));
jdescr.setSize(550, 50);
pannelloTasti.setLayout(new BoxLayout(pannelloTasti,
BoxLayout.X_AXIS));
pannelloTasti.add(bottoneInvio);
pannelloTasti.add(bottoneAnnulla);
panAll.add(jdescr);
panAll.add(scrollPane);
panAll.add(pannelloTasti);
finestraTestuale.add(panAll);
bottoneInvio.addActionListener(new ActionListener() {
#Override
/**
* metodo attivato quando c'è un'azione sul bottone
*/
public void actionPerformed(ActionEvent arg0) {
testoScritto = testo.getText();
pause = false;
finestraTestuale.show(false);
// send notify
notify();
}
});
bottoneAnnulla.addActionListener(new ActionListener() {
#Override
/**
* metodo attivato quando c'è un'azione sul bottone
*/
public void actionPerformed(ActionEvent arg0) {
pause = false;
testoScritto = "";
finestraTestuale.show(false);
// send notify
notify();
}
});
finestraTestuale.show();
}
}
public FinestraTesto(String titolo, String descrizione) {
this.titolo = titolo;
this.descrizione = descrizione;
}
}
You would better to use Synchronizers instead of wait and notify. They're more preferable because of simplicity and safety.
Given the difficulty of using wait and notify correctly, you should
use the higher-level concurrency utilities instead.
Effective Java (2nd Edition), Item 69
I solved with this class:
import java.awt.Dimension;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JRootPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class CustomDialog
{
private List<JComponent> components;
private String title;
private int messageType;
private JRootPane rootPane;
private String[] options;
private int optionIndex;
private JTextArea testo;
public CustomDialog(String title,String descrizione)
{
components = new ArrayList<>();
setTitle(title);
setMessageType(JOptionPane.PLAIN_MESSAGE);
addMessageText(descrizione);
testo = new JTextArea();
testo.setPreferredSize(new Dimension(550, 100));
testo.setSize(550, 100);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setViewportView(testo);
addComponent(scrollPane);
setRootPane(null);
setOptions(new String[] { "Send", "Cancel" });
setOptionSelection(0);
}
public void setTitle(String title)
{
this.title = title;
}
public void setMessageType(int messageType)
{
this.messageType = messageType;
}
public void addComponent(JComponent component)
{
components.add(component);
}
public void addMessageText(String messageText)
{
components.add(new JLabel(messageText));
}
public void setRootPane(JRootPane rootPane)
{
this.rootPane = rootPane;
}
public void setOptions(String[] options)
{
this.options = options;
}
public void setOptionSelection(int optionIndex)
{
this.optionIndex = optionIndex;
}
public String show()
{
int optionType = JOptionPane.OK_CANCEL_OPTION;
Object optionSelection = null;
if(options.length != 0)
{
optionSelection = options[optionIndex];
}
int selection = JOptionPane.showOptionDialog(rootPane,
components.toArray(), title, optionType, messageType, null,
options, optionSelection);
if(selection == 0)
return testo.getText();
else
return null;
}
}

Categories