this.dispose() is not working to close a JFrame - java

When I add:
this.dispose();
The window is not closing, what can I do?.
I use Eclipse with windowsBuilder.
I want to close the actual window to open another window.
My code:
public class Ventana_login extends JFrame {
/**
*
*/
private static final long serialVersionUID = -7948060398287723741L;
private JPanel contentPane;
private JTextField txtUsuario;
private JPasswordField txtContrasena;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Ventana_login frame = new Ventana_login();
frame.setVisible(true);
frame.setLocationRelativeTo(null);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Ventana_login() {
setTitle("Sistema Gestor de Eventos v1.0");
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblBienvenidoAlSistema = new JLabel("Bienvenido");
lblBienvenidoAlSistema.setHorizontalAlignment(SwingConstants.CENTER);
lblBienvenidoAlSistema.setFont(new Font("Tahoma", Font.BOLD, 16));
lblBienvenidoAlSistema.setBounds(10, 11, 424, 14);
contentPane.add(lblBienvenidoAlSistema);
JLabel lblUsuario = new JLabel("Usuario");
lblUsuario.setHorizontalAlignment(SwingConstants.RIGHT);
lblUsuario.setBounds(96, 79, 70, 14);
contentPane.add(lblUsuario);
JLabel lblContrasena = new JLabel("Contrase\u00F1a");
lblContrasena.setHorizontalAlignment(SwingConstants.RIGHT);
lblContrasena.setBounds(96, 109, 70, 14);
contentPane.add(lblContrasena);
txtUsuario = new JTextField();
txtUsuario.setBounds(176, 76, 150, 20);
contentPane.add(txtUsuario);
txtUsuario.setColumns(10);
JButton btnIniciarSesion = new JButton("Iniciar Sesi\u00F3n");
btnIniciarSesion.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
Dato_login d_lgn = new Dato_login();
Logica_login l_lgn = new Logica_login();
d_lgn.setUsuario(txtUsuario.getText());
char[] contrasenaChar = txtContrasena.getPassword();
String contrasenaClean = new String(contrasenaChar);
d_lgn.setContrasena(contrasenaClean);
Dato_login d_lgn2 = l_lgn.login(d_lgn.getUsuario(), d_lgn.getContrasena());
if (Logica_login.resultado) {
Ventana_menu v_menu = new Ventana_menu();
v_menu.setVisible(true);
v_menu.setLocationRelativeTo(null);
Ventana_menu.lblPerfilActual.setText(d_lgn2.getPerfil());
Ventana_menu.lblApellidoActual.setText(d_lgn2.getApellido());
Ventana_menu.lblNombreActual.setText(d_lgn2.getNombre());
Ventana_menu.lblUsuarioActual.setText(d_lgn2.getUsuario());
if (Ventana_menu.lblPerfilActual.getText().equals("Portero")) {
Ventana_menu.btnMantenimiento_Eventos.setEnabled(false);
Ventana_menu.btnMantenimiento_Invitaciones.setEnabled(false);
Ventana_menu.btnMantenimiento_Invitados.setEnabled(false);
Ventana_menu.btnMantenimiento_Usuarios.setEnabled(false);
Ventana_menu.btnReportes.setEnabled(true);
} else {
Ventana_menu.btnMantenimiento_Eventos.setEnabled(true);
Ventana_menu.btnMantenimiento_Invitaciones.setEnabled(true);
Ventana_menu.btnMantenimiento_Invitados.setEnabled(true);
Ventana_menu.btnMantenimiento_Usuarios.setEnabled(true);
Ventana_menu.btnReportes.setEnabled(true);
}
this.dispose();
} else {
JOptionPane.showMessageDialog(contentPane, "Acceso Denegado", "Error", JOptionPane.ERROR_MESSAGE);
}
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "Exception:\n" + e, "Error: Ventana_login", JOptionPane.ERROR_MESSAGE);
}
}
});
btnIniciarSesion.setBounds(176, 163, 150, 30);
contentPane.add(btnIniciarSesion);

I will assume by window you mean JFrame:
then do:
myJframe.dispatchEvent(new WindowEvent(myJframe, WindowEvent.WINDOW_CLOSING));

Related

Scroll Bar does not adjust to JPanel dimensions, Java JScrollPane

