I have been trying to get a scroll bar on my JTextArea for days, I've tried every way to do it as I could find. I am making a Chat Client and I have the JPanel setup with a null layout. I've tried using the Layout Managers but I don't understand how to get it to look the way I want.
I just want a scroll bar on the text area. I'm a beginner and for what I've read it isn't possible to have one with a null layout? I'm open to help changing the layout if that's easier also.
package guiserver;
import com.apple.eawt.Application;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.WindowConstants;
public class GUIserver extends JFrame implements ActionListener {
JFrame login = new JFrame();
JPanel panel = new JPanel();
JPanel main = new JPanel();
JFrame accept = new JFrame();
JPanel acpt = new JPanel();
JPanel buttonpanel = new JPanel();
JButton acceptinvite = new JButton("Accept Invite");
JButton denyinvite = new JButton("Deny Invite");
JLabel acceptlabel = new JLabel();
JLabel acceptname = new JLabel();
JPanel loginpanel = new JPanel();
JTextArea chat = new JTextArea(" Waiting to Start Client...");
JSplitPane chatsplit = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
JTextField input = new JTextField();
JScrollPane pane = new JScrollPane(chat);
JButton send = new JButton("Send");
JLabel IP = new JLabel("IP:... ");
JButton start = new JButton("Start");
sendThread s1 = new sendThread();
fromThread f1 = new fromThread();
infoFromThread f2 = new infoFromThread();
infoToThread s2 = new infoToThread();
RPSpickTimer pt = new RPSpickTimer();
myCanvas contact = new myCanvas();
myCanvas logo = new myCanvas();
JButton rock = new JButton("Rock");
JButton paper = new JButton("Paper");
JButton scissors = new JButton("Scissors");
JTextField username = new JTextField();
JLabel loguser = new JLabel("Username:");
JLabel logpass = new JLabel("Password:");
JPasswordField password = new JPasswordField();
JButton signin = new JButton("Sign in");
String inputText = "0";
String chatCurrent;
String out1;
String in;
boolean pause = true;
boolean rps = false;
int P1pick = 0;
int P2pick = 0;
String user = "User 1";
String user2 = "Jacob Abthorpe";
String pass;
int badge;
int sendinvite = 0;
char answerinvite = '-';
boolean pauseInfo = true;
int winner = 0;
public GUIserver() {
Application application = Application.getApplication();
Image image = Toolkit.getDefaultToolkit().getImage("src/icon.png");
application.setDockIconImage(image);
login.setVisible(true);
login.setSize(400, 500);
login.setLocationRelativeTo(null);
login.setTitle("Login");
login.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
login.add(loginpanel);
loginpanel.setLayout(null);
loginpanel.add(username);
loginpanel.add(password);
loginpanel.add(signin);
loginpanel.add(logpass);
loginpanel.add(loguser);
loginpanel.add(logo);
login.setAlwaysOnTop(true);
username.setHorizontalAlignment(JTextField.CENTER);
password.setHorizontalAlignment(JTextField.CENTER);
username.setBounds(50, 290, 300, 30);
password.setBounds(50, 350, 300, 30);
loguser.setBounds(55, 265, 300, 30);
logpass.setBounds(55, 325, 300, 30);
signin.setBounds(150, 400, 100, 30);
logo.setBounds(110, 50, 150, 150);
username.addActionListener(this);
password.addActionListener(this);
signin.addActionListener(this);
setVisible(false);
setSize(500, 600);
setLocationRelativeTo(null);
setTitle("Chat Server Client");
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setAlwaysOnTop(true);
panel.setLayout(null);
panel.setLocation(300, 0);
panel.add(pane);
panel.add(input);
panel.add(send);
panel.add(IP);
panel.add(start);
panel.add(rock);
panel.add(paper);
panel.add(scissors);
contact.picx = 120;
contact.picy = 120;
contact.setBackground(Color.white);
contact.setBounds(370, 10, 120, 120);
panel.add(contact);
input.addActionListener(this);
send.addActionListener(this);
start.addActionListener(this);
rock.addActionListener(this);
paper.addActionListener(this);
scissors.addActionListener(this);
chat.setEditable(false);
pane.setBounds(10, 10, 350, 450);
input.setEditable(false);
input.setBounds(10, 470, 350, 80);
start.setBounds(370, 470, 115, 80);
IP.setBounds(15, 520, 480, 80);
rock.setVisible(false);
paper.setVisible(false);
scissors.setVisible(false);
scissors.setBounds(370, 430, 115, 30);
paper.setBounds(370, 400, 115, 30);
rock.setBounds(370, 370, 115, 30);
setContentPane(panel);
accept.setVisible(false);
accept.setSize(400, 125);
accept.setLocationRelativeTo(null);
accept.setTitle("Rock, Paper, Scissors");
accept.setAlwaysOnTop(true);
accept.setResizable(false);
accept.add(acpt);
acpt.setLayout(null);
acpt.add(acceptlabel);
acpt.add(buttonpanel);
acpt.add(acceptname);
buttonpanel.setBounds(0, 60, 400, 40);
buttonpanel.setLayout(new FlowLayout());
acceptlabel.setHorizontalAlignment(SwingConstants.CENTER);
acceptlabel.setText("would like to play Rock, Paper, Scissors. Accept?");
acceptlabel.setBounds(0, 25, 400, 40);
acceptname.setHorizontalAlignment(SwingConstants.CENTER);
acceptname.setText(user2 + "");
acceptname.setBounds(0, 3, 400, 40);
buttonpanel.add(acceptinvite);
buttonpanel.add(denyinvite);
acceptinvite.addActionListener(this);
denyinvite.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == input) {
if (input.getText().startsWith("/")) {
if (input.getText().contentEquals("/")) {
chat.append("\n\n >Type '/help' for list of all commands");
}
if (input.getText().contentEquals("/start RPS")) {
chat.append("\n \n >Waiting for opponent to accept invite. . .");
pauseInfo = false;
sendinvite = 10;
}
if (input.getText().contentEquals("/help")) {
chat.append("\n\n >Type '/help' for list of all commands");
chat.append("\n >Type '/start RPS' to play Rock Paper Scissors");
chat.append("\n >Type '/end' to quit current game");
}
if (input.getText().contentEquals("/end")) {
if (rps == true) {
chat.append("\n\n >Quiting Rock, Paper, Scissors. . .");
rps = false;
rock.setVisible(false);
paper.setVisible(false);
scissors.setVisible(false);
}
}
input.setText("");
} else {
if ((input.getText().contentEquals("")) && (input.getText().contentEquals(" "))) {
Toolkit.getDefaultToolkit().beep();
} else {
pause = false;
chat.append("\n \n " + user + " says: \n " + input.getText());
inputText = input.getText();
input.setText("");
}
}
}
if (e.getSource() == send) {
//chat.append("\n \n Dale Schmidt says: \n " + inputText);
//pause = false;
}
if (e.getSource() == username) {
user = username.getText();
}
if (e.getSource() == signin) {
login.setVisible(false);
setVisible(true);
}
if (e.getSource() == start) {
try {
s1.start();
f1.start();
s2.start();
f2.start();
setAlwaysOnTop(false);
chat.append("\n " + InetAddress.getLocalHost() + "\n Server started.");
IP.setText("IP: " + InetAddress.getLocalHost());
start.setVisible(false);
send.setVisible(true);
input.setEditable(true);
send.setBounds(370, 470, 115, 80);
} catch (Exception s) {
System.out.print("YOLOerror starting server");
}
}
if (e.getSource() == rock) {
if ((rps == true) && (P1pick == 0)) {
P1pick = 1;
chat.append("\n\n >You picked 'Rock'");
if (P2pick != 0) {
pt.start();
}
}
}
if (e.getSource() == paper) {
if ((rps == true) && (P1pick == 0)) {
P1pick = 2;
chat.append("\n\n >You picked 'Paper'");
if (P2pick != 0) {
pt.start();
}
}
}
if (e.getSource() == scissors) {
if ((rps == true) && (P1pick == 0)) {
P1pick = 3;
chat.append("\n\n >You picked 'Scissors'");
if (P2pick != 0) {
pt.start();
}
}
}
if (e.getSource() == acceptinvite) {
rps = true;
rock.setVisible(true);
paper.setVisible(true);
scissors.setVisible(true);
answerinvite = 'y';
accept.dispose();
}
if (e.getSource() == denyinvite) {
answerinvite = 'n';
accept.dispose();
}
}
class myCanvas extends Canvas {
int x = 10, y = 10;
int picx = 150, picy = 150;
public void paint(Graphics g) {
Image image1 = Toolkit.getDefaultToolkit().getImage("src/icon.png");
g.drawImage(image1, x, y, picx, picy, this);
}
}
class sendThread extends Thread {
ServerSocket s1;
Socket sendclientSocket = null;
public void run() {
inputText = input.getText();
try {
System.err.println("Starting Send Server");
System.out.println(InetAddress.getLocalHost());
s1 = new ServerSocket(4444);
sendclientSocket = s1.accept();
System.err.println("Started Send Server");
} catch (Exception s1) {
System.exit(1);
}
while (true) {
try {
PrintWriter out = new PrintWriter(sendclientSocket.getOutputStream(), true);
if (pause == false) {
badge = 0;
out.println(input.getText());
System.out.println("sent");
pause = true;
}
} catch (Exception e) {
System.err.println("Error Sending.");
System.err.println(e.getMessage());
System.exit(2);
}
}
}
}
class fromThread extends Thread {
ServerSocket s2;
Socket fromclientSocket = null;
public void run() {
try {
System.err.println("Starting Recieve Server");
s2 = new ServerSocket(4441);
fromclientSocket = s2.accept();
System.err.println("Started Recieve Server");
} catch (Exception s2) {
System.exit(1);
}
while (true) {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(fromclientSocket.getInputStream()));
String fromClient = in.readLine();
if (fromClient.contentEquals("")) {
} else {
Toolkit.getDefaultToolkit().beep();
chat.append("\n\n " + user2 + " says:\n " + fromClient);
badge++;
Application.getApplication().setDockIconBadge(Integer.toString(badge));
}
} catch (Exception e) {
System.err.println("Error Receiving.");
System.err.println(e.getMessage());
System.exit(3);
}
}
}
}
class infoFromThread extends Thread {
ServerSocket s3;
Socket infoFromClientSocket = null;
public void run() {
try {
s3 = new ServerSocket(4446);
infoFromClientSocket = s3.accept();
} catch (Exception s3) {
System.exit(7);
}
while (true) {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(infoFromClientSocket.getInputStream()));
String infoFromClient = in.readLine();
if (infoFromClient.contentEquals("10")) {
accept.setVisible(true);
sendinvite = 0;
} else if (infoFromClient.contentEquals("y")) {
chat.append("\n >Invite Accepted");
rps = true;
rock.setVisible(true);
paper.setVisible(true);
scissors.setVisible(true);
answerinvite = '-';
} else if (infoFromClient.contentEquals("n")) {
chat.append("\n\n >Invite Declined");
answerinvite = '-';
} else if (infoFromClient.contentEquals("1")) {
chat.append("\n\n >Opponent made selection");
P2pick = 1;
if (P1pick != 0) {
pt.start();
}
} else if (infoFromClient.contentEquals("2")) {
chat.append("\n\n >Opponent made selection");
P2pick = 2;
if (P1pick != 0) {
pt.start();
}
} else if (infoFromClient.contentEquals("3")) {
chat.append("\n\n >Opponent made selection");
P2pick = 3;
if (P1pick != 0) {
pt.start();
}
}
} catch (Exception e) {
System.err.println("Error Receiving Information.");
System.err.println(e.getMessage());
System.exit(3);
}
}
}
}
class infoToThread extends Thread {
ServerSocket s4;
Socket infoToClientSocket = null;
public void run() {
inputText = input.getText();
try {
s4 = new ServerSocket(4447);
infoToClientSocket = s4.accept();
} catch (Exception s4) {
System.exit(8);
}
while (true) {
try {
PrintWriter out = new PrintWriter(infoToClientSocket.getOutputStream(), true);
if (sendinvite == 10) {
out.println(sendinvite);
sendinvite = 0;
pauseInfo = false;
}
if ((answerinvite == 'y') || (answerinvite == 'n')) {
out.println(answerinvite);
answerinvite = '-';
}
if (winner == 1) {
out.println("Loser");
}
else if (winner == 2) {
out.println("Winner");
}
else if (winner == 3) {
out.println("Tie");
}
//winner = 0;
//System.err.println("infoToClient");
} catch (Exception e) {
System.err.println("Error Sending Information.");
System.err.println(e.getMessage());
System.exit(2);
}
}
}
}
class RPSpickTimer extends Thread {
public void run() {
while (true) {
try {
if (P1pick != 0) {
if (P1pick == 1) {
if (P2pick == 1) {
//tie
chat.append("\n\n Tie!");
winner = 3;
} else if (P2pick == 2) {
//P2wins
chat.append("\n\n " + user2 + " wins!");
winner = 2;
} else if (P2pick == 3) {
//P1wins
chat.append("\n\n " + user + " wins!");
winner = 1;
}
} else if (P1pick == 2) {
if (P2pick == 1) {
//P1wins
chat.append("\n\n " + user + " wins!");
winner = 1;
} else if (P2pick == 2) {
//tie
chat.append("\n\n Tie!");
winner = 3;
} else if (P2pick == 3) {
//P2wins
chat.append("\n\n " + user2 + " wins!");
winner = 2;
}
} else if (P1pick == 3) {
if (P2pick == 1) {
//P2wins
chat.append("\n\n " + user2 + " wins!");
winner = 2;
} else if (P2pick == 2) {
//P1wins
chat.append("\n\n " + user + " wins!");
winner = 1;
} else if (P2pick == 3) {
//tie
chat.append("\n\n Tie!");
winner = 3;
}
}
P1pick = 0;
P2pick = 0;
}
else {
sleep(250);
}
} catch (Exception e) {
System.err.println("Error Picking Winner.");
System.err.println(e.getMessage());
System.exit(2);
}
}
}
}
public static void main(String[] args) {
GUIserver s = new GUIserver();
}`
This line:
panel.add(chat);
Instead of adding chat, add pane, like:
panel.add(pane);
From JTextArea docs "The java.awt.TextArea internally handles scrolling. JTextArea is different in that it doesn't manage scrolling, but implements the swing Scrollable interface. This allows it to be placed inside a JScrollPane if scrolling behavior is desired, and used directly if scrolling is not desired."
I think that means that this is what you want:
JTextArea chat = new JTextArea(" Waiting to Start Client...");
JScrollPane chatScrollPane = new JScrollPane(chat);
...
panel.setLocation(300, 0);
panel.add(chatScrollPane);
panel.add(input);
As Nicolás Carlo pointed out, you already have the JScrollPane and just need to add it instead of the JTextArea. Basically the Java UI system (and most UI systems) are a giant tree of widgets. If you don't add a widget to the tree it doesn't have an effect. In this case, the JScrollPane wasn't getting added to the tree and therefore wasn't doing anything for you.
This is not an answer, but a demonstration of how a LayoutManager might be used to achieve the OP's results
So, based on your code example, I get this output...
I hope you note that the frame isn't big enough to hold the content, this is the major problem with null layouts, they never look the same on other systems...
And by utilising a GridBagLayout and a GridLayout and a concept known as "compound layouts", I was able to mock this...
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class ChatLayout {
public static void main(String[] args) {
new ChatLayout();
}
public ChatLayout() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new ChatPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class ChatPane extends JPanel {
private JTextArea chatWindow;
private JTextField input;
private JLabel ipLabel;
private JButton rockBtn;
private JButton paperBtn;
private JButton scissorsBtn;
private JButton startBtn;
public ChatPane() {
JPanel leftPane = new JPanel(new GridBagLayout());
JPanel rightPane = new JPanel(new GridBagLayout());
chatWindow = new JTextArea(20, 40);
chatWindow.setText("Waiting to start chat...");
input = new JTextField(10);
ipLabel = new JLabel("IP...");
rockBtn = new JButton("Rock");
paperBtn = new JButton("Paper");
scissorsBtn = new JButton("Scissors");
startBtn = new JButton("Start");
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(4, 4, 4, 4);
gbc.gridx = 0;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.BOTH;
gbc.weighty = 1;
gbc.weightx = 1;
leftPane.add(new JScrollPane(chatWindow), gbc);
gbc.gridy++;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weighty = 0;
gbc.weightx = 1;
gbc.gridheight = 1;
leftPane.add(input, gbc);
gbc.gridy++;
gbc.fill = GridBagConstraints.HORIZONTAL;
leftPane.add(ipLabel, gbc);
JPanel buttonsPane = new JPanel(new GridLayout(3, 1));
buttonsPane.add(rockBtn);
buttonsPane.add(paperBtn);
buttonsPane.add(scissorsBtn);
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.SOUTH;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weighty = 1;
rightPane.add(buttonsPane, gbc);
gbc.gridy++;
gbc.insets = new Insets(8, 0, 0, 0);
gbc.fill = GridBagConstraints.BOTH;
gbc.anchor = GridBagConstraints.CENTER;
gbc.weighty = 0;
gbc.gridheight = 2;
gbc.ipadx = 30;
gbc.ipady = 30;
rightPane.add(startBtn, gbc);
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1;
gbc.weighty = 1;
gbc.fill = GridBagConstraints.BOTH;
add(leftPane, gbc);
gbc.gridx++;
gbc.weightx = 0;
gbc.weighty = 1;
add(rightPane, gbc);
}
}
}
Now, this is just an example. You needs might be different which would require using different layout managers or using them in different combinations...
Related
I am trying to use a JButton based keyboard in a GUI based game of Hangman. However when I want to check that the key pressed is in the hidden word, I am not sure where I need to change the type from String to char. I want to use the GUI based keyboard instead of allowing the user to use the keyboard, to try and minimise the validation that needs to be done. These are the classes that I have created thus far. I am struggling to get this working.
package guis;
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;
public class MouseClick extends JFrame implements ActionListener, MouseListener
{
private static final long serialVersionUID = 1L;
private static ActionListener letterHandler = null;
private Container cPane;
private JLabel lblTitle, lblTries, lblCountryToGuess, chancesLabel, message;//, usedLettersPanel;
private JButton btnExit, btnStart, btn1, btn3, btn4, btnX;
private JButton [] btn = new JButton[26];
private JPanel pNorth, pSouth, pEast, pWest, pCenter, wordPanel, messagePanel, usedLettersPanel, hangPanel, drawingFrame;//, lblCountryToGuess;
private JMenuItem mIRules, mIDev, mIRestart, mIExit;
private javax.swing.JLabel jLabel1;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenu jMenu2;
private javax.swing.JMenu jMenu3;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JMenuItem jMenuItem1;
private javax.swing.JMenuItem jMenuItem3;
private javax.swing.JMenuItem jMenuItem4;
private javax.swing.JMenuItem jMenuItem5;
private javax.swing.JPopupMenu.Separator jSeparator1;
private JFrame frame = new JFrame();
private JButton enter;
private JLabel[] wordArray, usedLetters;
//private JFrame drawingFrame;
private HangmanDrawing drawing;
private char[] incorrectGuesses;
private char[] buttonLetters = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };
private String word;
private int chances;
char input;
private JFrame endFrame;
private JPanel top, bottom;
private JLabel doNow;
private JButton restart, exit;
MouseClick() throws IOException
{
super("Assignment 2 - Hangman");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
word = new WordHandler().getRandomWord();
chances = 7;
cPane = getContentPane();
cPane.setBackground(new Color (236, 128, 19));
pNorth = new JPanel();
pSouth = new JPanel();
pEast = new JPanel();
pWest = new JPanel();
pCenter = new JPanel();
lblTitle = new JLabel(" Hangman ", SwingConstants.CENTER);
lblTitle.setFont(new Font("Comic Sans MS", Font.BOLD, 24));
lblTitle.setBorder(BorderFactory.createRaisedBevelBorder());
lblTitle.setBackground(new Color (38, 29, 226));
lblTitle.setOpaque(true);
lblTitle.setForeground(Color.white);
pNorth.add(lblTitle);
/*lblCountryToGuess = new JLabel("", SwingConstants.CENTER);
lblCountryToGuess.setFont(new Font("Comic Sans MS", Font.BOLD, 24));
//lblCountryToGuess.setLayout(new FlowLayout(FlowLayout.CENTER, 15, 5));
lblCountryToGuess.setBounds(50, 1, 500, 60);
lblCountryToGuess.setBorder(BorderFactory.createTitledBorder("This is the country to be guessed..."));
//wordArray = new JLabel [hiddenCountry.length()];
//for (int i = 0 ; i < wordArray.length ; i++)
//{
// wordArray[i] = new JLabel("_");
// wordArray[i].setFont(new Font("Comic Sans MS.", Font.BOLD, 23));
// lblTitle4.add(wordArray[i]);
//}
pCenter.add(lblCountryToGuess);*/
hangPanel = new HangmanDrawing();
//drawing = new HangmanDrawing();
drawingFrame = new JPanel();
//drawingFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
//drawingFrame.setFocusableWindowState(false);
//drawingFrame.getContentPane().add(drawing);
//int xPosition = (int) ((scrnsize.width / 2) + (this.getWidth() / 2));
//drawingFrame.setSize(scrnsize.width - xPosition - 10,
//scrnsize.width - xPosition - 10);
// drawingFrame.setLocation(xPosition,
//(int) (scrnsize.height - this.getHeight())/3);
setVisible (true);
drawingFrame.setVisible(true);
pCenter.add(drawingFrame);
wordPanel = new JPanel();
wordPanel.setBounds(100, 100, 100, 60);
wordPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 15, 5));
wordPanel.setBorder(BorderFactory.createTitledBorder("This is the country to guess..."));
wordArray = new JLabel [word.length()];
for (int i = 0 ; i < wordArray.length ; i++)
{
wordArray[i] = new JLabel("_");
wordArray[i].setFont(new Font("Arial", Font.BOLD, 23));
wordPanel.add(wordArray[i]);
}
pCenter.add(wordPanel);
usedLettersPanel = new JPanel();
usedLettersPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 13, 5));
incorrectGuesses = new char [chances];
usedLetters = new JLabel [incorrectGuesses.length];
for (int i = 0 ; i < usedLetters.length ; i++)
{
usedLetters[i] = new JLabel("~");
usedLetters[i].setFont(new Font("Comic Sans MS", Font.BOLD, 18));
usedLettersPanel.add(usedLetters[i]);
}
pCenter.add(usedLettersPanel);
messagePanel = new JPanel();
messagePanel.setLayout (new FlowLayout (FlowLayout.LEFT));
message = new JLabel ("Guess a letter...");
message.setFont (new Font ("Comic Sans MS", Font.BOLD, 17));
messagePanel.add(message);
pCenter.add(messagePanel);
/*usedLettersPanel = new JLabel();
usedLettersPanel.setFont(new Font("Comic Sans MS", Font.BOLD, 24));
usedLettersPanel.setBounds(50, 1, 500, 60);
usedLettersPanel.setBorder(BorderFactory.createTitledBorder("Letters already guessed..."));
//usedLettersPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 13, 5));
//incorrectGuesses = new char [chances];
//usedLetters = new JLabel [incorrectGuesses.length];
//for (int i = 0 ; i < usedLetters.length ; i++)
//{
//usedLetters[i] = new JLabel("~");
//usedLetters[i].setFont(new Font("Comic Sans MS", Font.BOLD, 18));
//usedLettersPanel.add(usedLetters[i]);
//}
pCenter.add(usedLettersPanel);*/
btnStart = new JButton(" Start / New Game ");
btnStart.setFont(new Font("Comic Sans MS", Font.BOLD, 12));
btnStart.setBackground(Color.GREEN);
btnStart.setForeground(Color.white);
btnStart.setOpaque(true);
btnStart.setBorder(BorderFactory.createRaisedBevelBorder());
pWest.add(btnStart);
btnStart.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
dispose();
jMenuItem1.setVisible(true);
MouseClick sample = null;
try
{
sample = new MouseClick();
}
catch (IOException e1)
{
e1.printStackTrace();
}
sample.setTitle("Assignment 2 - Hangman Game");
sample.setSize(1200, 800);
sample.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
sample.setVisible(true);
}// end actionPerformed method
});
chancesLabel = new JLabel (chances + " chances left...");
chancesLabel.setFont (new Font ("Comic Sans MS", Font.BOLD, 17));
//lblTries = new JLabel(" Tries Remaining ");
//lblTries.setFont(new Font("Comic Sans MS", Font.BOLD, 12));
chancesLabel.setBackground(new Color (38, 29, 226));
chancesLabel.setForeground(Color.white);
chancesLabel.setOpaque(true);
chancesLabel.setBorder(BorderFactory.createRaisedBevelBorder());
pWest.add(chancesLabel);
btnExit = new JButton(" Exit Game");
btnExit.setFont(new Font("Comic Sans MS", Font.BOLD, 12));
btnExit.setBackground(new Color (236, 19, 35));
btnExit.setForeground(Color.white);
btnExit.setBorder(BorderFactory.createRaisedBevelBorder());
pWest.add(btnExit);
for(int i = 0; i < 26; i++)
{
//JButton btnX = new JButton();
btnX = new JButton(new KeyboardListener(buttonLetters[i]));
btnX.setText("" + buttonLetters[i]);
pSouth.add(btnX);
btnX.setVisible(true);
//btn[i] = btnX;
//btn[i].setText("" + (char)('A'+ i));
//btn[i].setText("" + buttonLetters[i]);
//input = buttonLetters[i];
//pSouth.add(btn[i]);
//btn[i].setVisible(true);
}
cPane.add(pNorth, BorderLayout.NORTH);
cPane.add(pSouth, BorderLayout.SOUTH);
pSouth.setLayout(new GridLayout(3,10,1,1));
cPane.add(pWest, BorderLayout.WEST);
pWest.setLayout(new GridLayout(3,1,1,10));
cPane.add(pEast, BorderLayout.EAST);
cPane.add(pCenter, BorderLayout.CENTER);
pCenter.setLayout(new GridLayout(4, 1, 1, 1));
/*Container chancesContainer = new Container();
chancesContainer.setLayout(new FlowLayout (FlowLayout.RIGHT));
chancesContainer.add(chancesLabel);
JPanel wrongGuessesContainer = new JPanel();
wrongGuessesContainer.setLayout(new GridLayout (1, 2));
wrongGuessesContainer.setBorder(BorderFactory.createTitledBorder ("Wrong Guesses"));
wrongGuessesContainer.add(usedLettersPanel);
wrongGuessesContainer.add (chancesContainer);
Container bottomContainer = new Container();
bottomContainer.setLayout(new BorderLayout());
bottomContainer.add(wrongGuessesContainer, BorderLayout.NORTH);
bottomContainer.add(messagePanel, BorderLayout.SOUTH);
getContentPane().setLayout(new BorderLayout());
//getContentPane().add (inputPanel, BorderLayout.NORTH);
getContentPane().add(wordPanel, BorderLayout.CENTER);
getContentPane().add(bottomContainer, BorderLayout.SOUTH);*/
btnExit.addActionListener(this);
pCenter.addMouseListener(this);
pNorth.addMouseListener(this);
pSouth.addMouseListener(this);
pEast.addMouseListener(this);
pWest.addMouseListener(this);
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
jMenuItem1 = new javax.swing.JMenuItem();
jMenu2 = new javax.swing.JMenu();
jMenuItem3 = new javax.swing.JMenuItem();
jSeparator1 = new javax.swing.JPopupMenu.Separator();
jMenuItem4 = new javax.swing.JMenuItem();
jMenu3 = new javax.swing.JMenu();
jMenuItem5 = new javax.swing.JMenuItem();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jMenu1.setText("File");
jMenuItem1.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_N, java.awt.event.InputEvent.CTRL_MASK));
jMenuItem1.setText("New Game");
jMenuItem1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
dispose();
jMenuItem1.setVisible(true);
MouseClick sample = null;
try
{
sample = new MouseClick();
}
catch (IOException e1)
{
e1.printStackTrace();
}
sample.setTitle("Assignment 2 - Hangman Game");
sample.setSize(1200, 800);
sample.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
sample.setVisible(true);
}// end actionPerformed method
});
jMenu1.add(jMenuItem1);
jMenuBar1.add(jMenu1);
jMenu2.setText("Help");
jMenuItem3.setText("Rules");
jMenuItem3.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
JOptionPane.showMessageDialog(frame, "Hangman is a guessing game where the word"
+"\n to guess is represented by dashes. The player"
+"\n is given the option to enter a letter. If the letter"
+"\n guessed is contained in the word, the letter will"
+"\n replace the dash in its approprate placement."
+"\n You cannot exceed 7 wrong guesses or else you"
+"\n lose. Words are selected randomly.", "Instructions",
JOptionPane.INFORMATION_MESSAGE);
}
});
jMenu2.add(jMenuItem3);
jMenu2.add(jSeparator1);
jMenuItem4.setText("Developer");
jMenuItem4.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
JOptionPane.showMessageDialog(frame, "Developer: Ryan Smith");
}
});
jMenu2.add(jMenuItem4);
jMenuBar1.add(jMenu2);
jMenu3.setText("Exit");
jMenuItem5.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F4, java.awt.event.InputEvent.ALT_MASK));
jMenuItem5.setText("Exit Game");
jMenuItem5.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
jMenu3.add(jMenuItem5);
jMenuBar1.add(jMenu3);
setJMenuBar(jMenuBar1);
pack();
/*drawing = new HangmanDrawing();
drawingFrame = new JFrame();
drawingFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
drawingFrame.setFocusableWindowState(false);
drawingFrame.getContentPane().add(drawing);
int xPosition = (int) ((scrnsize.width / 2) + (this.getWidth() / 2));
drawingFrame.setSize(scrnsize.width - xPosition - 10,
scrnsize.width - xPosition - 10);
drawingFrame.setLocation(xPosition,
(int) (scrnsize.height - this.getHeight())/3);
setVisible (true);
drawingFrame.setVisible(true);*/
}
private void endGame()
{
enter.removeActionListener (this);
//inputField.removeActionListener(this);
//inputField.setEditable (false);
endFrame = new JFrame();
top = new JPanel();
bottom = new JPanel();
doNow = new JLabel ("What do you want to do now?");
restart = new JButton ("Start Again");
exit = new JButton ("Exit Hangman");
doNow.setFont (new Font ("Verdana", Font.BOLD, 17));
top.setLayout (new FlowLayout (FlowLayout.CENTER));
top.add (doNow);
restart.setFont (new Font ("Arial", Font.BOLD, 12));
restart.addActionListener(this);
exit.setFont (new Font ("Arial", Font.BOLD, 12));
exit.addActionListener(this);
bottom.setLayout (new FlowLayout (FlowLayout.CENTER, 44, 10));
bottom.add (restart);
bottom.add (exit);
endFrame.getContentPane().setLayout (new BorderLayout());
endFrame.getContentPane().add (top, BorderLayout.NORTH);
endFrame.getContentPane().add (bottom, BorderLayout.SOUTH);
endFrame.pack();
Dimension scrnsize = Toolkit.getDefaultToolkit().getScreenSize();
endFrame.setLocation ((int) (scrnsize.width - endFrame.getWidth())/2,
(int) (scrnsize.height - this.getHeight())/3 + this.getHeight());
endFrame.setResizable (false);
endFrame.setVisible (true);
this.setFocusableWindowState(false);
}
public void actionPerformed (ActionEvent event)
{
if(event.getSource().equals(btnExit))
{
System.exit(0);
}
else if (event.getSource().equals(restart))
{
endFrame.dispose();
MouseClick.this.dispose();
//drawingFrame.dispose();
//new HangmanMenu();
}
else if (event.getSource().equals(exit))
{
endFrame.dispose();
MouseClick.this.dispose();
//drawingFrame.dispose();
System.exit(0);
}
else
{
try
{
//char input = Character.toUpperCase(inputField.getText().charAt(0));
//if(event.getSource().equals(btn))
//{
//System.out.println("\n" + input);
boolean letterInWord = false;
for (int i = 0 ; i < word.length() ; i++)
{
if (word.charAt (i) == input)
{
letterInWord = true;
break;
}
}
if (!letterInWord) {
boolean alreadyGuessed = false;
for (int i = 0 ; i < incorrectGuesses.length ; i++) {
if (incorrectGuesses [i] == input) {
alreadyGuessed = true;
message.setText ("You already guessed that!");
break;
}
}
if (!alreadyGuessed) {
chances--;
drawing.addPart();
if (chances >= 0) {
incorrectGuesses [incorrectGuesses.length - chances - 1] = input;
usedLetters [usedLetters.length - chances - 1].setText ("" + input);
message.setText ("Woops, wrong! Try again!");
chancesLabel.setText (chances + " chances left...");
} else {
chancesLabel.setText ("Sorry, you lose.");
message.setText ("The word was: " + word);
endGame();
}
}
} else {
boolean alreadyGuessed = false;
for (int i = 0 ; i < wordArray.length ; i++) {
if (wordArray [i].getText().charAt (0) == input) {
alreadyGuessed = true;
message.setText ("You already guessed that!");
break;
}
}
if (!alreadyGuessed) {
for (int i = 0 ; i < word.length() ; i++) {
if (word.charAt (i) == input) {
wordArray [i].setText ("" + input);
}
}
boolean wordComplete = true;
for (int i = 0 ; i < wordArray.length ; i++) {
if (!Character.isLetter (wordArray [i].getText().charAt (0))) {
wordComplete = false;
break;
}
}
if (!wordComplete) {
message.setText ("Well done, you guessed right!");
} else {
message.setText ("Congratulations, you win the game!");
drawing.escape();
endGame();
}
}
//}
}
//inputField.setText ("");
}catch (Exception x)
{
}
}
}
#Override
public void mouseClicked(MouseEvent e){}
#Override
public void mouseEntered(MouseEvent e){}
#Override
public void mouseExited(MouseEvent e){}
#Override
public void mousePressed(MouseEvent e){}
#Override
public void mouseReleased(MouseEvent e){}
class KeyboardListener implements ActionListener
{
private final char letter;
public KeyboardListener(char letter)
{
this.letter = letter;
}
public char getLetter()
{
return letter;
}
#Override
public void actionPerformed(ActionEvent e)
{
char tempLetter;
if (e.getSource().equals(btnX))
{
tempLetter = 'A';
}
}
}
}
This is the code for the WordHandler class.
package guis;
import java.io.*;
class WordHandler
{
private BufferedReader fileIn;
private String[] wordArray;
private File wordFile;
public WordHandler() throws IOException
{
wordFile = new File("countriesnospaces.txt");
int arrayCounter = 0;
try {
BufferedReader fileIn = new BufferedReader(new FileReader(wordFile));
while (fileIn.readLine() != null)
{
arrayCounter++;
}
wordArray = new String [arrayCounter];
fileIn.close();
fileIn = new BufferedReader(new FileReader(wordFile));
for (int pos = 0 ; pos < arrayCounter ; pos++)
{
wordArray[pos] = fileIn.readLine();
}
fileIn.close();
} catch (FileNotFoundException e)
{
System.out.println("File not found. Please create it and add words.");
}
catch (Exception e)
{
System.out.println("Error: " + e);
}
}
public String getRandomWord() throws IOException
{
int random = (int) (Math.random() * wordArray.length);
return wordArray[random].toUpperCase();
}
public void sort()
{
String temp;
for (int loop = 0 ; loop < wordArray.length - 1 ; loop++) {
for (int pos = 0 ; pos < wordArray.length - 1 - loop ; pos++) {
if (wordArray[pos].compareTo(wordArray[pos + 1]) >0) {
temp = wordArray[pos];
wordArray[pos] = wordArray[pos + 1];
wordArray[pos + 1] = temp;
}
}
}
}
public String[] getArray()
{
return wordArray;
}
}
This is the test class.
package guis;
import java.io.IOException;
import javax.swing.JFrame;
public class TestMouseClick
{
public static void main(String[] args) throws IOException
{
MouseClick sample = new MouseClick();
sample.setTitle("Assignment 2 - Hangman");
sample.setSize(800, 750);
sample.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
sample.setVisible(true);
}
}
A simple fix would be getting the first character in the String returned by JButton tooltip text using the charAt(0) method and assign it to input:
char input = jButton26.getToolTipText().charAt(0);
or you could split it up to make it clearer:
String s = jButton26.getToolTipText();
char input = s.charAt(0);
Also just a tip, instead of manually coding each individual JButton for the GUI keyboard, you could create an array containing all 26 letters and then create the buttons and attach listeners using a for loop. This would significantly reduce the amount of code you have to write.
New Edit: creating and setting up lots of similar objects
(Also I noticed you created an array to store the buttons as well as a buttonLettersarray - this isn't necessary unless you have changed your code to utlise an array of buttons)
The important thing to note here is that ActionListener is an object in Java so it can be defined to store data and other method definitions like any other class. Personally I would prefer to write an inner class that extends ActionListener to store the letter that each button represents.
//define this inner class outside of the methods
class KeyboardListener extends ActionListener {
//field type depends on your buttonLetters array (not sure if it is chars or Strings)
private final String letter;
public KeyboardListener(String letter) {
this.letter = letter;
}
public String getLetter() {
return letter;
}
#Override
public void actionPerformed(ActionEvent ae) {
//do something when button is clicked
//you can make use of the getLetter() method to retrieve the letter
}
}
//this goes in the for loop when creating each button
JButton btnX = new JButton(new KeyboardListener(buttonLetters[i]));
//add button to interface and anything else
Note: one of the JButton constructors can take any class that implements the Action interface (or extends ActionListener in this case) to add it upon creation rather than having to call addActionListener().
I'm trying to make a chronometer but when I click on "Iniciar (start)", the program freezes. This is the part that give me problems:
ActionListener escucha = new ActionListener() {
public void actionPerformed(ActionEvent e) {
iniciar.setEnabled(false);
pausar.setEnabled(true);
reiniciar.setEnabled(true);
rb1.setEnabled(false);
rb2.setEnabled(false);
try {
while (true) {
milisegundos++;
if (milisegundos > 999) {
milisegundos = 0;
segundos++;
if (segundos > 59) {
segundos = 0;
minutos++;
if (minutos > 59) {
minutos = 0;
horas++;
}
}
}
if (milisegundos < 10) {
MS = "00"+milisegundos;
} else if (milisegundos < 100) {
MS = "0"+milisegundos;
} else {
MS = Integer.toString(milisegundos);
}
if (segundos < 10) {
S = "0"+segundos;
} else {
S = Integer.toString(segundos);
}
if (minutos < 10) {
M = "0"+minutos;
} else {
M = Integer.toString(minutos);
}
if (horas < 10) {
H = "0"+horas;
} else {
H = Integer.toString(horas);
}
cadena = H+":"+M+":"+":"+S+":"+MS;
tiempo.setText(cadena);
panel.repaint();
}
} catch (Exception w) {
w.printStackTrace();
}
}
};
iniciar.setText("Iniciar");
iniciar.addActionListener(escucha);
I have done another similar algorithm but it is a very basic digital clock, with the same method of a while and a Thread.sleep() and it works:
import java.util.Date;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import java.awt.Font;
public class asdfasdflkj {
public static void main(String[] args) {
try {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
JLabel lblHoli = new JLabel("Holi");
lblHoli.setFont(new Font("Arial", Font.PLAIN, 43));
frame.setTitle("Hola Gráfica");
frame.setSize(400, 200);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(panel);
panel.setLayout(null);
panel.add(lblHoli);
lblHoli.setBounds(10, 11, 364, 106);
int hora, minuto, segundo;
while (true) {
Date dt = new Date();
hora = dt.getHours();
minuto = dt.getMinutes();
segundo = dt.getSeconds();
lblHoli.setText(hora+":"+minuto+":"+segundo);
Thread.sleep(1000);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Little edit: posting all program code (It's incomplete):
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import java.awt.Toolkit;
import javax.swing.SwingConstants;
import java.awt.Font;
public class principal {
public static int horas = 0, minutos = 0, segundos = 0, milisegundos = 0;
public static String cadena = "00:00:00:00", MS, S, M, H;
public static boolean condición = true, alredySelected = false;
public static void main(String[] args) {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
JPanel panel_botones = new JPanel();
JPanel panel_opciones = new JPanel();
JRadioButton rb1 = new JRadioButton();
JRadioButton rb2 = new JRadioButton();
ButtonGroup bg = new ButtonGroup();
JButton iniciar = new JButton();
JButton pausar = new JButton();
JButton reiniciar = new JButton();
Dimension minimumSize = new Dimension(400, 200);
JTextField tiempo = new JTextField(cadena);
JCheckBox siempreArriba = new JCheckBox();
tiempo.setFont(new Font("Arial", Font.BOLD, 45));
tiempo.setHorizontalAlignment(SwingConstants.CENTER);
tiempo.setEditable(false);
pausar.setEnabled(false);
reiniciar.setEnabled(false);
frame.setTitle("Cronómetro");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(minimumSize);
frame.setMinimumSize(minimumSize);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setIconImage(Toolkit.getDefaultToolkit().getImage(principal.class.getResource("/icons/icono.png")));
panel.setLayout(new BorderLayout());
panel.add(panel_botones, BorderLayout.PAGE_END);
panel.add(panel_opciones, BorderLayout.PAGE_START);
panel.add(tiempo, BorderLayout.CENTER);
panel.add(siempreArriba, BorderLayout.EAST);
panel_botones.setLayout(new FlowLayout());
panel_botones.add(iniciar);
panel_botones.add(pausar);
panel_botones.add(reiniciar);
siempreArriba.setText("Siempre arriba");
siempreArriba.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent e) {
if (siempreArriba.isSelected()) {
frame.setAlwaysOnTop(true);
}else{
frame.setAlwaysOnTop(false);
}
}
});
ActionListener escucha = new ActionListener() {
public void actionPerformed(ActionEvent e) {
iniciar.setEnabled(false);
pausar.setEnabled(true);
reiniciar.setEnabled(true);
rb1.setEnabled(false);
rb2.setEnabled(false);
try {
while (true) {
milisegundos++;
if (milisegundos > 999) {
milisegundos = 0;
segundos++;
if (segundos > 59) {
segundos = 0;
minutos++;
if (minutos > 59) {
minutos = 0;
horas++;
}
}
}
if (milisegundos < 10) {
MS = "00"+milisegundos;
} else if (milisegundos < 100) {
MS = "0"+milisegundos;
} else {
MS = Integer.toString(milisegundos);
}
if (segundos < 10) {
S = "0"+segundos;
} else {
S = Integer.toString(segundos);
}
if (minutos < 10) {
M = "0"+minutos;
} else {
M = Integer.toString(minutos);
}
if (horas < 10) {
H = "0"+horas;
} else {
H = Integer.toString(horas);
}
cadena = H+":"+M+":"+":"+S+":"+MS;
tiempo.setText(cadena);
panel.repaint();
}
} catch (Exception w) {
w.printStackTrace();
}
}
};
iniciar.setText("Iniciar");
iniciar.addActionListener(escucha);
pausar.setText("Pausar");
pausar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
condición = false;
pausar.setEnabled(false);
iniciar.setEnabled(true);
iniciar.setText("Reanudar");
}
});
reiniciar.setText("Reiniciar");
reiniciar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
rb1.setText("Cronómetro");
rb1.setSelected(true);
rb1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
alredySelected = false;
}
});
rb2.setText("Cuenta regresiva");
rb2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
if (rb2.isSelected() && alredySelected==false) {
alredySelected = true;
String temp = JOptionPane.showInputDialog(frame, "Ingrese el número en segundos:");
while (temp.equals("")) {
JOptionPane.showMessageDialog(frame, "¡Debe ingresar un valor!", "Error", JOptionPane.ERROR_MESSAGE);
temp = JOptionPane.showInputDialog(frame, "Ingrese el número en segundos:");
}
horas = Integer.parseInt(temp);
}
} catch (java.lang.NumberFormatException x) {
JOptionPane.showMessageDialog(frame, "¡Solo debe ingresar números!", "Error", JOptionPane.ERROR_MESSAGE);
rb1.setSelected(true);
alredySelected = false;
} catch (java.lang.NullPointerException x) {
rb1.setSelected(true);
alredySelected = false;
}
}
});
bg.add(rb1);
bg.add(rb2);
panel_opciones.setLayout(new FlowLayout());
panel_opciones.add(rb1);
panel_opciones.add(rb2);
}
}
Basically, you're violating the single threaded nature of Swing.
Never update the UI from any thread other then the Event Dispatching Thread
Never block the Event Dispatching Thread
Doing the second will prevent the EDT from updating the UI (and responding to events and other important things)
Take a look at The Event Dispatching Thread for more details
In your case, a Swing Timer would be more then sufficient. Have a look at Swing Timer for more details
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import java.awt.Toolkit;
import javax.swing.SwingConstants;
import java.awt.Font;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class Principal {
public int horas = 0, minutos = 0, segundos = 0, milisegundos = 0;
public String cadena = "00:00:00:00", MS, S, M, H;
public boolean condición = true, alredySelected = false;
private Timer timer;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Principal();
}
});
}
public Principal() {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
JPanel panel_botones = new JPanel();
JPanel panel_opciones = new JPanel();
JRadioButton rb1 = new JRadioButton();
JRadioButton rb2 = new JRadioButton();
ButtonGroup bg = new ButtonGroup();
JButton iniciar = new JButton();
JButton pausar = new JButton();
JButton reiniciar = new JButton();
Dimension minimumSize = new Dimension(400, 200);
JTextField tiempo = new JTextField(cadena);
JCheckBox siempreArriba = new JCheckBox();
tiempo.setFont(new Font("Arial", Font.BOLD, 45));
tiempo.setHorizontalAlignment(SwingConstants.CENTER);
tiempo.setEditable(false);
tiempo.setColumns(11);
pausar.setEnabled(false);
reiniciar.setEnabled(false);
frame.setTitle("Cronómetro");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
// frame.setIconImage(Toolkit.getDefaultToolkit().getImage(Principal.class.getResource("/icons/icono.png")));
panel.setLayout(new BorderLayout());
panel.add(panel_botones, BorderLayout.PAGE_END);
panel.add(panel_opciones, BorderLayout.PAGE_START);
panel.add(tiempo, BorderLayout.CENTER);
panel.add(siempreArriba, BorderLayout.EAST);
panel_botones.setLayout(new FlowLayout());
panel_botones.add(iniciar);
panel_botones.add(pausar);
panel_botones.add(reiniciar);
siempreArriba.setText("Siempre arriba");
siempreArriba.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if (siempreArriba.isSelected()) {
frame.setAlwaysOnTop(true);
} else {
frame.setAlwaysOnTop(false);
}
}
});
timer = new Timer(1, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
milisegundos++;
if (milisegundos > 999) {
milisegundos = 0;
segundos++;
if (segundos > 59) {
segundos = 0;
minutos++;
if (minutos > 59) {
minutos = 0;
horas++;
}
}
}
if (milisegundos < 10) {
MS = "00" + milisegundos;
} else if (milisegundos < 100) {
MS = "0" + milisegundos;
} else {
MS = Integer.toString(milisegundos);
}
if (segundos < 10) {
S = "0" + segundos;
} else {
S = Integer.toString(segundos);
}
if (minutos < 10) {
M = "0" + minutos;
} else {
M = Integer.toString(minutos);
}
if (horas < 10) {
H = "0" + horas;
} else {
H = Integer.toString(horas);
}
cadena = H + ":" + M + ":" + S + ":" + MS;
tiempo.setText(cadena);
panel.repaint();
}
});
ActionListener escucha = new ActionListener() {
public void actionPerformed(ActionEvent e) {
milisegundos = 0;
iniciar.setEnabled(false);
pausar.setEnabled(true);
reiniciar.setEnabled(true);
rb1.setEnabled(false);
rb2.setEnabled(false);
timer.start();
// try {
// while (true) {
// milisegundos++;
// if (milisegundos > 999) {
// milisegundos = 0;
// segundos++;
// if (segundos > 59) {
// segundos = 0;
// minutos++;
// if (minutos > 59) {
// minutos = 0;
// horas++;
// }
// }
// }
//
// if (milisegundos < 10) {
// MS = "00" + milisegundos;
// } else if (milisegundos < 100) {
// MS = "0" + milisegundos;
// } else {
// MS = Integer.toString(milisegundos);
// }
//
// if (segundos < 10) {
// S = "0" + segundos;
// } else {
// S = Integer.toString(segundos);
// }
//
// if (minutos < 10) {
// M = "0" + minutos;
// } else {
// M = Integer.toString(minutos);
// }
//
// if (horas < 10) {
// H = "0" + horas;
// } else {
// H = Integer.toString(horas);
// }
//
// cadena = H + ":" + M + ":" + ":" + S + ":" + MS;
// tiempo.setText(cadena);
// panel.repaint();
//
// }
// } catch (Exception w) {
// w.printStackTrace();
// }
}
};
iniciar.setText("Iniciar");
iniciar.addActionListener(escucha);
pausar.setText("Pausar");
pausar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
condición = false;
pausar.setEnabled(false);
iniciar.setEnabled(true);
iniciar.setText("Reanudar");
timer.stop();
}
});
reiniciar.setText("Reiniciar");
reiniciar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
timer.start();
}
});
rb1.setText("Cronómetro");
rb1.setSelected(true);
rb1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
alredySelected = false;
}
});
rb2.setText("Cuenta regresiva");
rb2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
if (rb2.isSelected() && alredySelected == false) {
alredySelected = true;
String temp = JOptionPane.showInputDialog(frame, "Ingrese el número en segundos:");
while (temp.equals("")) {
JOptionPane.showMessageDialog(frame, "¡Debe ingresar un valor!", "Error", JOptionPane.ERROR_MESSAGE);
temp = JOptionPane.showInputDialog(frame, "Ingrese el número en segundos:");
}
horas = Integer.parseInt(temp);
}
} catch (java.lang.NumberFormatException x) {
JOptionPane.showMessageDialog(frame, "¡Solo debe ingresar números!", "Error", JOptionPane.ERROR_MESSAGE);
rb1.setSelected(true);
alredySelected = false;
} catch (java.lang.NullPointerException x) {
rb1.setSelected(true);
alredySelected = false;
}
}
});
bg.add(rb1);
bg.add(rb2);
panel_opciones.setLayout(new FlowLayout());
panel_opciones.add(rb1);
panel_opciones.add(rb2);
frame.add(panel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
Personally, I don't like incrementing a counter in a Timer like this, as the Timer is inaccurate, a better solution would be to keep a starting point in time and calculate the difference between when the Timer ticks and this point, but, that's me
First, you while loop is exhausting your CPU, the variable millisecond is increasing, and decreasing when reach 999, nonstop, CPU never get a break to rest, and everytime the value millisecond changes, you ask panel to repaints, it is impossible mission for your CPU to do that.
Second, the millisecond won't work the way you expect it to, unless your CPU take 1 millisecond for every clock cycle, not even a antique computer is that slow.
You should replace your while loop with Timer, (Google Java Timer example), so your code get run once every millisecond, which your CPU can handle one handed. :)
This question already has answers here:
Connect 4 check for a win algorithm
(6 answers)
Closed 6 years ago.
So i am having problem checking the winner diagonally in a game called connect 4. I didn't have any problem checking vertically and horizontally. So.. Can u please help me check diagonally?
Code so far:
import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.border.LineBorder;
public class connectFourDesign extends JPanel {
private static final long serialVersionUID = 1L;
// Welcome Screen
private JLabel lblWelcome;
// Buttons for Welcome Screen
private JButton playButton;
private JButton helpButton;
private JButton quitButton;
// Game Modes
private JButton onePlayer;
private JButton twoPlayer;
// Go Back Button
private JButton goBack;
private JButton clickMeOne;
private JButton clickMeTwo;
private JButton clickMeThree;
private JButton clickMeFour;
private JButton clickMeFive;
private JButton clickMeSix;
private JButton clickMeSeven;
// Grid xSize,ySize and 2D Array
private int ysize = 7;
private int xsize = 8;
private JButton[][] slots;
public static void main(String[] args) {
JFrame frame = new JFrame(" Connect Four ");
frame.setSize(500, 500);
frame.getContentPane().add(new connectFourDesign());
frame.setVisible(true);
frame.setResizable(false);
}
public connectFourDesign () {
setBackground(Color.black);
lblWelcome = new JLabel (" Connect 4 ", SwingConstants.CENTER);
lblWelcome.setFont(new Font("Astron Boy Rg", Font.ITALIC, 90));
lblWelcome.setForeground(Color.white);
add(lblWelcome);
lblWelcome.setVisible(true);
playButton = new JButton (" Play ");
playButton.setFont(new Font("Astron Boy Rg", Font.ITALIC, 75));
playButton.setBackground(Color.black);
playButton.setForeground(Color.GREEN);
add(playButton);
playButton.setVisible(true);
playButton.addActionListener(new playButtonListener());
onePlayer = new JButton (" 1 Player ");
onePlayer.setFont(new Font("Astron Boy Rg", Font.ITALIC, 55));
onePlayer.setBackground(Color.black);
onePlayer.setForeground(Color.GREEN);
add(onePlayer);
onePlayer.setVisible(false);
onePlayer.addActionListener(new onePlayerButtonListener());
twoPlayer = new JButton (" 2 Player ");
twoPlayer.setFont(new Font("Astron Boy Rg", Font.ITALIC, 55));
twoPlayer.setBackground(Color.black);
twoPlayer.setForeground(Color.GREEN);
add(twoPlayer);
twoPlayer.setVisible(false);
twoPlayer.addActionListener(new twoPlayerButtonListener());
helpButton = new JButton ( " Help ");
helpButton.setFont(new Font("Astron Boy Rg", Font.ITALIC, 75));
helpButton.setBackground(Color.black);
helpButton.setForeground(Color.magenta);
add(helpButton);
helpButton.setVisible(true);
helpButton.addActionListener(new helpListener());
quitButton = new JButton ( " Quit ");
quitButton.setFont(new Font("Astron Boy Rg", Font.ITALIC, 75));
quitButton.setBackground(Color.black);
quitButton.setForeground(Color.orange);
add(quitButton);
quitButton.setVisible(true);
quitButton.addActionListener(new CloseListener());
goBack = new JButton ( " Go Back ");
goBack.setFont(new Font("Astron Boy Rg", Font.ITALIC, 60));
goBack.setBackground(Color.black);
goBack.setForeground(Color.BLUE);
add(goBack);
goBack.setVisible(false);
goBack.addActionListener(new goBackButtonListener());
clickMeOne = new JButton ();
clickMeOne.setFont(new Font("Astron Boy Rg", Font.ITALIC, 20));
clickMeOne.setBackground(Color.gray);
clickMeOne.setForeground(Color.CYAN);
clickMeOne.setName("clickMeOne");
add(clickMeOne);
clickMeOne.setVisible(false);
clickMeOne.addActionListener(new clikMeOneButtonListener());
clickMeTwo = new JButton ();
clickMeTwo.setFont(new Font("Astron Boy Rg", Font.ITALIC, 20));
clickMeTwo.setBackground(Color.gray);
clickMeTwo.setForeground(Color.CYAN);
clickMeTwo.setName("clickMeTwo");
add(clickMeTwo);
clickMeTwo.setVisible(false);
clickMeTwo.addActionListener(new clikMeOneButtonListener());
clickMeThree = new JButton ();
clickMeThree.setFont(new Font("Astron Boy Rg", Font.ITALIC, 20));
clickMeThree.setBackground(Color.gray);
clickMeThree.setForeground(Color.CYAN);
clickMeThree.setName("clickMeThree");
add(clickMeThree);
clickMeThree.setVisible(false);
clickMeThree.addActionListener(new clikMeOneButtonListener());
clickMeFour = new JButton ();
clickMeFour.setFont(new Font("Astron Boy Rg", Font.ITALIC, 20));
clickMeFour.setBackground(Color.gray);
clickMeFour.setForeground(Color.CYAN);
clickMeFour.setName("clickMeFour");
add(clickMeFour);
clickMeFour.setVisible(false);
clickMeFour.addActionListener(new clikMeOneButtonListener());
clickMeFive = new JButton ();
clickMeFive.setFont(new Font("Astron Boy Rg", Font.ITALIC, 20));
clickMeFive.setBackground(Color.gray);
clickMeFive.setForeground(Color.CYAN);
clickMeFive.setName("clickMeFive");
add(clickMeFive);
clickMeFive.setVisible(false);
clickMeFive.addActionListener(new clikMeOneButtonListener());
clickMeSix = new JButton ();
clickMeSix.setFont(new Font("Astron Boy Rg", Font.ITALIC, 20));
clickMeSix.setBackground(Color.gray);
clickMeSix.setForeground(Color.CYAN);
clickMeSix.setName("clickMeSix");
add(clickMeSix);
clickMeSix.setVisible(false);
clickMeSix.addActionListener(new clikMeOneButtonListener());
clickMeSeven = new JButton ();
clickMeSeven.setFont(new Font("Astron Boy Rg", Font.ITALIC, 20));
clickMeSeven.setBackground(Color.gray);
clickMeSeven.setForeground(Color.CYAN);
clickMeSeven.setName("clickMeSeven");
add(clickMeSeven);
clickMeSeven.setVisible(false);
clickMeSeven.addActionListener(new clikMeOneButtonListener());
clickMeOne.setIcon(new ImageIcon("kdevelop_down.png"));
clickMeTwo.setIcon(new ImageIcon("kdevelop_down.png"));
clickMeThree.setIcon(new ImageIcon("kdevelop_down.png"));
clickMeFour.setIcon(new ImageIcon("kdevelop_down.png"));
clickMeFive.setIcon(new ImageIcon("kdevelop_down.png"));
clickMeSix.setIcon(new ImageIcon("kdevelop_down.png"));
clickMeSeven.setIcon(new ImageIcon("kdevelop_down.png"));
clickMeOne.setBorder(new LineBorder(Color.black));
clickMeTwo.setBorder(new LineBorder(Color.black));
clickMeThree.setBorder(new LineBorder(Color.black));
clickMeFour.setBorder(new LineBorder(Color.black));
clickMeFive.setBorder(new LineBorder(Color.black));
clickMeSix.setBorder(new LineBorder(Color.black));
clickMeSeven.setBorder(new LineBorder(Color.black));
validate();
}
private class onePlayerButtonListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
if (event.getSource() == onePlayer) {
lblWelcome.setVisible(false);
playButton.setVisible(false);
helpButton.setVisible(false);
quitButton.setVisible(false);
twoPlayer.setVisible(false);
onePlayer.setVisible(true);
goBack.setVisible(false);
Thread thread =new Thread() {
public void run() {
onePlayer.setText(" Game Starts In ");
onePlayer.setFont(new Font("Astron Boy Rg", Font.ITALIC, 40));
onePlayer.setBackground(Color.black);
onePlayer.setForeground(Color.BLUE);
try {
Thread.sleep(1000);
}catch (Exception e) {
}
onePlayer.setText("3");
try {
Thread.sleep(1000);
}catch (Exception e) {
}
onePlayer.setText("2");
try {
Thread.sleep(1000);
}catch (Exception e) {
}
onePlayer.setText("1");
try {
Thread.sleep(1000);
}catch (Exception e) {
}
setLayout(new GridLayout(xsize, ysize));
slots = new JButton[xsize - 1][ysize];
for (int column = 0; column < ysize; column++) {
for (int row = 0; row < xsize - 1; row++) {
slots[row][column] = new JButton();
slots[row][column].setHorizontalAlignment(SwingConstants.CENTER);
slots[row][column].setBackground(Color.GREEN);
slots[row][column].setBorder(new LineBorder(Color.black));
add(slots[row][column]);
}
}
lblWelcome.setVisible(false);
remove(lblWelcome);
playButton.setVisible(false);
remove(playButton);
helpButton.setVisible(false);
remove(helpButton);
quitButton.setVisible(false);
remove(quitButton);
goBack.setVisible(false);
remove(goBack);
onePlayer.setVisible(false);
remove(onePlayer);
twoPlayer.setVisible(false);
remove(twoPlayer);
clickMeOne.setVisible(true);
clickMeTwo.setVisible(true);
clickMeThree.setVisible(true);
clickMeFour.setVisible(true);
clickMeFive.setVisible(true);
clickMeSix.setVisible(true);
clickMeSeven.setVisible(true);
}
};
thread.start();
}
}
}
private class twoPlayerButtonListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
if (event.getSource() == twoPlayer) {
lblWelcome.setVisible(false);
playButton.setVisible(false);
helpButton.setVisible(false);
quitButton.setVisible(false);
twoPlayer.setVisible(true);
onePlayer.setVisible(false);
goBack.setVisible(false);
Thread thread =new Thread() {
public void run() {
twoPlayer.setText(" Game Starts In ");
twoPlayer.setFont(new Font("Astron Boy Rg", Font.ITALIC, 40));
twoPlayer.setBackground(Color.black);
twoPlayer.setForeground(Color.blue);
try {
Thread.sleep(1000);
}catch (Exception e) {
}
twoPlayer.setText("3");
try {
Thread.sleep(1000);
}catch (Exception e) {
}
twoPlayer.setText("2");
try {
Thread.sleep(1000);
}catch (Exception e) {
}
twoPlayer.setText("1");
try {
Thread.sleep(1000);
}catch (Exception e) {
}
setLayout(new GridLayout(xsize, ysize));
slots = new JButton[xsize - 1][ysize];
for (int column = 0; column < ysize; column++) {
for (int row = 0; row < xsize - 1; row++) {
slots[row][column] = new JButton();
slots[row][column].setHorizontalAlignment(SwingConstants.CENTER);
slots[row][column].setBackground(Color.GREEN);
slots[row][column].setBorder(new LineBorder(Color.black));
add(slots[row][column]);
}
}
lblWelcome.setVisible(false);
remove(lblWelcome);
playButton.setVisible(false);
remove(playButton);
helpButton.setVisible(false);
remove(helpButton);
quitButton.setVisible(false);
remove(quitButton);
goBack.setVisible(false);
remove(goBack);
onePlayer.setVisible(false);
remove(onePlayer);
twoPlayer.setVisible(false);
remove(twoPlayer);
clickMeOne.setVisible(true);
clickMeTwo.setVisible(true);
clickMeThree.setVisible(true);
clickMeFour.setVisible(true);
clickMeFive.setVisible(true);
clickMeSix.setVisible(true);
clickMeSeven.setVisible(true);
}
};
thread.start();
}
}
}
private class playButtonListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
if (event.getSource() == playButton) {
lblWelcome.setVisible(true);
playButton.setVisible(false);
helpButton.setVisible(false);
quitButton.setVisible(false);
onePlayer.setVisible(true);
twoPlayer.setVisible(true);
goBack.setVisible(true);
}
}
}
private class goBackButtonListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
if (event.getSource() == goBack) {
lblWelcome.setVisible(true);
playButton.setVisible(true);
helpButton.setVisible(true);
quitButton.setVisible(true);
onePlayer.setVisible(false);
twoPlayer.setVisible(false);
goBack.setVisible(false);
}
}
}
private class CloseListener implements ActionListener{
public void actionPerformed(ActionEvent event) {
if (event.getSource() == quitButton) {
int quitTheGame = JOptionPane.showConfirmDialog(null, " Are You Sure You Want to Leave The Game? ", " Quit? "
, JOptionPane.YES_NO_OPTION);
if (quitTheGame == JOptionPane.YES_OPTION) {
System.exit(0);
}
}
}
}
private class helpListener implements ActionListener{
public void actionPerformed(ActionEvent event) {
if (event.getSource() == helpButton) {
JOptionPane.showMessageDialog(null, " 1) Choose who plays first.", " Help ", JOptionPane.INFORMATION_MESSAGE);
}
}
}
private Color playerColor = Color.red;
private class clikMeOneButtonListener implements ActionListener{
public void actionPerformed(ActionEvent event) {
if (event.getSource() == clickMeOne
|| event.getSource() == clickMeTwo
|| event.getSource() == clickMeThree
|| event.getSource() == clickMeFour
|| event.getSource() == clickMeFive
|| event.getSource() == clickMeSix
|| event.getSource() == clickMeSeven
) {
JButton b = (JButton)event.getSource();
int column = 0;
switch ( b.getName() ) {
case "clickMeOne" : column = 0; break;
case "clickMeTwo" : column = 1; break;
case "clickMeThree" : column = 2; break;
case "clickMeFour" : column = 3; break;
case "clickMeFive" : column = 4; break;
case "clickMeSix" : column = 5; break;
case "clickMeSeven" : column = 6; break;
}
int lastEmptyIdx = -1;
for ( int i = 0; i < slots[column].length; i++ ) {
if ( slots[column][i].getBackground() != Color.green ) {
break;
}
else {
lastEmptyIdx = i;
}
}
if ( lastEmptyIdx != -1 ) {
slots[column][lastEmptyIdx].setBackground(playerColor);
if ( IsWin(column, lastEmptyIdx) ) {
String message = playerColor == Color.red ? " Player One Won!" : " Player Two Won!";
JOptionPane.showMessageDialog(null, message, " Results ", JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
} else {
playerColor = playerColor == Color.red ? Color.yellow : Color.red;
}
}
}
}
public boolean IsWin(int column, int row) {
boolean result = false;
// horizontal
boolean found = false;
int counter = 0;
for ( int i = 0; i < slots.length; i++ ) {
if ( slots[i][row].getBackground().equals(playerColor)) {
counter++;
if ( found == true ) {
if ( counter == 4 ) { // win \o/
result = true;
break;
}
}
else {
found = true;
}
}
else {
if ( found == true ) { // reset counter
counter = 0;
}
found = false;
}
}
// vertical
for ( int i = 0; i < slots.length; i++ ) {
if ( slots[column][i].getBackground().equals(playerColor)) {
counter++;
if ( found == true ) {
if ( counter == 4 ) { // win \o/
result = true;
break;
}
}
else {
found = true;
}
}
else {
if ( found == true ) { // reset counter
counter = 0;
}
found = false;
}
}
// diagonal
// TODO
return result;
}
}
}
UPDATE:
for ( int i = 0; i < slots.length; i++ ) {
if ( slots[column][i].getBackground().equals(playerColor)) {
counter++;
column ++;
if (column >= slots.length - 1){
found = false;
break;
}
if ( found == true ) {
if ( counter == 4 ) { // win \o/
result = true;
break;
}
}
else {
found = true;
}
}
else {
if ( found == true ) { // reset counter
counter = 0;
}
found = false;
}
}
Your check needs to not only increment one direction of the slot pane (i), but also needs to increment or decrement what is column in this supposed-to-check-diagonal code to really check along a diagonal.
You also may know there can not be a diagonal win towards a direction if there are less than 4 columns to that side.
**EDIT*: You really should read about language concepts and especially try to understand the concept beyond the syntax! For understanding what is going on, a debugger is an essential tool. If you have a specific algorithm (e.g. your IsWin() method that you need to get insight into, use paper and pencil and do a "manual" execution. This will give you more hints on what might be wrong than any answer to a question with SO. Nevertheless, the references to duplicates of your problem perfectly show what a solution could look like. It is up to you to understand and transfer that to your specific code environment.
To help you a bit further, find below a version of your IsWin() that is working with your code logic. You just need to provide the current playerColor as another parameter. It then will indicate whether the last move lead to a win. (As there can not have been a win before, otherwise it would have been indicated before!). Thus, you just need to check the last move completed a sequence of four in any direction. The code is not truely optimized. There still is room for shortening. But maybe you should first start understanding what you are doing and remove unnecessary garbage from your code....
Suggested code:
public boolean IsWin(final int column, final int row, final Color playerColor) {
boolean won = true;
// vertical
if (row < slots[column].length - 3) {
for (int i = 0; i < 4; i++ ) {
if ( !slots[column][row + i].getBackground().equals(playerColor)) {
won = false;
break;
}
}
if (won) {
return won;
}
}
// to the left
if (column >= 3) {
// horizontal
won = true;
for (int i = 0; i < 4; i++ ) {
if ( !slots[column - i][row].getBackground().equals(playerColor)) {
won = false;
break;
}
}
if (won) {
return won;
}
// diagonal
if (row < slots[column].length - 3) {
won = true;
for (int i = 0; i < 4; i++ ) {
if ( !slots[column - i][row + i].getBackground().equals(playerColor)) {
won = false;
break;
}
}
if (won) {
return won;
}
}
}
// to the right
if (slots.length - column > 3) {
// horizontal
won = true;
for (int i = 0; i < 4; i++ ) {
if ( !slots[column + i][row].getBackground().equals(playerColor)) {
won = false;
break;
}
}
if (won) {
return won;
}
// diagonal
if (row < slots[column].length - 3) {
won = true;
for (int i = 0; i < 4; i++ ) {
if ( !slots[column + i][row + i].getBackground().equals(playerColor)) {
won = false;
break;
}
}
if (won) {
return won;
}
}
}
return false;
}
So I've been trying to figure out why my JApplet is starting and giving no errors but nothing is showing up. I have an init() method that calls setup_layout(), but I think I may have done something wrong the layouts. Anyone help?
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class Assignment8 extends JApplet implements ActionListener
{
public static final int WIDTH = 500;
public static final int HEIGHT = 500;
public static final int NUMBER_OF_DIGITS = 30;
private JTextArea operand, result;
private double answer = 0.0;
private JButton sevenB, eightB, nineB, divideB, fourB, fiveB, sixB, multiplyB, oneB, twoB, threeB, subtractB,
zeroB, dotB, addB, resetB, clearB, sqrtB, absB, expB;
/** public static void main(String[] args)
{
Assignment8 aCalculator = new Assignment8( );
aCalculator.setVisible(true);
}**/
public void init( )
{
setup_layout();
}
private void setup_layout() {
setSize(WIDTH, HEIGHT);
JPanel MainPanel = new JPanel();
JPanel buttonPanel = new JPanel();
JPanel calcPanel = new JPanel();
JPanel textPanel = new JPanel ();
buttonPanel.setLayout(new GridLayout(3, 4));
calcPanel.setLayout(new GridLayout(3, 3));
textPanel.setLayout(new FlowLayout());
MainPanel.setLayout(new BorderLayout());
MainPanel.setBackground(Color.red);
operand = new JTextArea();
result = new JTextArea();
operand.setEditable(false);
result.setEditable(false);
textPanel.add(operand);
textPanel.add(result);
sevenB = new JButton("7");
eightB = new JButton("8");
nineB = new JButton("9");
divideB = new JButton("/");
fourB = new JButton("4");
fiveB = new JButton("5");
sixB = new JButton("6");
multiplyB = new JButton("*");
oneB = new JButton("1");
twoB = new JButton("2");
threeB = new JButton("3");
subtractB = new JButton("-");
zeroB = new JButton("0");
dotB = new JButton(".");
addB = new JButton("+");
resetB = new JButton("Reset");
clearB = new JButton("Clear");
sqrtB = new JButton("Sqrt");
absB = new JButton("Abs");
expB = new JButton("Exp");
sevenB.addActionListener(this);
eightB.addActionListener(this);
nineB.addActionListener(this);
divideB.addActionListener(this);
fourB.addActionListener(this);
fiveB.addActionListener(this);
sixB.addActionListener(this);
multiplyB.addActionListener(this);
oneB.addActionListener(this);
twoB.addActionListener(this);
threeB.addActionListener(this);
subtractB.addActionListener(this);
zeroB.addActionListener(this);
dotB.addActionListener(this);
addB.addActionListener(this);
resetB.addActionListener(this);
clearB.addActionListener(this);
absB.addActionListener(this);
expB.addActionListener(this);
sqrtB.addActionListener(this);
buttonPanel.add(sevenB);
buttonPanel.add(eightB);
buttonPanel.add(nineB);
buttonPanel.add(fourB);
buttonPanel.add(fiveB);
buttonPanel.add(sixB);
buttonPanel.add(oneB);
buttonPanel.add(twoB);
buttonPanel.add(threeB);
buttonPanel.add(zeroB);
buttonPanel.add(dotB);
calcPanel.add(subtractB);
calcPanel.add(multiplyB);
calcPanel.add(divideB);
calcPanel.add(sqrtB);
calcPanel.add(absB);
calcPanel.add(expB);
calcPanel.add(addB);
calcPanel.add(resetB);
calcPanel.add(clearB);
MainPanel.add(buttonPanel);
MainPanel.add(calcPanel);
MainPanel.add(textPanel);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
try
{
assumingCorrectNumberFormats(e);
}
catch (NumberFormatException e2)
{
result.setText("Error: Reenter Number.");
}
catch (DivideByZeroException e1) {
result.setText("Error: CANNOT Divide By Zero. Reenter Number.");
}
}
//Throws NumberFormatException.
public void assumingCorrectNumberFormats(ActionEvent e) throws DivideByZeroException
{
String actionCommand = e.getActionCommand( );
if (actionCommand.equals("1"))
{
int num = 1;
operand.append(Integer.toString(num));
}
else if (actionCommand.equals("2"))
{
int num = 2;
operand.append(Integer.toString(num));
}
else if (actionCommand.equals("3"))
{
int num = 3;
operand.append(Integer.toString(num));
}
else if (actionCommand.equals("4"))
{
int num = 4;
operand.append(Integer.toString(num));
}
else if (actionCommand.equals("5"))
{
int num = 5;
operand.append(Integer.toString(num));
}
else if (actionCommand.equals("6"))
{
int num = 6;
operand.append(Integer.toString(num));
}
else if (actionCommand.equals("7"))
{
int num = 7;
operand.append(Integer.toString(num));
}
else if (actionCommand.equals("8"))
{
int num = 8;
operand.append(Integer.toString(num));
}
else if (actionCommand.equals("9"))
{
int num = 9;
operand.append(Integer.toString(num));
}
else if (actionCommand.equals("0"))
{
int num = 0;
String text = operand.getText();
//double check = stringToDouble(text);
if(text.isEmpty()||text.contains(".")) {
operand.append(Integer.toString(num));
}
}
else if (actionCommand.equals("."))
{
String text = operand.getText();
if(!text.contains(".")) {
operand.append(".");
}
}
else if (actionCommand.equals("+"))
{
answer = answer + stringToDouble(operand.getText( ));
result.setText(Double.toString(answer));
operand.setText("");
}
else if (actionCommand.equals("-"))
{
answer = answer - stringToDouble(operand.getText( ));
result.setText(Double.toString(answer));
operand.setText("");
}
else if (actionCommand.equals("*"))
{
answer = answer * stringToDouble(operand.getText( ));
result.setText(Double.toString(answer));
operand.setText("");
}
else if (actionCommand.equals("/"))
{
double check = stringToDouble(operand.getText());
if(check >= -1.0e-10 && check <= 1.0e-10 ) {
throw new DivideByZeroException();
}
else {
answer = answer / stringToDouble(operand.getText( ));
result.setText(Double.toString(answer));
operand.setText("");
}
}
else if (actionCommand.equals("Sqrt"))
{
double check = stringToDouble(result.getText());
if(check < 0 ) {
throw new NumberFormatException();
}
else {
answer = Math.sqrt(stringToDouble(result.getText( )));
result.setText(Double.toString(answer));
operand.setText("");
}
}
else if (actionCommand.equals("Abs"))
{
answer = Math.abs(stringToDouble(result.getText( )));
result.setText(Double.toString(answer));
operand.setText("");
}
else if (actionCommand.equals("Exp"))
{
answer = Math.pow(stringToDouble(result.getText( )),stringToDouble(operand.getText( )));
result.setText(Double.toString(answer));
operand.setText("");
}
else if (actionCommand.equals("Reset"))
{
answer = 0.0;
result.setText("");
operand.setText("");
}
else if (actionCommand.equals("Clear"))
{
operand.setText("");
}
else
result.setText("Unexpected error.");
}
//Throws NumberFormatException.
private static double stringToDouble(String stringObject)
{
return Double.parseDouble(stringObject.trim( ));
}
//Divide by Zero Exception Class
public class DivideByZeroException extends Exception {
DivideByZeroException() {
}
}
}
You never add MainPanel to the applet itself.
i.e.,
add(MainPanel);
Also, since MainPanel uses BorderLayout, you will need to add the subPanels with a BorderLayout.XXX constant. i.e.,
change this:
MainPanel.add(buttonPanel);
MainPanel.add(calcPanel);
MainPanel.add(textPanel);
to:
MainPanel.add(buttonPanel, BorderLayout.CENTER);
MainPanel.add(calcPanel, BorderLayout.PAGE_END); // wherever you want to add this
MainPanel.add(textPanel, BorderLayout.PAGE_START);
Note that your code can be simplified greatly by using arrays or Lists.
Or could simplify it in other ways, for instance:
public void assumingCorrectNumberFormats(ActionEvent e)
throws DivideByZeroException {
String actionCommand = e.getActionCommand();
String numbers = "1234567890";
if (numbers.contains(actionCommand)) {
operand.append(actionCommand);
// if you need to work with it as a number
int num = Integer.parseInt(actionCommand);
}
Myself, I'd use a different ActionListeners for different functionality, for instance one ActionListener for numeric and . entry buttons and another one for the operation buttons.
The purpose of this program is to allow the tutor to keep a log of his/her students. I'm a newbie to GUI so my code probably isnt the best but I need help with the code for the JButton "SAVE" to take all the information in the log and store it in a .txt file. Line 374 is where my button command is.
import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;
public class MainGUI extends JFrame {
// Declare variables:
// array lists
String[] columnNames = {"ID", "NAME", "COURSE", "Professor", "Reason for Tutor"};
Object[][] data = new Object[25][5];
// table
JTable table = new JTable(data, columnNames) {
// sets the ability of the cells to be edited by the user
#Override
public boolean isCellEditable(int row, int column) {
return false; // returns false, cannot be edited
}
};
// frames
JFrame frame, frame1;
// panels
JPanel buttonPanel, buttonPanel2, tablePanel, addPanel, editPanel;
// labels
JLabel labelID, labelName, labelCourse, labelProfessor, labelHelp;
// text fields
JTextField txtID, txtName, txtCourse, txtProfessor, txtHelp;
// buttons
JButton btnAdd, btnEdit, btnDelete, btnSort, btnSave, btnAddInput, btnCancel;
// additionals
int keyCode, rowIndex, rowNumber, noOfStudents;
// button handler
MainGUI.ButtonHandler bh = new MainGUI.ButtonHandler();
public MainGUI() {
// setting/modifying table components
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.getSelectionModel().addListSelectionListener(new MainGUI.RowListener());
table.getColumnModel().getColumn(1).setPreferredWidth(200);
table.getColumnModel().getColumn(3).setPreferredWidth(100);
table.getColumnModel().getColumn(4).setPreferredWidth(200);
table.getTableHeader().setResizingAllowed(false);
table.getTableHeader().setReorderingAllowed(false);
JScrollPane scrollPane = new JScrollPane(table);
// main buttons
btnAdd = new JButton("ADD");
btnAdd.addActionListener(bh);
btnEdit = new JButton("EDIT");
btnEdit.addActionListener(bh);
btnEdit.setEnabled(false); // disables the component
btnDelete = new JButton("DELETE");
btnDelete.addActionListener(bh);
btnDelete.setEnabled(false); // disables the component
btnSort = new JButton("SORT");
btnSort.addActionListener(bh);
btnSave = new JButton("SAVE");
btnSave.addActionListener(bh);
btnSave.setActionCommand("Save");
// with button Listeners
// sub buttons
btnAddInput = new JButton("Add");
btnAddInput.addActionListener(bh);
btnAddInput.setActionCommand("AddInput");
btnCancel = new JButton("Cancel");
btnCancel.addActionListener(bh);
// set label names
labelID = new JLabel("ID");
labelName = new JLabel("NAME");
labelCourse = new JLabel("COURSE");
labelProfessor = new JLabel("Professor");
labelHelp = new JLabel("Reason for Tutoring");
// set text fields width
txtID = new JTextField(20);
txtName = new JTextField(20);
txtCourse = new JTextField(20);
txtProfessor = new JTextField(20);
txtHelp = new JTextField(20);
txtID.setDocument(new MainGUI.JTextFieldLimit(15)); // limits the length of input:
// max of 15
txtID.addKeyListener(keyListener); // accepts only numerals
// main frame
// panel for the table
tablePanel = new JPanel();
tablePanel.setLayout(new BoxLayout(tablePanel, BoxLayout.PAGE_AXIS));
tablePanel.setBorder(BorderFactory.createEmptyBorder(10, 2, 0, 10));
tablePanel.add(table.getTableHeader());
tablePanel.add(table);
// panel for the main buttons
buttonPanel = new JPanel();
buttonPanel.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
// positions the main buttons
c.gridx = 0;
c.gridy = 0;
c.ipady = 20;
c.insets = new Insets(10, 10, 10, 10);
c.fill = GridBagConstraints.HORIZONTAL;
buttonPanel.add(btnAdd, c);
c.gridx = 0;
c.gridy = 1;
c.fill = GridBagConstraints.HORIZONTAL;
c.ipady = 20;
c.insets = new Insets(10, 10, 10, 10);
buttonPanel.add(btnEdit, c);
c.gridx = 0;
c.gridy = 2;
c.fill = GridBagConstraints.HORIZONTAL;
c.ipady = 20;
c.insets = new Insets(10, 10, 10, 10);
buttonPanel.add(btnDelete, c);
c.gridx = 0;
c.gridy = 3;
c.ipady = 20;
c.insets = new Insets(10, 10, 10, 10);
c.fill = GridBagConstraints.HORIZONTAL;
buttonPanel.add(btnSort, c);
c.gridx = 0;
c.gridy = 4;
c.ipady = 20;
c.insets = new Insets(10, 10, 10, 10);
c.fill = GridBagConstraints.HORIZONTAL;
buttonPanel.add(btnSave, c);
frame = new JFrame("Student Database");
frame.setVisible(true);
frame.setResizable(false);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.add(tablePanel, BorderLayout.CENTER);
frame.add(buttonPanel, BorderLayout.EAST);
frame.pack();
// ADD frame
// panel for adding
addPanel = new JPanel();
addPanel.setLayout(new GridBagLayout());
// positions the components for adding
// labels
c.insets = new Insets(1, 0, 1, 1);
c.gridx = 0;
c.gridy = 0;
addPanel.add(labelID, c);
c.gridy = 1;
addPanel.add(labelName, c);
c.gridy = 2;
addPanel.add(labelCourse, c);
c.gridy = 3;
addPanel.add(labelProfessor, c);
c.gridy = 4;
addPanel.add(labelHelp, c);
// text fields
c.gridx = 1;
c.gridy = 0;
c.ipady = 1;
addPanel.add(txtID, c);
c.gridy = 1;
c.ipady = 1;
addPanel.add(txtName, c);
c.gridy = 2;
c.ipady = 1;
addPanel.add(txtCourse, c);
c.gridy = 3;
c.ipady = 1;
addPanel.add(txtProfessor, c);
c.gridy = 4;
c.ipady = 1;
addPanel.add(txtHelp, c);
// panel for other necessary buttons
buttonPanel2 = new JPanel();
buttonPanel2.setLayout(new GridLayout(1, 1));
buttonPanel2.add(btnAddInput);
buttonPanel2.add(btnCancel);
frame1 = new JFrame("Student Database");
frame1.setVisible(false);
frame1.setResizable(false);
frame1.setDefaultCloseOperation(HIDE_ON_CLOSE);
frame1.add(addPanel, BorderLayout.CENTER);
frame1.add(buttonPanel2, BorderLayout.PAGE_END);
frame1.pack();
}// end
KeyListener keyListener = new KeyListener() {
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
keyCode = e.getKeyCode();
if (!(keyCode >= 48 && keyCode <= 57) && !(keyCode >= 96 && keyCode <= 105)
&& !(keyCode >= 37 && keyCode <= 40) && !(keyCode == 127 || keyCode == 8)) {
txtID.setEditable(false);
}
}
#Override
public void keyReleased(KeyEvent e) {
txtID.setEditable(true);
}
};
class RowListener implements ListSelectionListener {
#Override
public void valueChanged(ListSelectionEvent event) {
if (event.getValueIsAdjusting()) {
rowIndex = table.getSelectedRow();
if (data[rowIndex][0] == null || data[rowIndex][0] == "") {
btnEdit.setEnabled(false);
btnDelete.setEnabled(false);
} else {
btnEdit.setEnabled(true);
btnDelete.setEnabled(true);
}
}
}
}// end
class ButtonHandler implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("ADD")) {
// text fields for Student input data
txtID.setText("");
txtName.setText("");
txtCourse.setText("");
txtProfessor.setText("");
txtHelp.setText("");
frame1.setTitle("Add Student data"); // title bar name for add
frame1.setVisible(true);
} else if (e.getActionCommand().equals("EDIT")) {
txtID.setText(data[rowIndex][0] + ""); // will preview the ID
// input during Add
txtName.setText(data[rowIndex][1] + ""); // will preview the Name
// input during Add
txtCourse.setText(data[rowIndex][2] + ""); // will preview the
// Course input during
// Add
txtProfessor.setText(data[rowIndex][3] + ""); // will preview the Year
// input during Add
txtHelp.setText(data[rowIndex][4] + ""); // will preview the
// Gender input during
// Add
txtID.setEditable(false); // forbids the user to edit the entered
// ID number
frame1.setTitle("Edit Student data"); // title bar name for edit
btnAddInput.setActionCommand("Edit2");
btnAddInput.setText("ACCEPT");
frame1.setVisible(true); // sets the visibility of frame1
} else if (e.getActionCommand().equals("DELETE")) {
int confirm = JOptionPane.showConfirmDialog(frame, "ARE YOU SURE?", "CONFIRM",
JOptionPane.YES_NO_OPTION);
if (confirm == 0) {
rowIndex = table.getSelectedRow();
rowNumber = 0;
noOfStudents--;
for (int i = 0; i <= 10; i++) {
if (rowIndex != i && i <= noOfStudents) {
data[rowNumber][0] = data[i][0];
data[rowNumber][1] = data[i][1];
data[rowNumber][2] = data[i][2];
data[rowNumber][3] = data[i][3];
data[rowNumber][4] = data[i][4];
rowNumber++;
} else if (rowIndex != i && i > noOfStudents) {
data[rowNumber][0] = "";
data[rowNumber][1] = "";
data[rowNumber][2] = "";
data[rowNumber][3] = "";
data[rowNumber][4] = "";
rowNumber++;
}
}
if (noOfStudents == 1000) {
btnAdd.setEnabled(false);
}
else {
btnAdd.setEnabled(true);
}
if (noOfStudents == 0) {
btnDelete.setEnabled(false);
btnEdit.setEnabled(false);
} else {
btnDelete.setEnabled(true);
btnEdit.setEnabled(true);
}
rowIndex = table.getSelectedRow();
if (data[rowIndex][0] == null || data[rowIndex][0] == "") {
btnEdit.setEnabled(false);
btnDelete.setEnabled(false);
} else {
btnEdit.setEnabled(true);
btnDelete.setEnabled(true);
}
table.updateUI();
}
} else if (e.getActionCommand().equals("AddInput")) {
if (txtID.getText().isEmpty() || txtName.getText().isEmpty()
|| txtCourse.getText().isEmpty()// /
|| txtProfessor.getText().isEmpty() || txtHelp.getText().isEmpty()) {
JOptionPane.showMessageDialog(null, "PLEASE FILL IN THE BLANKS.", "ERROR!",
JOptionPane.ERROR_MESSAGE);
}
else {
int dup = 0;
for (int i = 0; i < 10; i++) {
if (txtID.getText().equals(data[i][0])) {
JOptionPane.showMessageDialog(null, "ID NUMBER ALREADY EXISTS.", "ERROR!",
JOptionPane.ERROR_MESSAGE);
dup++;
}
}
if (dup == 0) {
rowIndex = table.getSelectedRow();
data[noOfStudents][0] = txtID.getText();
data[noOfStudents][1] = txtName.getText();
data[noOfStudents][2] = txtCourse.getText();
data[noOfStudents][3] = txtProfessor.getText();
data[noOfStudents][4] = txtHelp.getText();
table.updateUI();
frame1.dispose();
noOfStudents++;
if (noOfStudents == 50){
btnAdd.setEnabled(false);
}
else {
btnAdd.setEnabled(true);
}
if (data[rowIndex][0] == null) {
btnEdit.setEnabled(false);
btnDelete.setEnabled(false);
} else {
btnEdit.setEnabled(true);
btnDelete.setEnabled(true);
}
}
}
table.updateUI();
}else if(e.getActionCommand().equals("Save")){
try {
PrintWriter out = new PrintWriter("filename.txt");
out.println(txtID.getText());
out.println(txtName.getText());
out.println(txtCourse.getText());
out.println(txtProfessor.getText());
out.println(txtHelp.getText());
} catch (FileNotFoundException ex) {
}
}else if (e.getActionCommand().equals("Edit2")) {
if (txtID.getText().isEmpty() || txtName.getText().isEmpty()
|| txtCourse.getText().isEmpty() || txtProfessor.getText().isEmpty()
|| txtHelp.getText().isEmpty()) {
JOptionPane.showMessageDialog(null, "INCOMPLETE INPUT.", "ERROR!",
JOptionPane.ERROR_MESSAGE);
} else {
data[rowIndex][0] = txtID.getText();
data[rowIndex][1] = txtName.getText();
data[rowIndex][2] = txtCourse.getText();
data[rowIndex][3] = txtProfessor.getText();
data[rowIndex][4] = txtHelp.getText();
frame1.dispose();
}
table.updateUI();
} else if (e.getActionCommand().equals("Cancel")) {
frame1.dispose();
}
}
}// end
class JTextFieldLimit extends PlainDocument {
private int limit;
JTextFieldLimit(int limit) {
super();
this.limit = limit;
}
JTextFieldLimit(int limit, boolean upper) {
super();
this.limit = limit;
}
#Override
public void insertString(int offset, String str, AttributeSet attr)
throws BadLocationException {
if (str == null) {
return;
}
if ((getLength() + str.length()) <= limit) {
super.insertString(offset, str, attr);
}
}
}
public static void main(String[] args) {
new MainGUI();
}
}
You need to call flush() method once at the end of printing content to file.
Like,
else if(e.getActionCommand().equals("Save")){
try {
PrintWriter out = new PrintWriter("filename.txt");
out.println(txtID.getText());
out.println(txtName.getText());
out.println(txtCourse.getText());
out.println(txtProfessor.getText());
out.println(txtHelp.getText());
out.flush();
} catch (FileNotFoundException ex) {
}
}
The java.io.Writer.flush() method flushes the stream. If the stream has saved any characters from the various write() methods in a buffer, write them immediately to their intended destination. Then, if that destination is another character or byte stream, flush it. Thus one flush() invocation will flush all the buffers in a chain of Writers and OutputStreams.
The print method will call write method in class PrintWriter, piece of source code is as follows:
/**
* Prints a String and then terminates the line. This method behaves as
* though it invokes <code>{#link #print(String)}</code> and then
* <code>{#link #println()}</code>.
*
* #param x the <code>String</code> value to be printed
*/
public void println(String x) {
synchronized (lock) {
print(x);
println();
}
}
We can see in print() method, it will call write() method.
/**
* Prints a string. If the argument is <code>null</code> then the string
* <code>"null"</code> is printed. Otherwise, the string's characters are
* converted into bytes according to the platform's default character
* encoding, and these bytes are written in exactly the manner of the
* <code>{#link #write(int)}</code> method.
*
* #param s The <code>String</code> to be printed
*/
public void print(String s) {
if (s == null) {
s = "null";
}
write(s);
}