Home > Archive > Java Help > January 2006 > Swing Threading issue?
You are viewing an archived Text-only version of the thread.
To view this thread in it's original format and/or if you want to reply to
this thread please [click here]
| Author |
Swing Threading issue?
|
|
| kitkit80@gmail.com 2006-01-25, 4:14 am |
| Hi,
My UI hangs whenever I m trying do something without threading. I'm
quite amatuer with threads and need help please.
How can i make my UI thread safe?
THANKS!
/**
*
* @author Ho Wai Kit
*/
import java.net.*;
import java.io.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.border.*;
public class Stratego extends JFrame implements ActionListener{
private static final int ROWS = 5;
private static final int COLUMNS = 5;
private final Card[][] cards = new Card[ROWS][COLUMNS];
private JPanel centerPnl, boardPnl, rightPnl;
private Client clientGame=null;
private Server serverGame=null;
private AIGame aiGame=null;
private Socket con;
boolean isStarted, isConnected, isClient, isServer;
private Card inHand, target;
private String otherHostname = "";
private JLabel statusLbl;
private JMenuItem menuItemNewGame;
private JMenuItem menuItemLoadFile;
private JMenuItem menuItemSave;
private JMenuItem menuItemSaveAs;
private JMenuItem menuItemConnect;
private JMenuItem menuItemCloseConnection;
private ConnectionManager conMan;
private GameLogic gl;
private Protocol protocol;
DataOutputStream output;
DataInputStream input;
private char[] pieces = {Card.FLAG, Card.BOMB, Card.BOMB,
Card.MARSHAL, Card.MINER, Card.CAPTAIN, Card.GENERAL, Card.CAPTAIN,
Card.GENERAL, Card.SPY};
/** Creates a new instance of Stratego */
public Stratego(){
super("Stratego");
initCenterPnl();
conMan = new ConnectionManager();
//menu bar
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu gameMenu = new JMenu("File");
JMenu settingsMenu = new JMenu("Network");
menuBar.add(gameMenu);
menuBar.add(settingsMenu);
menuItemNewGame = new JMenuItem("New game");
menuItemNewGame.addActionListener(new
java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt)
{
playAIGame();
}
});
gameMenu.add(menuItemNewGame);
menuItemLoadFile = new JMenuItem("Load file...");
menuItemLoadFile.addActionListener(new
java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt)
{
//if (isFileChanged())
// askForSaving();
JFileChooser fileChooser = new JFileChooser();
//fileChooser.setCurrentDirectory(new
java.io.File(fileChooserDir));
fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
fileChooser.resetChoosableFileFilters();
//fileChooser.addChoosableFileFilter(new
PGNFileFilter());
int choice = fileChooser.showOpenDialog(null);
if (choice == JFileChooser.APPROVE_OPTION) {
//loadFile(fileChooser.getSelectedFile());
//fileName =
fileChooser.getSelectedFile().getName();
//setTitle(TITLE + " - " + fileName);
//fileIsChanged = false;
}
}
});
gameMenu.add(menuItemLoadFile);
menuItemSave = new JMenuItem("Save");
menuItemSave.addActionListener(new
java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt)
{
//if (fileName != null && fileName.length() > 0) {
// save(fileName, false);
//} else {
// saveAs();
// }
}
});
gameMenu.add(menuItemSave);
menuItemSaveAs = new JMenuItem("Save as...");
menuItemSaveAs.addActionListener(new
java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt)
{
// saveAs();
}
});
gameMenu.add(menuItemSaveAs);
gameMenu.addSeparator();
JMenuItem item2 = new JMenuItem("Exit");
item2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt)
{
if (clientGame!=null||serverGame!=null) {
int choice =
JOptionPane.showConfirmDialog(null, "Are you
sure?", "Close connection?", JOptionPane.YES_NO_OPTION);
if (choice == JOptionPane.YES_OPTION) {
closeConnections();
} else
return;
}
System.exit(0);
}
});
gameMenu.add(item2);
JMenuItem serverSettingsItem = new JMenuItem("Host Game");
serverSettingsItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
playGameAsHost();
}
});
settingsMenu.add(serverSettingsItem);
menuItemConnect = new JMenuItem("Join Game");
menuItemConnect.addActionListener(new
java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt)
{
String input = JOptionPane.showInputDialog(null,
"Connect to IP : ");
if(input.trim().equals("")||input==null){
JOptionPane.showMessageDialog(null, "No IP
specified", "Error", JOptionPane.ERROR_MESSAGE);
}else{
playGameAsClient(input);
}
}
});
settingsMenu.add(menuItemConnect);
menuItemCloseConnection = new JMenuItem("Close connection");
menuItemCloseConnection.addActionListener(new
java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt)
{
int choice =
JOptionPane.showConfirmDialog(
null,
"Are you sure?",
"Close connection?",
JOptionPane.YES_NO_OPTION);
if (choice == JOptionPane.YES_OPTION) {
//boardConnector.closeConnection();
//connectionClosed();
}
}
});
settingsMenu.add(menuItemCloseConnection);
menuItemCloseConnection.setEnabled(false);
//end of menu
Container c = getContentPane();
c.setLayout(new BoxLayout(c, BoxLayout.Y_AXIS));
c.add(centerPnl, BorderLayout.CENTER);
}
public void initCenterPnl(){
centerPnl = new JPanel();
centerPnl.setLayout(new BoxLayout(centerPnl,
BoxLayout.X_AXIS));
boardPnl = new JPanel();
fillBoard();
boardPnl.setSize(450, 450);
boardPnl.setMinimumSize(new Dimension(450, 450));
boardPnl.setMaximumSize(new Dimension(450, 450));
initRightPnl();
centerPnl.add(boardPnl);
centerPnl.add(rightPnl);
}
public void initRightPnl(){
rightPnl = new JPanel();
statusLbl = new JLabel();
rightPnl.setBorder(BorderFactory.createTitledBorder("Game
Status"));
//rightPnl.setSize(100, 450);
rightPnl.add(statusLbl);
rightPnl.setMinimumSize(new Dimension(250, 450));
rightPnl.setMaximumSize(new Dimension(250, 450));
}
public void fillBoard(){
boardPnl.setLayout(new GridLayout(ROWS, COLUMNS, 1, 1));
boardPnl.setBorder(BorderFactory.createTitledBorder("Board"));
for(int i = 0; i < ROWS; i++)
{
for(int j = 0; j < COLUMNS; j++)
{
cards[i][j] = new Card(Card.GRASS, i, j);
cards[i][j].addActionListener(this);
cards[i][j].setXCoordinate(i);
cards[i][j].setYCoordinate(j);
boardPnl.add(cards[i][j]);
}
}
//initialise water
cards[2][2].setCardType(Card.WATER);
cards[2][2].drawImage(Card.WATER);
}
public void closeConnections(){
if(isServer&&isConnected){
conMan.allDone = true;
isServer = false;
}else if(isClient&&isConnected){
isServer = false;
}
try{
con.close();
}catch(Exception e){
e.printStackTrace();
}
isConnected = false;
}
public void playAIGame(){
newGameBoard();
aiGame = new AIGame(cards, this);
System.out.println("AI game started");
isStarted = true;
placeCards(cards, Card.RED_PLAYER);
}
public void playGameAsHost(){
try {
JDialog notify = new JDialog();
conMan.start();
JLabel notifyLbl = new JLabel("Listening for connection...
....\n", 0);
notify.setTitle("Server IP : "
+InetAddress.getLocalHost().getHostAddress());
notify.getContentPane().setLayout(new FlowLayout());
notify.getContentPane().add(notifyLbl);
notify.setLocation (400, 300);
notify.setSize (250, 90);
notify.setVisible(true);
//ServerSocket server = new
ServerSocket(ConnectionManager.PORT_NO,
ConnectionManager.MAX_CONNECTIONS);
while(true){
con = conMan.getConnection();
//con = server.accept();
if(con!=null){
notify.dispose();
break;
}
}
isServer = true;
isConnected = true;
//serverGame = new Server(this, con);
System.out.println("Hosting Game");
isStarted = true;
placeCards(cards, Card.RED_PLAYER);
//repaint();
protocol = new Protocol(con, this);
input = new DataInputStream(con.getInputStream());
output = new DataOutputStream(con.getOutputStream());
InputReader inReader = new InputReader(input, protocol);
inReader.start();
//gl = new GameLogic(this, protocol);
sendMessage("server cone");
//readInput();
}catch(Exception e){
e.printStackTrace();
}
}
public void playGameAsClient(String ip){
try{
con = new Socket(InetAddress.getByName(ip),
ConnectionManager.PORT_NO);
if(con.isConnected()){
isConnected = true;
isClient = true;
System.out.println("Joining game");
isStarted = true;
placeCards(cards, Card.BLUE_PLAYER);
//repaint();
//clientGame = new Client(this, con);
protocol = new Protocol(con, this);
//gl = new GameLogic(this, protocol);
input = new DataInputStream(con.getInputStream());
output = new DataOutputStream(con.getOutputStream());
//usage of thread to read data (works)
InputReader inReader = new InputReader(input,
protocol);
inReader.start();
//end
sendMessage(Protocol.ATTACK_NOTIFICATION);
//without implementing a thread(does not work)
//readInput();
}else{
JOptionPane.showMessageDialog(null, "Connection cannot
be established.\nServer might not be active.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}catch(Exception e){
e.printStackTrace();
}
}
//place the cards automatically(testing)
public void placeCards(Card[][] cards, String playerColor){
int k=0;
for(int i = 3; i < 5; i++){
for(int j = 0; j < COLUMNS; j++){
cards[i][j].setExposed(false);
cards[i][j].setOwn(true);
cards[i][j].setCardType(pieces[k]);
cards[i][j].setPlayerColor(playerColor);
cards[i][j].drawImage(pieces[k], playerColor, true,
false);
k++;
}
}
}
public void wonGame(){
if(aiGame!=null){
aiGame.killAI();
aiGame=null;
}
//clientGame=null;
//serverGame=null;
}
private void lostGame(){
}
public void newGameBoard(){
for(int i = 0; i < ROWS; i++){
for(int j = 0; j < COLUMNS; j++){
emptyField(cards[i][j], cards);
}
}
cards[2][2].setCardType(Card.WATER);
cards[2][2].drawImage(Card.WATER);
}
public void emptyField(Card inHand, Card[][] cards){
int x = inHand.getXCoordinate();
int y = inHand.getYCoordinate();
cards[x][y].setCardType(Card.GRASS);
cards[x][y].setExposed(false);
cards[x][y].setOwn(false);
cards[x][y].drawImage(Card.GRASS);
cards[x][y].setSelected(false);
cards[x][y].setPlayerColor(Card.NULL_PLAYER);
}
public void sendMessageToLbl(String msg){
statusLbl.setText(msg);
}
public void actionPerformed(ActionEvent e){
Card card = null;
if(isStarted){
card = (Card)e.getSource();
if(aiGame!=null){
if(card.getCardType()!=Card.WATER){
if((inHand==null||inHand==card)&&card.isOwn()){
if(card.getCardType()!=Card.BOMB&&card.getCardType()!=Card.FLAG){
inHand = aiGame.selectCard(card, cards);
}
}else{
target=card;
if(aiGame.move(inHand, target, cards)){
inHand=null;
target=null;
}
}
}
}else if(isConnected){
if(card.getCardType()!=Card.WATER){
if((inHand==null||inHand==card)&&card.isOwn()){
if(card.getCardType()!=Card.BOMB&&card.getCardType()!=Card.FLAG){
inHand = gl.selectCard(card, cards);
}
}else{
target=card;
if(gl.move(inHand, target, cards,
Card.BLUE_PLAYER)){
inHand=null;
target=null;
}else{
JOptionPane.showMessageDialog(null, "You cannot
move back and forth between two tiles for three consecutive
turns!\nPlease try again.", "Invalid move", JOptionPane.ERROR_MESSAGE);
}
}
}
}
}
repaint();
}
public void paint(Graphics g){
super.paint(g);
}
public static void main(String args[]) {
JFrame.setDefaultLookAndFeelDecorated(true);
Stratego t = new Stratego();
try{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}catch(Exception e){
}
t.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
t.setSize(600, 500);
//t.setResizable(false);
t.setVisible(true);
}
public void sendMessage(String msg){
try{
output.writeUTF(msg);
output.flush();
}catch(Exception e){
e.printStackTrace();
}
}
public void readInput(){
while(true){
String msg="";
try{
msg = input.readUTF();
}catch(Exception e){
}
if(msg!=null&&!msg.equals("")){
System.out.println(msg);
protocol.handleInput(msg);
msg="";
}
}
}
}
| |
| Roedy Green 2006-01-25, 4:14 am |
| On 24 Jan 2006 22:36:23 -0800, kitkit80@gmail.com wrote, quoted or
indirectly quoted someone who said :
>How can i make my UI thread safe?
see http://mindprod.com/jgloss/threadsafe.html
and follow links.
--
Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.
| |
|
|
|
|
|