I am trying to get a scroll bar for a Panel that will get a big number of lines, however I am stuck whit this.
As you can see in my window (click here to open the picture), Scroll bars does not adjust to the panel's dimensions
Below you can see the code i am working with:
public class Config extends JFrame {
private static JPanel contentPane;
private static JScrollPane paneSiteScroll;
private static JPanel paneSite;
private JTextField txtURL;
private JButton btnAdd;
private JLabel lblName;
private JTextField txtName;
private JPanel paneBar;
/**
* Launch the application.
*/
public static void config() {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Config frame = new Config();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
} catch (Throwable e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
* #throws Throwable
*/
public Config() throws Throwable {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 800, 550);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
//Start top Add Bar
paneBar = new JPanel();
paneBar.setBounds(0, 0, 700, 35);
contentPane.add(paneBar);
paneBar.setLayout(null);
JButton btnBack = new JButton("Back");
btnBack.setBounds(1, 3, 65, 28);
paneBar.add(btnBack);
btnBack.setVerticalAlignment(SwingConstants.TOP);
JLabel lblUrl = new JLabel("URL:");
lblUrl.setBounds(80, 9, 35, 20);
paneBar.add(lblUrl);
txtURL = new JTextField();
txtURL.setBounds(115, 5, 310, 26);
paneBar.add(txtURL);
txtURL.setColumns(10);
lblName = new JLabel("Name:");
lblName.setBounds(435, 9, 47, 20);
paneBar.add(lblName);
txtName = new JTextField();
txtName.setBounds(480, 5, 155, 26);
paneBar.add(txtName);
txtName.setColumns(10);
btnAdd = new JButton("Add");
btnAdd.setBounds(635, 3, 61, 29);
paneBar.add(btnAdd);
//End top Add Bar
//Start Scroll and Panel configuration
paneSiteScroll = new JScrollPane();
paneSite = new JPanel();
paneSite.setLayout(null);
paneSite.setBounds(10, 40, 400, 600);
/*Testing different dimensions configuration*/
paneSiteScroll.setSize(new Dimension(300, 300));
paneSiteScroll.setBounds(10, 40, 300, 200);
paneSiteScroll.setPreferredSize(new Dimension(400, 300));
/*Testing different dimensions configuration*/
paneSiteScroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
paneSiteScroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
paneSiteScroll.getViewport().add(paneSite);
contentPane.add(paneSiteScroll);
paneSiteScroll.setVisible(true);
paneSite.setVisible(true);
//End Scroll and Panel configuration
try {
Categories.categories(paneSite); //GET CATEGORIES
} catch (Throwable e) {
e.printStackTrace();
}
btnAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (!txtURL.getText().isEmpty() || !txtName.getText().isEmpty()) {
InsertDB insert = new InsertDB();
try {
insert.insertDB("INSERT INTO sites (siUrl, siName) VALUES ('" + txtURL.getText() +"'"
+ ", '" + txtName.getText() + "')",
conn);
} catch (Exception e1) {
e1.printStackTrace();
}
}
else {
JOptionPane.showMessageDialog(null, "URL or Name cannot be empty!");
}
}
});
btnBack.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//Back action button
dispose();
}
});
}
}
This is my first question, I do not know what else to add, also i visited many question from stak overflow with similar problems but i couldn't figure it out.
Thanks in advance.
Finally fixed it, I restored the layout to null and added paneSite.setPreferredSize(new Dimension(600, 600)); after paneSite.setbounds. This make it work.

I need a method that goes back to the previous screen

