Tutoring Log, Confuse don code for a JButton - java

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);
}

Related

Can you add JButtons inside a JPanel

I'm making a Battleship game using one board. The picture below shows how the board GUI should look. My current code sets up a board without the 'menu-layer'. (see picture)
I tried doing this using Swing GUI designer in Intellij and got the following form (see picture), but can't find a way to insert these buttons inside the panel. Currently, I have got the following code.
package BattleshipGUI;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class BoardFrame extends JFrame {
//variables
Ships ship = new Ships();
static final Color colorHit = Color.red;
static final Color colorNormal = Color.gray;
static final Color colorWater = Color.blue;
static final Color colorCarrier = Color.yellow;
static final Color colorBattleship = Color.BLACK;
static final Color colorSubmarine = Color.magenta;
static final Color colorDestroyer = Color.white;
int[][] map;
private Container contents;
int cols;
int rows;
boolean equalPoints;
Player p1 = new Player();
Player p2 = new Player();
private JPanel mainPanel; // I tried using the GUI swing designer, but I cant manage to create
//a menu-layer on top of the buttons
private JButton buttonHighScores;
private JButton quitGame;
private JLabel player1Points;
private JLabel player2Points;
private JLabel playerTurn;
JButton[][] tiles = new JButton[100][100]; // I create 100*100 buttons, but only assign the right
// number to them
public void setMap(int[][] map) {
this.map = map;
}
public void SetFrame(int r, int c) {
this.rows = r;
this.cols = c;
}
public BoardFrame(int r, int c) {
super("Battleship");
setSize(400,450); // I create a frame
this.setLayout(new GridLayout(r, c)); // I set the layout depending on the number of rows and
//columns
AttackHandler attackHandler = new AttackHandler(); // action event class
p1.turn = true; // player 1's turn is true, he commences
p2.turn= false; //player 2's turn is false
for (int i =0; i<r; i++) {
for (int j =0; j <c; j++) {
tiles[i][j] = new JButton(); // this is where all the buttons are declared
tiles[i][j].setBackground(colorNormal);
add(tiles[i][j]);
tiles[i][j].addActionListener(attackHandler);
}
}
setResizable(true);
setLocationRelativeTo(null);
setVisible(true);
setDefaultCloseOperation(this.DISPOSE_ON_CLOSE);
setSize(400,450); //the size of my frame
}
public class AttackHandler implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (source == tiles[i][j]) {
isHit(i, j);
return;
}
}
}
}
}
public void isHit(int row, int col) {
// the map consists of an 2D array
//where 0's represent the water, 1's represent the tiles that are
//already hit, and the other represent the ships
if (AllHit()) {
JOptionPane.showMessageDialog(null, "All Ships Destructed!");
setWinner();
String winner =DecideWinner();
JOptionPane.showMessageDialog(null, winner+" has won!", "Winner",
JOptionPane.PLAIN_MESSAGE);
int again = JOptionPane.showConfirmDialog(null, "Play Again", "Play
Again",JOptionPane.YES_NO_OPTION);
if (again==0){
Main.main(null);
}
dispose();
}
else if (map[row][col] == 5) {
AddPoint(p1.turn, 5); // this should add points to the player that
//has the turn
tiles[row][col].setBackground(colorCarrier);
map[row][col] = 1;
} else if (map[row][col] == 4) {
AddPoint(p1.turn, 4);
tiles[row][col].setBackground(colorBattleship);
map[row][col] = 1;
} else if (map[row][col] == 3) {
AddPoint(p1.turn, 3);
tiles[row][col].setBackground(colorSubmarine);
map[row][col] = 1;
} else if (map[row][col] == 2) {
AddPoint(p1.turn, 2);
tiles[row][col].setBackground(colorDestroyer);
map[row][col] = 1;
} else if (map[row][col] == 1) {
System.out.println("Already Hit!");
} else if (map[row][col] == 0 || map[row][col] == 9) {
tiles[row][col].setBackground(colorWater);
map[row][col] = 1;
}
p1.changeTurn(p1.turn); // every click, the turn of each player should
//switch from true to false, p1 starts with value
//true, and p2 with false
p2.changeTurn(p2.turn);
System.out.println("Points Player 1: "+p1.points);
System.out.println("Points Player 2: "+p2.points);
}
public boolean AllHit() { // if all ships are hit, a message pops up
boolean allHit = true;
for (int i = 0; i<rows;i++) {
for (int j = 0; j < cols; j++) {
if (map[i][j] != 1 && map[i][j] != 0) {
allHit = false;
break;
}
}
}
return allHit;
}
public void AddRandomShips(int rows, int cols) {
int[][] map = ship.setRandomShips(rows, cols);
setMap(map);
}
public void AddShipsNotRandom(int size, int[][] coordinates){
int[][] map = ship.PlaceShips(size, coordinates);
setMap(map);
}
public void ScoreMethod(boolean scoreMethod){
if(scoreMethod){
equalPoints = true;
}
else if(!scoreMethod){ // the second method adjusts the score
//for the second player because the first player
//is more likely to hit a ship
equalPoints = false;
}
}
public void AddPoint(boolean turn,int amount){
if (turn){
p1.points = p1.points+ amount;
}
else p2.points = p2.points+amount;
}
public void setWinner(){
if(p1.points>p2.points){
p1.setWon();
}
else p2.setWon();
}
public String DecideWinner(){
if (p1.won == true){
return "Player 1";
}
else return "Player 2";
}
}
This is how the GUI should look like:
This is what my code generates:
this is the for that I designed using Intellij's Swing Designer (the panel with 'buttons' should be filled with the JButtons I created in the code):
UPDATE :
Thanks to mr. Kroukamp, I was able to add a menu-overlay. The code looks like this:
package BattleshipGUI;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.LineBorder;
import java.awt.Dimension;
public class BoardFrame extends JFrame {
//variables
Ships ship = new Ships();
static final Color colorNormal = Color.gray;
static final Color colorWater = Color.blue;
static final Color colorCarrier = Color.yellow;
static final Color colorBattleship = Color.BLACK;
static final Color colorSubmarine = Color.magenta;
static final Color colorDestroyer = Color.white;
int[][] map;
int cols;
int rows;
boolean equalPoints;
Player p1 = new Player();
Player p2 = new Player();
JButton[][] tiles = new JButton[100][100];
public void setMap(int[][] map) {
this.map = map;
}
public void SetFrame(int r, int c) {
this.rows = r;
this.cols = c;
}
JButton highScoresButton = new JButton("High Scores");
JLabel player1ScoreTitleLabel = new JLabel(String.valueOf(p1.points));
JLabel turnTitleLabel = new JLabel(Turn());
JLabel player2ScoreTitleLabel = new JLabel(String.valueOf(p1.points));
JButton quitGameButton = new JButton("Quite Game");
JFrame frame = new JFrame("Battleship");
public BoardFrame(int r, int c) {
super("Battleship");
AttackHandler attackHandler = new AttackHandler(); // action event class
p1.turn = true; // player 1's turn is true, he commences
p2.turn= false; //player 2's turn is false
JFrame frame = new JFrame("Battleship");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// panel 1 (yellow border)
JPanel panel1 = new JPanel(new GridBagLayout());
JButton highScoresButton = new JButton("High Scores");
JLabel player1ScoreTitleLabel = new JLabel(String.valueOf(p1.points));
JLabel turnTitleLabel = new JLabel(Turn());
JLabel player2ScoreTitleLabel = new JLabel(String.valueOf(p1.points));
JButton quitGameButton = new JButton("Quite Game");
GridBagConstraints s = new GridBagConstraints();
s.weightx = 1;
s.gridx = 0;
s.gridy = 0;
panel1.add(highScoresButton, s);
s.weightx = 1;
s.gridx = 1;
s.gridy = 0;
panel1.add(player1ScoreTitleLabel, s);
s.weightx = 1;
s.gridx = 2;
s.gridy = 0;
panel1.add(turnTitleLabel);
s.weightx = 1;
s.gridx = 3;
s.gridy = 0;
panel1.add(player2ScoreTitleLabel, s);
s.weightx = 1;
s.gridx = 4;
s.gridy = 0;
panel1.add(quitGameButton, s);
// panel 2 (red border)
JPanel panel2 = new JPanel();
GridLayout layout = new GridLayout(r, c);
layout.setHgap(0);
layout.setVgap(0);
panel2.setLayout(layout);
panel2.setBorder(new LineBorder(Color.blue, 4));
for (int i =0; i<r; i++) {
for (int j =0; j < c; j++) {
tiles[i][j] = new JButton(){
#Override
public Dimension getPreferredSize() {
return new Dimension(100,100);
}
};
tiles[i][j].setBackground(colorNormal);
panel2.add(tiles[i][j]);
tiles[i][j].addActionListener(attackHandler);
}
}
frame.add(panel1, BorderLayout.NORTH);
frame.add(panel2, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
public class AttackHandler implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (source == tiles[i][j]) {
isHit(i, j);
return;
}
}
}
}
}
public void isHit(int row, int col) {
if (AllHit()) {
JOptionPane.showMessageDialog(null, "All Ships Destructed!");
setWinner();
String winner =DecideWinner();
if(p1.won){
p1.checkHighScore();
}
else if (p2.won){
p2.checkHighScore();
}
JOptionPane.showMessageDialog(null, winner, "Winner",
JOptionPane.PLAIN_MESSAGE);
int again = JOptionPane.showConfirmDialog(null, "Play Again", "Play
Again",JOptionPane.YES_NO_OPTION);
if (again==0){
Main.main(null);
}
frame.dispose();
}
else if (map[row][col] == 5) {
AddPoint(p1.turn, 5);
tiles[row][col].setBackground(colorCarrier);
map[row][col] = 1;
} else if (map[row][col] == 4) {
AddPoint(p1.turn, 4);
tiles[row][col].setBackground(colorBattleship);
map[row][col] = 1;
} else if (map[row][col] == 3) {
AddPoint(p1.turn, 3);
tiles[row][col].setBackground(colorSubmarine);
map[row][col] = 1;
} else if (map[row][col] == 2) {
AddPoint(p1.turn, 2);
tiles[row][col].setBackground(colorDestroyer);
map[row][col] = 1;
} else if (map[row][col] == 1) {
System.out.println("Already Hit!");
} else if (map[row][col] == 0 || map[row][col] == 9) {
tiles[row][col].setBackground(colorWater);
map[row][col] = 1;
}
p1.changeTurn(p1.turn);
p2.changeTurn(p2.turn);
// I cannot find a way to change the labels....
player1ScoreTitleLabel.setText(String.valueOf(p1.points));
player2ScoreTitleLabel.setText(String.valueOf(p2.points));
turnTitleLabel.setText(Turn());
System.out.println("Points Player 1: "+p1.points);
System.out.println("Points Player 2: "+p2.points);
}
public boolean AllHit() {
boolean allHit = true;
for (int i = 0; i<rows;i++) {
for (int j = 0; j < cols; j++) {
if (map[i][j] != 1 && map[i][j] != 0) {
allHit = false;
break;
}
}
}
return allHit;
}
public void AddRandomShips(int rows, int cols) {
int[][] map = ship.setRandomShips(rows, cols);
setMap(map);
}
public void AddShipsNotRandom(int size, int[][] coordinates){
int[][] map = ship.PlaceShips(size, coordinates);
setMap(map);
}
public void ScoreMethod(boolean scoreMethod){
if(scoreMethod){
equalPoints = true;
}
else {
equalPoints = false;
}
}
public void AddPoint(boolean turn,int amount){
if (turn){
p1.points = p1.points+ amount;
}
else p2.points = p2.points+amount;
}
public void setWinner(){
if(p1.points>p2.points){
p1.setWon();
}
else if (p2.points>p1.points){
p2.setWon();
}
}
public String DecideWinner(){
if (p1.won){
return "Player 1 won the game!";
}
else if (p2.won){
return "Player 2 won the game!";
}
else return "It's a tie!";
}
public String Turn(){
if (p1.turn){
return "Player 1";
}else return "Player 2";
}
This generates the following GUI:
However, I am still struggling finding a way to change the values of the text of the score JLabels, the following code did not work for me:
player1ScoreTitleLabel.setText(String.valueOf(p1.points));
player2ScoreTitleLabel.setText(String.valueOf(p2.points));
turnTitleLabel.setText(Turn())
Adding to my comment here is a small example to help get you started without the burden of an IDE for building your UI incorporating as much of Swing best practices as possible:
I opted to use JLabels as it just makes more sense
The yellow border represents panel1 which makes use of a GridBagLayout.
The red panel represents panel2 which makes use of a GridLayout.
Finally the 2 JPanels are added to a JFrame which by default uses BorderLayout.
TestApp.java:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.border.LineBorder;
public class TestApp {
public TestApp() {
createAndShowGui();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(TestApp::new);
}
private void createAndShowGui() {
JFrame frame = new JFrame("TestApp");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// panel 1 (yellow border)
JPanel panel1 = new JPanel(new GridBagLayout());
JButton highScoresButton = new JButton("High Scores");
JLabel player1ScoreLabel = new JLabel("<html>Player 1 Score:<br><h2>950</h2>");
JLabel turnLabel = new JLabel("<html>Turn:<br><h1>Player 1</h1>");
JLabel player2ScoreLabel = new JLabel("<html>Player 2 Score:<br><h2>925</h2>");
JButton quitGameButton = new JButton("Quit Game");
GridBagConstraints c = new GridBagConstraints();
c.weightx = 1;
c.gridx = 0;
c.gridy = 0;
panel1.add(highScoresButton, c);
c.weightx = 1;
c.gridx = 1;
c.gridy = 0;
panel1.add(player1ScoreLabel, c);
c.weightx = 1;
c.gridx = 2;
c.gridy = 0;
panel1.add(turnLabel);
c.weightx = 1;
c.gridx = 3;
c.gridy = 0;
panel1.add(player2ScoreLabel, c);
c.weightx = 1;
c.gridx = 4;
c.gridy = 0;
panel1.add(quitGameButton, c);
panel1.setBorder(new LineBorder(Color.YELLOW, 4)); // just for visual purposes of the answer
// panel 2 (red border)
JPanel panel2 = new JPanel();
GridLayout layout = new GridLayout(8, 8);
layout.setHgap(5);
layout.setVgap(5);
panel2.setLayout(layout);
panel2.setBorder(new LineBorder(Color.RED, 4)); // just for visual purposes of the answer
for (int i = 0; i < 64; i++) {
JLabel label = new JLabel() {
#Override
public Dimension getPreferredSize() {
return new Dimension(100, 100);
}
};
label.setOpaque(true);
label.setBackground(Color.DARK_GRAY);
panel2.add(label);
}
frame.add(panel1, BorderLayout.NORTH);
frame.add(panel2, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
}

I can't make my program to wait until GUI has finished gathering requested info (Java)

I am quite new to Java and before I end up asking this question I searched and searched SO, but I don't seem to get my head around it.
As you will see I have a class that creates a GUI, asks for some input and stores that input in a returnable String[].
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class InputConsole {
final static boolean shouldFill = true;
final static boolean shouldWeightX = true;
final static boolean RIGHT_TO_LEFT = false;
public static String[] details = new String[3];
public static JButton btn2013;
public static JButton btn2014;
public static JButton btn2015;
public static JButton btn2016;
public static JButton btnGo;
public static JTextField textField2;
public static JTextField textField4;
public static void addComponentsToPane(Container pane) {
if (RIGHT_TO_LEFT) {
pane.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
}
pane.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
if (shouldFill) {
c.fill = GridBagConstraints.HORIZONTAL;
}
btn2013 = new JButton("ZMR 2013");
btn2013.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
details[2] = "2013";
btn2014.setEnabled(false);
btn2015.setEnabled(false);
btn2016.setEnabled(false);
textField2.requestFocusInWindow();
}
});
if (shouldWeightX) {
c.weightx = 0.0;
}
c.fill = GridBagConstraints.HORIZONTAL;
c.insets = new Insets(10, 0, 0, 0);
c.gridx = 0;
c.gridy = 0;
pane.add(btn2013, c);
btn2014 = new JButton("ZMR 2014");
btn2014.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
details[2] = "2014";
btn2013.setEnabled(false);
btn2015.setEnabled(false);
btn2016.setEnabled(false);
textField2.requestFocusInWindow();
}
});
c.fill = GridBagConstraints.HORIZONTAL;
c.insets = new Insets(10, 10, 0, 0);
c.weightx = 0.0;
c.gridx = 1;
c.gridy = 0;
pane.add(btn2014, c);
btn2015 = new JButton("ZMR 2015");
btn2015.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
details[2] = "2015";
btn2013.setEnabled(false);
btn2014.setEnabled(false);
btn2016.setEnabled(false);
textField2.requestFocusInWindow();
}
});
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.0;
c.gridx = 2;
c.gridy = 0;
pane.add(btn2015, c);
btn2016 = new JButton("ZMR 2016");
btn2016.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
details[2] = "2016";
btn2013.setEnabled(false);
btn2014.setEnabled(false);
btn2015.setEnabled(false);
textField2.requestFocusInWindow();
}
});
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.0;
c.gridx = 3;
c.gridy = 0;
pane.add(btn2016, c);
JLabel textField1 = new JLabel("What was your Bib number? : ");
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 2;
c.gridwidth = 2;
pane.add(textField1, c);
textField2 = new JTextField(10);
textField2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
details[0] = textField2.getText();
textField4.requestFocusInWindow();
}
});
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 2;
c.gridy = 2;
pane.add(textField2, c);
JLabel textField3 = new JLabel("What is your email address : ");
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 3;
c.gridwidth = 2;
pane.add(textField3, c);
textField4 = new JTextField(15);
textField4.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
details[1] = textField4.getText();
btnGo.setEnabled(true);
btnGo.requestFocusInWindow();
}
});
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 2;
c.gridy = 3;
pane.add(textField4, c);
btnGo = new JButton("Go And Get Me My Diploma!");
btnGo.setEnabled(false);
btnGo.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, details[0] + " " + details[1] + " " + details[2]);
}
});
c.fill = GridBagConstraints.HORIZONTAL;
c.ipady = 0;
c.weighty = 1.0;
c.anchor = GridBagConstraints.PAGE_END;
c.insets = new Insets(10, 0, 0, 0);
c.gridx = 0;
c.gridwidth = 4;
c.gridy = 4;
pane.add(btnGo, c);
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("Zagori Mountain Running Diploma Maker");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addComponentsToPane(frame.getContentPane());
frame.pack();
frame.setSize(500, 250);
frame.setVisible(true);
}
public String[] inputBib() {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
return details;
}
But when I call this GUI in another class
public class CheckFiles {
InputConsole bibInput = new InputConsole();
String[] detailsInput = bibInput.inputBib();
private static Scanner scanner;
public String bibCorrected() {
String yearToCheck = null;
{
if (detailsInput[2] == "2016") {
yearToCheck = "ZMR2016.txt";
} else if (detailsInput[2] == "2015") {
yearToCheck = "ZMR2015.txt";
} else if (detailsInput[2] == "2014") {
yearToCheck = "ZMR2014.txt";
} else {
yearToCheck = "ZMR2013.txt";
in order to obtain that String[], I get a java.lang.NullPointerException. I Know that I get this because the program does not wait for the GUI to get all the input and files the returnable String[] as null. I think I know that I have to do something with wait() and notify() but I do not seem to understand exactly what.
Thank you in advance for any suggestions. (and very sorry for the long thread)
You could add a button on your GUI which will just call the bibCorrected() method. Currently you are showing and then returning so the array is empty and arg 2 is none existent therefor throwing an NPE. This would probably be the easiest way to resolve the issue.
Also, it's better to use String.equals(String) rather than ==. Read this StackOverflow post What is the difference between == vs equals() in Java?

How do I add 2 separate JPanels together to get 1 JPanel?

I am trying to make a sign in program with a time clock display. I am having a hard time trying to get the clock into the already made JPanel. It currently pops up 2 seperate JPanels when I run the program. Please help with any suggestions.
CODE:
private static JLabel lblUserName;
private static JTextField txtUserName;
private static JButton btnSignIn;
private static JLabel lblPassword;
private static JPasswordField txtPassword;
private static JButton btnCancel;
private static JTabbedPane tabbedPane;
public static void main(String[] args)
{
UserSignIn frame = new UserSignIn();
JFrame frm = new JFrame();
SimpleDigitalClock clock1 = new SimpleDigitalClock();
frm.add(clock1);
//Pack
frm.pack();
frame.pack();
// Set origional focus on User Name text field
txtUserName.requestFocusInWindow();
// Make Visible
frame.setVisible(true);
frm.setVisible(true);
}
static class SimpleDigitalClock extends JPanel
{
String stringTime;
int hour, minute, second;
String aHour = "";
String bMinute = "";
String cSecond = "";
public void setStringTime(String abc)
{
this.stringTime = abc;
}
public int Number(int a, int b)
{
return (a <= b) ? a : b;
}
SimpleDigitalClock()
{
Timer t = new Timer(1000, new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
repaint();
}
});
t.start();
}
#Override
public void paintComponent(Graphics v)
{
super.paintComponent(v);
Calendar rite = Calendar.getInstance();
hour = rite.get(Calendar.HOUR_OF_DAY);
minute = rite.get(Calendar.MINUTE);
second = rite.get(Calendar.SECOND);
if (hour < 10)
{
this.aHour = "0";
}
if (hour >= 10)
{
this.aHour = "";
}
if (minute < 10)
{
this.bMinute = "0";
}
if (minute >= 10)
{
this.bMinute = "";
}
if (second < 10)
{
this.cSecond = "0";
}
if (second >= 10)
{
this.cSecond = "";
}
setStringTime(aHour + hour + ":" + bMinute+ minute + ":" + cSecond + second);
v.setColor(Color.RED);
int length = Number(this.getWidth(),this.getHeight());
Font Font1 = new Font("Digital", Font.BOLD, length / 5);
v.setFont(Font1);
v.drawString(stringTime, (int) length/6, length/2);
}
#Override
public Dimension getPreferredSize()
{
return new Dimension(200, 200);
}
}
public UserSignIn()
{
initGUI();
}
public void initGUI()
{
setTitle("Login");
JPanel pnlUserSignIn = new JPanel(new GridBagLayout());
this.getContentPane().add(pnlUserSignIn);
//build table for employees signed in
JTable t = new JTable(null);
JLabel label = new JLabel("Employees Currently Signed In");
// ROW 1 BUTTONS
// Username and Sign In buttons
lblUserName = new JLabel("Username: ");
txtUserName = new JTextField("Username");
// Actions
//txtUserName.addMouseListener(this);
// Adding objects to Panel
JPanel pnlLogin = new JPanel();
pnlLogin.add(lblUserName);
pnlLogin.add(txtUserName);
//ROW 2 BUTTONS
//Password and Cancel
btnSignIn = new JButton("Sign In");
btnCancel=new JButton("Cancel");
//Actions
btnSignIn.addActionListener(this);
btnCancel.addActionListener(this);
// Adding objects to Panel
JPanel pnlPassword = new JPanel();
pnlPassword.add(btnSignIn);
pnlPassword.add(btnCancel);
JPanel detailsPanel = new JPanel();
detailsPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
GridBagConstraints gbc = new GridBagConstraints();
// Putting Objects into the grid
gbc.gridx = 0;
gbc.gridy = 0;
pnlUserSignIn.add(label, gbc);
gbc.gridx = 0;
gbc.gridy = 1;
pnlUserSignIn.add(new JScrollPane(t), gbc);
gbc.gridx = 0;
gbc.gridy = 2;
pnlUserSignIn.add(pnlLogin, gbc);
gbc.gridx = 0;
gbc.gridy = 3;
gbc.gridwidth = 2;
pnlUserSignIn.add(pnlPassword, gbc);
//gbc.gridx = 1;
//gbc.gridy = 1;
//gbc.gridwidth = 1;
//gbc.gridheight = 2;
//panel.add(detailsPanel, gbc);
this.pack();
this.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent actionEvent)
{
if(actionEvent.getSource()==btnCancel)
{
System.exit(0);
}
//if(actionEvent.getSource()==txtUserName)
//{
// txtUserName.setText("");
// txtUserName.requestFocus();
//}
}
PLEASE IGNORE THE COMMENTED CODE, I am working on many things at once.
You don't need another frame. Just add clock to existing one. For example to the SOUTH:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Calendar;
import javax.swing.BorderFactory;
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.JTabbedPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.Timer;
public class UserSignIn extends JFrame implements ActionListener{
private static JLabel lblUserName;
private static JTextField txtUserName;
private static JButton btnSignIn;
private static JLabel lblPassword;
private static JPasswordField txtPassword;
private static JButton btnCancel;
private static JTabbedPane tabbedPane;
public static void main(String[] args) {
UserSignIn frame = new UserSignIn();
SimpleDigitalClock clock1 = new SimpleDigitalClock();
frame.add(clock1, BorderLayout.SOUTH);
// Pack
frame.pack();
// Set origional focus on User Name text field
txtUserName.requestFocusInWindow();
// Make Visible
frame.setVisible(true);
}
static class SimpleDigitalClock extends JPanel {
String stringTime;
int hour, minute, second;
String aHour = "";
String bMinute = "";
String cSecond = "";
public void setStringTime(String abc) {
this.stringTime = abc;
}
public int Number(int a, int b) {
return (a <= b) ? a : b;
}
SimpleDigitalClock() {
Timer t = new Timer(1000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
repaint();
}
});
t.start();
}
#Override
public void paintComponent(Graphics v) {
super.paintComponent(v);
Calendar rite = Calendar.getInstance();
hour = rite.get(Calendar.HOUR_OF_DAY);
minute = rite.get(Calendar.MINUTE);
second = rite.get(Calendar.SECOND);
if (hour < 10) {
this.aHour = "0";
}
if (hour >= 10) {
this.aHour = "";
}
if (minute < 10) {
this.bMinute = "0";
}
if (minute >= 10) {
this.bMinute = "";
}
if (second < 10) {
this.cSecond = "0";
}
if (second >= 10) {
this.cSecond = "";
}
setStringTime(aHour + hour + ":" + bMinute + minute + ":" + cSecond
+ second);
v.setColor(Color.RED);
int length = Number(this.getWidth(), this.getHeight());
Font Font1 = new Font("Digital", Font.BOLD, length / 5);
v.setFont(Font1);
v.drawString(stringTime, (int) length / 6, length / 2);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
}
public UserSignIn() {
initGUI();
}
public void initGUI() {
setTitle("Login");
JPanel pnlUserSignIn = new JPanel(new GridBagLayout());
this.getContentPane().add(pnlUserSignIn);
// build table for employees signed in
JTable t = new JTable(null);
JLabel label = new JLabel("Employees Currently Signed In");
// ROW 1 BUTTONS
// Username and Sign In buttons
lblUserName = new JLabel("Username: ");
txtUserName = new JTextField("Username");
// Actions
// txtUserName.addMouseListener(this);
// Adding objects to Panel
JPanel pnlLogin = new JPanel();
pnlLogin.add(lblUserName);
pnlLogin.add(txtUserName);
// ROW 2 BUTTONS
// Password and Cancel
btnSignIn = new JButton("Sign In");
btnCancel = new JButton("Cancel");
// Actions
btnSignIn.addActionListener(this);
btnCancel.addActionListener(this);
// Adding objects to Panel
JPanel pnlPassword = new JPanel();
pnlPassword.add(btnSignIn);
pnlPassword.add(btnCancel);
JPanel detailsPanel = new JPanel();
detailsPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
GridBagConstraints gbc = new GridBagConstraints();
// Putting Objects into the grid
gbc.gridx = 0;
gbc.gridy = 0;
pnlUserSignIn.add(label, gbc);
gbc.gridx = 0;
gbc.gridy = 1;
pnlUserSignIn.add(new JScrollPane(t), gbc);
gbc.gridx = 0;
gbc.gridy = 2;
pnlUserSignIn.add(pnlLogin, gbc);
gbc.gridx = 0;
gbc.gridy = 3;
gbc.gridwidth = 2;
pnlUserSignIn.add(pnlPassword, gbc);
// gbc.gridx = 1;
// gbc.gridy = 1;
// gbc.gridwidth = 1;
// gbc.gridheight = 2;
// panel.add(detailsPanel, gbc);
this.pack();
this.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent actionEvent) {
if (actionEvent.getSource() == btnCancel) {
System.exit(0);
}
// if(actionEvent.getSource()==txtUserName)
// {
// txtUserName.setText("");
// txtUserName.requestFocus();
// }
}
}

How do I add a scroll bar in a null layout?

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...

How to put name to label?

I am a student programmer and I really need to fix this code to able to finish my project.
Is there any other way to put a unique name to this for loop labels?
Because whenever a user click one of the labels, the text will change its color. Not all the labels, only the one that user had clicked.
public void addComponentsToPane(final JPanel pane) {
if (RIGHT_TO_LEFT) {
pane.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
}
pane.setLayout(new GridBagLayout());
c.insets = new Insets(20, 20, 5, 5);
c.anchor = GridBagConstraints.NORTH;
if (shouldFill) {
//natural height, maximum width
c.fill = GridBagConstraints.HORIZONTAL;
}
int i;
for (i = 1; i <= 80; i++) {
if (z == 14) {
y++;
x = 0;
z = 0;
}
try {
label = new JLabel("# " + i);
labels();
c.weightx = 0.5;
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = x;
c.gridy = y;
pane.add(label, c);
x++;
z++;
set_x = x;
set_y = y;
} catch (Exception e) {
}
}
tableNum = i;
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
int UserInput = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter Number of Table:"));
int i;
for (i = tableNum; i <= (tableNum + UserInput) - 1; i++) {
if (z == 14) {
set_y++;
set_x = 0;
z = 0;
}
try {
label = new JLabel("# " + i);
labels();
c.weightx = 0.5;
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = set_x;
c.gridy = set_y;
pane.add(label, c);
set_x++;
z++;
lbl[i] = label;
// lbl[i].setForeground(Color.red);
System.out.print(lbl[i].getText());
// set_x = x;
// set_y = y;
} catch (Exception ex) {
}
}
tableNum = i;
frame.revalidate();
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "PLease Input Digits Only", "Input Error", JOptionPane.ERROR_MESSAGE);
}
}
});
}
private void labels() {
ImageIcon icon = new ImageIcon(imagePath + labelIconName);
icon.getImage().flush();
label.setIcon(icon);
label.setBackground(Color.WHITE);
label.setPreferredSize(new Dimension(80, 80));
label.setFont(new Font("Serif", Font.PLAIN, 18));
label.setForeground(Color.black);
label.setVerticalTextPosition(SwingConstants.BOTTOM);
label.setHorizontalTextPosition(SwingConstants.CENTER);
// label.setBorder(BorderFactory.createBevelBorder(0));
label.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
// String[] option = {"Available", "Occupied", "Reserved"};
// choose = (String) JOptionPane.showInputDialog(this, "Table :"+label.getText() + , "Choose transaction", JOptionPane.INFORMATION_MESSAGE, null, option, option[0]);
System.out.print(label.getName());
centerScreen();
selectAllMenu();
jDialogMenu.show();
// frame.setDefaultCloseOperation(JInternalFrame.DO_NOTHING_ON_CLOSE);
}
});
}
i want to set a name for each of the panel. So i can set a foreground to each labels.
You don't need a unique name. You need to add a MouseListener to every label that you create. Then is the mousePressed() event you can change the foreground of the label clicked by using generic code. For example:
MouseListener ml = new MouseAdapter()
{
#Override
public void mousePressed(MouseEvent e)
{
JLabel label = (JLabel)e.getSource();
label.setForeground(...);
}
}
...
label.addMouseListener( ml );

Categories