I need a method so that when the user presses the nextCustomerBtn it will load the previous screen.
Any help would be much appreciated.
This is the extract from class MenuPage
JButton nextCustomerBtn = new JButton("Next Customer");
nextCustomerBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
nextCustomerBtn.setBounds(364, 306, 127, 29);
contentPane.add(nextCustomerBtn);
}
This is the code for the previous screen.
public class Restaurant extends JFrame {
private JPanel contentPane;
private JTextField restaurantTxt;
private JTextField numDiners;
private JTextField numDinersTxt;
private JTextField tableNumTxt;
private JTextField numTable;
private JButton numTableSubBtn;
private JButton proceedMenuBtn;
MenuPage parent;
/**
* Launch the application.
*/
////
public static String tableNumber;
public static String dinerNumber;
////
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Restaurant frame = new Restaurant();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Restaurant() {
super("Restaurant");
parent = new MenuPage();
initGUI();
// numTable = new JTextField("NewUser", 10);
}
public void initGUI() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 840, 368);
contentPane = new JPanel();
contentPane.setBackground(new Color(100, 149, 237));
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
restaurantTxt = new JTextField();
restaurantTxt.setHorizontalAlignment(SwingConstants.CENTER);
restaurantTxt.setEditable(false);
restaurantTxt.setText("Matthew's Restaurant");
restaurantTxt.setBounds(340, 23, 191, 20);
contentPane.add(restaurantTxt);
restaurantTxt.setColumns(10);
numDiners = new JTextField("", 10);
numDiners.addKeyListener(new KeyAdapter() {
#Override
public void keyTyped(KeyEvent e) { //method to only allow the textfield to accept numbers, backspace or delete.
char c=e.getKeyChar();
if(!(Character.isDigit(c) || (c==KeyEvent.VK_BACK_SPACE)||c==KeyEvent.VK_DELETE)){
e.consume(); // consume will not allow the user to enter anyhting but a number.
if (e.getKeyCode() == 10) {
JOptionPane.showMessageDialog(Restaurant.this, "Please select a meal");
}
}
}
});
numDiners.setBounds(448, 89, 83, 26);
contentPane.add(numDiners);
numDiners.setColumns(10);
JButton numDinersSubBtn = new JButton("Submit");
numDinersSubBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dinerNumber = numDiners.getText();
numDiners.setText(""); // this sets the textfield to be blank when the submit button is entered.
}
});
numDinersSubBtn.setBounds(612, 89, 83, 29);
contentPane.add(numDinersSubBtn);
numDinersTxt = new JTextField();
numDinersTxt.setEditable(false);
numDinersTxt.setText("Number of diners ?");
numDinersTxt.setBounds(251, 89, 130, 26);
contentPane.add(numDinersTxt);
numDinersTxt.setColumns(10);
tableNumTxt = new JTextField();
tableNumTxt.setEditable(false);
tableNumTxt.setText("Table number ?");
tableNumTxt.setBounds(252, 164, 130, 26);
contentPane.add(tableNumTxt);
tableNumTxt.setColumns(10);
numTable = new JTextField("", 10);
numTable.addKeyListener(new KeyAdapter() {
#Override
public void keyTyped(KeyEvent e) {
char c=e.getKeyChar();
if(!(Character.isDigit(c) || (c==KeyEvent.VK_BACK_SPACE)||c==KeyEvent.VK_DELETE)){
e.consume();
//method to only allow the textfield to accept numbers, backspace or delete
if (e.getKeyCode() == 10) { // consume will not allow the user to enter anyhting but a number.
//tableNumber = numTable.getText();
//System.out.println("enter pressed");
}
}
}
});
numTable.setBounds(448, 164, 83, 26);
contentPane.add(numTable);
numTable.setColumns(10);
numTableSubBtn = new JButton("Submit");
numTableSubBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
tableNumber = numTable.getText();
numTable.setText("");
}
});
numTableSubBtn.setBounds(612, 164, 83, 29);
contentPane.add(numTableSubBtn);
proceedMenuBtn = new JButton("Proceed to menu");
proceedMenuBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
MenuPage nw = new MenuPage(); // the new visual class window has been created and called MenuPage. The proceedMenuBtn
nw.NewScreen(); // takes the user to the NewScreen.
}
});
proceedMenuBtn.setBounds(608, 265, 135, 29);
contentPane.add(proceedMenuBtn);
JTextPane txtpnWelcomeToMatthews = new JTextPane();
txtpnWelcomeToMatthews.setEditable(false);
txtpnWelcomeToMatthews.setText("Welcome to Matthew's Restaurant\n\nTo get started with your dining experience please enter the number of diners and the table number of your choice.\n\nPress Submit when done.\n\nPress proceed to menu.\n\nEnjoy.");
txtpnWelcomeToMatthews.setBounds(20, 38, 183, 256);
contentPane.add(txtpnWelcomeToMatthews);
}
}

Relative path for browsing folder in java

I want to modify to browse the folder through the relative path.
The code only browse through the absolute path and check only the provided directory is empty or not...plz help....thanks in advance
package fyp;
import java.awt.Color;
public class Frame2 extends JFrame {
private JPanel contentPane;
private JTextField textField;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Frame2 frame = new Frame2();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Frame2() {
textField = new JTextField();
textField.setBounds(92, 107, 272, 20);
setTitle("Plagiarm Detection System\r\n");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 600, 300);
contentPane = new JPanel();
contentPane.setBackground(Color.LIGHT_GRAY);
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton btnBrowse = new JButton("Browse");
btnBrowse.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new java.io.File("."));
chooser.setDialogTitle("Browse the folder to process");
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.setAcceptAllFileFilterUsed(true);
File file=new File("C:/Users/Shahzaib/Desktop/empty");
//File relative=new File("C:/Users/Shahzaib/Desktop/empty");
//System.out.println(relative.getName());
//System.out.println(relative.getPath());
//File file = new File("directory");
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
{
textField.setText(chooser.getSelectedFile().toString());
//System.out.println("getCurrentDirectory(): "+ chooser.getCurrentDirectory());
//System.out.println("getSelectedFile() : "+ chooser.getSelectedFile());
}
if(file.isDirectory()){
if(file.list().length>0){
Component frame = null;
JOptionPane.showMessageDialog(frame, "Directory is Not Empty.");
}else{
Component frame = null;
JOptionPane.showMessageDialog(frame, "Directory is Empty.");
}
//else
//{
// Component frame = null;
//JOptionPane.showMessageDialog(frame, "No Selection.");
}
}
});
getContentPane().add(btnBrowse);
btnBrowse.setBounds(374, 106, 89, 23);
contentPane.add(btnBrowse);
contentPane.add(textField);
textField.setColumns(10);
JButton btnProceed = new JButton("Next");
btnProceed.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dispose();
new Frame2().setVisible(true);
}
});
btnProceed.setBounds(485, 227, 89, 23);
contentPane.add(btnProceed);
JButton btnBack = new JButton("Cancel");
btnBack.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
dispose();
new Frame().setVisible(true);
}
});
btnBack.setBounds(374, 227, 89, 23);
contentPane.add(btnBack);
JLabel lblNewLabel = new JLabel("Choose Folder of Assignments");
lblNewLabel.setFont(new Font("Tahoma", Font.BOLD, 15));
lblNewLabel.setBounds(180, 11, 235, 50);
contentPane.add(lblNewLabel);
}
}
When it comes to files usually you at least want to have a try{} and catch{}.
Hints: if you want to find the directory of a file, try file.getParent() or file.getParentFile(). Additionally, you should check to see if the file exists .exists() or isDirectory().

JAVA two way communication between classes

I want to be able to create an instance of my Client class in my GUI and then pass GUI.this as a parameter for the Client constructor but I'm not sure exactly how to do that. I know I'm missing something obvious! I want to be able to call methods on the other from either class. Obviously I have commented code out because I don't know how or what I am supposed to do to achieve this two way communication without merging the classes! I want to be able to do stuff like send a command through the Client from the GUI class when the "Up" button is clicked on the GUI etc. Thanks for the help in advance.
Client class:
public class Client{
//static playerGUI GUI;
public static void main(String[] args) {
//GUI = new playerGUI();
//GUI.getFrame().setVisible(true);
//Client cli = new Client("localhost",4444);
}
public Client(playerGUI GUI){
try{
final Socket sock = new Socket("localhost",4444);
final DataInputStream in = new DataInputStream(sock.getInputStream());
final PrintStream out = new PrintStream(sock.getOutputStream());
DataInputStream inputLine = new DataInputStream(new BufferedInputStream(System.in));
final Thread serverResponse = new Thread(){
public void run(){
System.out.println("DUNGEON OF DOOM HAS STARTED");
if(sock != null){
if(in != null){
try{
String response;
while((response = in.readLine()) != null){
//GUI.processgrid(response);
//send to GUI to process output!
System.out.println(response);
}
}catch(UnknownHostException uhe){
System.err.println("Unknown host1: " + uhe);
}catch(IOException ioe){
System.err.println("IOException1: " + ioe);
}catch(NullPointerException npe){
System.err.println("Null Pointer1: " + npe);
}
}
}
}
};
serverResponse.start();
if(sock != null){
if(out != null){
try{
while(true){
//inputbuttons!
String sending = inputLine.readLine();
out.println(sending);
if(sending.equals("QUIT")) break;
}
}catch(UnknownHostException uhe2){
System.err.println("Unknown host2: " + uhe2);
}catch(IOException ioe2){
System.err.println("IOException2: " + ioe2);
}catch(NullPointerException npe2){
System.err.println("Null Pointer2: " + npe2);
}
}
}
out.close();
in.close();
sock.close();
}catch(UnknownHostException uhe3){
System.err.println("Unknown host3: " + uhe3);
}catch(IOException ioe3){
System.err.println("IOException3: " + ioe3);
}catch(NullPointerException npe3){
System.err.println("Null Pointer3: " + npe3);
}
}
}
GUI Class:
public class playerGUI {
private JFrame Frame = new JFrame();
private JPanel displayPanel;
private JTextPane hostTextPane;
private JTextPane portTextPane;
private playerGUI GUI;
public static void main(String[] args) {
playerGUI GUI = new playerGUI();
GUI.Frame.setVisible(true);
Client newclient = new Client(this.playerGUI);
}
/**
* Create the application.
*/
public playerGUI() {
Frame.getContentPane().setBackground(new Color(255, 255, 255));
Frame.getContentPane().setLayout(null);
Frame.setBounds(100, 100, 500, 630);
Frame.setUndecorated(false); // REMOVES MENU BAR
Frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// ############################################################################################################################################################################
final JPanel humanGameWindow = new JPanel();
humanGameWindow.setLayout(null);
humanGameWindow.setBackground(Color.LIGHT_GRAY);
humanGameWindow.setBounds(0, 0, 500, 600);
humanGameWindow.setVisible(false);
JLabel gameTitle = new JLabel("DUNGEON OF DOOM!!");
gameTitle.setForeground(new Color(100, 149, 237));
gameTitle.setFont(new Font("Moire", Font.BOLD, 28));
gameTitle.setBounds(92, 5, 380, 50);
JButton up = new JButton("Up");
up.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// ######################
}
});
up.setBackground(new Color(100, 149, 237));
up.setBounds(274, 514, 100, 40);
JButton down = new JButton("Down");
down.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// ######################
}
});
down.setBackground(new Color(100, 149, 237));
down.setBounds(274, 555, 100, 40);
JButton left = new JButton("Left");
left.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// ######################
}
});
left.setBackground(new Color(100, 149, 237));
left.setBounds(173, 535, 100, 40);
JButton right = new JButton("Right");
right.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// ######################
}
});
right.setBackground(new Color(100, 149, 237));
right.setBounds(375, 535, 100, 40);
JButton pickup = new JButton("Pickup");
pickup.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// ######################
}
});
pickup.setBackground(new Color(100, 149, 237));
pickup.setBounds(40, 555, 100, 40);
JButton Exit = new JButton("Exit");
Exit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
Exit.setBackground(new Color(100, 149, 237));
Exit.setBounds(427, 17, 70, 40);
displayPanel = new JPanel();
displayPanel.setBounds(48, 89, 400, 400);
displayPanel.setLayout(new GridLayout(5, 5));
displayPanel.setPreferredSize(new Dimension((int) (400), (int) (400)));
for (int i = 1; i < 26; i++) {
displayPanel.add(new JLabel("Label " + i));
}
humanGameWindow.add(gameTitle);
humanGameWindow.add(up);
humanGameWindow.add(down);
humanGameWindow.add(left);
humanGameWindow.add(right);
humanGameWindow.add(pickup);
humanGameWindow.add(Exit);
humanGameWindow.add(displayPanel);
final JPanel mainMenu = new JPanel();
mainMenu.setLayout(null);
mainMenu.setBackground(Color.LIGHT_GRAY);
mainMenu.setBounds(0, 0, 500, 600);
mainMenu.setVisible(true);
JLabel mainMenuTitle = new JLabel("DUNGEON OF DOOM!!");
mainMenuTitle.setForeground(new Color(100, 149, 237));
mainMenuTitle.setFont(new Font("Moire", Font.BOLD, 28));
mainMenuTitle.setBounds(50, 13, 380, 50);
hostTextPane = new JTextPane();
hostTextPane.setToolTipText("Enter the host name");
hostTextPane.setBackground(new Color(192, 192, 192));
hostTextPane.setBounds(50, 100, 234, 30);
hostTextPane.setFont(new Font("Moire", Font.BOLD, 19));
portTextPane = new JTextPane();
portTextPane.setToolTipText("Enter the port");
portTextPane.setBackground(new Color(192, 192, 192));
portTextPane.setBounds(50, 175, 234, 30);
portTextPane.setFont(new Font("Moire", Font.BOLD, 19));
JButton playGameHuman = new JButton("Play Game Human");
playGameHuman.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mainMenu.setVisible(false);
humanGameWindow.setVisible(true);
//not sure if i need to be creating the Client here?
/*
* if (!(hostTextPane.getText().equals("")) &&
* !(portTextPane.getText().equals(""))) { try { Client cli =
* new Client(hostTextPane.getText(), Integer
* .parseInt(portTextPane.getText())); } catch (Exception e1) {
* System.out.println("Error."); } } else {
* JOptionPane.showMessageDialog(null,
* "Do not leave hostname or port no. blank."); }
*/
}
});
playGameHuman.setBackground(new Color(100, 149, 237));
playGameHuman.setBounds(50, 345, 150, 55);
mainMenu.add(mainMenuTitle);
mainMenu.add(mainMenuQuit);
mainMenu.add(playGameHuman);
mainMenu.add(hostTextPane);
mainMenu.add(portTextPane);
getFrame().getContentPane().add(humanGameWindow);
getFrame().getContentPane().add(mainMenu);
getFrame().setVisible(true);
}
}
public static void main(String[] args) {
playerGUI GUI = new playerGUI();
GUI.Frame.setVisible(true);
Client newclient = new Client(GUI);
}
main is a static method, which means it is run in a static context (ie, not "as" any instantiated object). This means you can't access this in main because there is no this to access. You need to access playerGUI with just playerGUI or playerGUI.playerGUI in your Client.main method. Also, you need to set the field playerGUI.playerGUI to static.
Instead of this:
Client newclient = new Client(this.playerGUI);
you need this:
Client newclient = new Client(GUI);
Notice that as main is static there is no this defined.
Also consider changing the names of your class and variables to follow Java naming conventions:
playerGUI should be PlayerGUI
GUI should be gui or whatever you feel like but starting with lowercase
Also do you notice that you are not using that field called GUI? You are only using the variable GUI. So it may be adding up to the confusion.

Java, runing "textArea = new JTextArea()" taking too much time

Something strange happened to me. For some reason, it takes a long time(1.60900 seconds) till it runs the following line:
textArea = new JTextArea();
I declared textArea variable as globally.
This only happens in one window (Jframe). In others it does not happen.
public class FAQ extends JFrame
{
/*--------attributes--------*/
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private JPanel panel;
private JScrollPane scrollPaneInput;
private JScrollPane scrollPaneQuestions;
private JPanel paneQuestions;
private JPanel paneSelectOrNewFAQ;
private JButton btnEditSelection;
private JButton btnNewFAQ;
public JTextArea textArea;
private JLabel lblQuestions;
public JList list;
private User user;
private FAQ currentWindow;
private int selectedFaq = 0;
private DatabaseManager DManager;
private Vector<FAQ_class> Faqs = new Vector<FAQ_class>();
private JButton btnNewButton;
/*--------methods--------*/
public FAQ(User _user,DatabaseManager DM)
{
setResizable(false);
DManager = DM;
addWindowStateListener(new WindowStateListener() {
public void windowStateChanged(WindowEvent arg0) {
}
});
addWindowListener(new WindowAdapter() {
#Override
public void windowClosed(WindowEvent arg0) {
Menu menu = new Menu(user,DManager);
menu.setVisible(true);
}
});
currentWindow = this;
user = _user;
addGui();
if(!user.rule.equals("patient"))
{
btnEditSelection.setEnabled(true);
btnNewFAQ.setEnabled(true);
}
loadFaqs();
}//end of FAQ
public void loadFaqs()
{
Faqs = DManager.getQuestionsList();
Vector<String> temp = new Vector<String>();
for(int i = 0 ; i < Faqs.size();i++)
{
temp.addElement(Faqs.get(i).question);
}
list.setListData(temp);
}
public void addGui()
{
setTitle("FAQ - Online medical help");
setIconImage(Toolkit.getDefaultToolkit().getImage(FAQ.class.getResource("/Images/question.png")));
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setBounds(100, 100, 708, 438);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new GridLayout(1, 0, 0, 0));
addPanel();
addPanes();
addButtons();
addGroupLayout();
addJTextArea();
}//end of addGui
public void addPanel()
{
panel = new JPanel();
panel.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.add(panel);
}//end of addPanel
public void addPanes()
{
scrollPaneInput = new JScrollPane();
scrollPaneInput.setBounds(327, 0, 365, 398);
paneQuestions = new JPanel();
paneQuestions.setBounds(0, 0, 317, 38);
paneQuestions.setBackground(new Color(154, 205, 50));
}//end of addScrollPanes
public void addButtons()
{
}//end of addButtons
public void addJTextArea()
{
textArea = new JTextArea();
textArea.setEditable(false);
textArea.setFont(new Font("Courier New", Font.PLAIN, 14));
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
textArea.setAlignmentX(Component.RIGHT_ALIGNMENT);
scrollPaneInput.setViewportView(textArea);
}//end of addJTextArea
public void addGroupLayout()
{
lblQuestions = new JLabel("Questions");
lblQuestions.setHorizontalAlignment(SwingConstants.CENTER);
lblQuestions.setBounds(0, 0, 317, 38);
lblQuestions.setForeground(new Color(255, 255, 255));
lblQuestions.setFont(new Font("Tahoma", Font.BOLD, 22));
panel.setLayout(null);
scrollPaneQuestions = new JScrollPane();
scrollPaneQuestions.setBounds(0, 37, 317, 318);
list = new JList();
list.setSelectionBackground(new Color(154, 205, 50));
list.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent arg0) {
try
{
for(int i = 0; i<Faqs.size();i++)
{
if(!list.isSelectionEmpty())
if(Faqs.get(i).question.equals(list.getSelectedValue().toString()))
{
textArea.setText(Faqs.get(i).answer);
selectedFaq = i;
break;
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
});
scrollPaneQuestions.setViewportView(list);
panel.add(scrollPaneQuestions);
panel.add(paneQuestions);
paneQuestions.setLayout(null);
paneQuestions.add(lblQuestions);
panel.add(scrollPaneInput);
paneSelectOrNewFAQ = new JPanel();
paneSelectOrNewFAQ.setBounds(0, 348, 317, 50);
btnEditSelection = new JButton("Edit Selected");
btnEditSelection.setBounds(68, 11, 131, 40);
btnEditSelection.setEnabled(false);
btnEditSelection.addActionListener(new ActionListener() {
//open EditFAQ to edit FAQ
public void actionPerformed(ActionEvent e) {
if(!list.isSelectionEmpty())
{
EditFAQ faq = new EditFAQ(user,Faqs.get(selectedFaq),currentWindow,DManager);
faq.setVisible(true);
currentWindow.setEnabled(false);
}
else
{
JOptionPane.showMessageDialog(null,"You must select for the list first.");
}
}
});
btnEditSelection.setIcon(new ImageIcon(FAQ.class.getResource("/Images/tool.png")));
btnNewFAQ = new JButton("New FAQ");
btnNewFAQ.setBounds(203, 11, 114, 40);
btnNewFAQ.setEnabled(false);
btnNewFAQ.addActionListener(new ActionListener() {
//open EditFAQ to make new FAQ
public void actionPerformed(ActionEvent e) {
EditFAQ faq = new EditFAQ(user,null,currentWindow,DManager);
faq.setVisible(true);
currentWindow.setEnabled(false);
}
});
btnNewFAQ.setMinimumSize(new Dimension(95, 23));
btnNewFAQ.setMaximumSize(new Dimension(95, 23));
btnNewFAQ.setPreferredSize(new Dimension(95, 23));
btnNewFAQ.setIcon(new ImageIcon(FAQ.class.getResource("/Images/add.png")));
btnNewButton = new JButton("");
btnNewButton.setBounds(0, 10, 42, 41);
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dispose();
}
});
btnNewButton.setIcon(new ImageIcon(FAQ.class.getResource("/Images/left.png")));
panel.add(paneSelectOrNewFAQ);
paneSelectOrNewFAQ.setLayout(null);
paneSelectOrNewFAQ.add(btnNewButton);
paneSelectOrNewFAQ.add(btnEditSelection);
paneSelectOrNewFAQ.add(btnNewFAQ);
}//end of addGroupLayout
}//end of class
Something strange happened to me. For some reason, it takes a long time(5 second~) till it runs the following line: Run this class and give me the result:
import java.text.DecimalFormat;
import java.text.NumberFormat;
import javax.swing.JTextArea;
public class JTextAreaRunningTime {
JTextArea textArea;
public JTextAreaRunningTime(){
long startTime = System.currentTimeMillis();
textArea = new JTextArea();
long endTime = System.currentTimeMillis();
NumberFormat nf = new DecimalFormat("#0.00000");
String totalTime = nf.format((endTime-startTime)/1000d);
System.out.println("Execution time is " + totalTime + " seconds");
}
public static void main (String...argW){
new JTextAreaRunningTime();
}
}

Categories