I'm trying to link my login class to my Laptop class but when I try to run the program it's only display "login successful" and when I press ok it's appeared as a blank frame. can someone tell me why? I already try to mess around with the button action performed but still display blank frame as result.
login class
import java.awt.*;
import java.io.*;
import javax.swing.*;
public class login extends JFrame{
JFrame frame = new JFrame();
JButton btnLogin;
JTextField fieldPass, fieldUser;
JLabel lblUser, lblPass;
String filePath="password.txt";
String filePathUser="userrname.txt";
String password="";
String username="";
BufferedWriter bw=null;
BufferedWriter bw2=null;
FileWriter fw=null;
FileWriter fw2=null;
File textFile=new File(filePath);
File textFileUser=new File(filePathUser);
Boolean login=false;
public login() {
function();
}
private void readFile() throws FileNotFoundException{
String user="";
String pass="";
boolean passFound=false;
boolean userFound=false;
BufferedReader passReader=null;
BufferedReader userReader=null;
password=fieldPass.getText();
username=fieldUser.getText();
boolean notFound=false;
try{
passReader=new BufferedReader(new FileReader("D:\\sementara buat ngoding\\password.txt"));
userReader=new BufferedReader(new FileReader("D:\\sementara buat ngoding\\username.txt"));
do{
user=userReader.readLine();
if (username.equalsIgnoreCase(user)) {
userFound=true;
}
pass=passReader.readLine();
if (password.equalsIgnoreCase(pass)) {
passFound=true;
}
if (pass==null||user==null) {
notFound=true;
}
}while(!userFound&&!passFound&&!notFound);
if (userFound&&passFound) {
login=true;
}
}
catch(IOException ex){
}
finally{
try{
if (passReader!=null) {
passReader.close();
}
if (userReader!=null) {
userReader.close();
}
}
catch(IOException ioe){
JOptionPane.showMessageDialog(null, "close error");
}
}
}
#SuppressWarnings("unchecked")
private void function() {
btnLogin = new JButton();
fieldPass = new JTextField();
fieldUser = new JTextField();
lblUser = new JLabel();
lblPass = new JLabel();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
btnLogin.setText("LOGIN");
btnLogin.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnLoginActionPerformed(evt);
}
});
fieldPass.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
fieldPassActionPerformed(evt);
}
});
lblUser.setText("USERNAME:");
lblPass.setText("PASSWORD:");
}
private void fieldPassActionPerformed(java.awt.event.ActionEvent evt) {
}
private void btnLoginActionPerformed(java.awt.event.ActionEvent evt) {
try{
readFile();
if (login==true) {
JOptionPane.showMessageDialog(null, "login Success");
Laptop lapcl = new Laptop();
lapcl.setVisible(true);
}
else{
JOptionPane.showMessageDialog(null, "Login Failed");
}
}
catch(IOException ioe){
}
}
public static void main(String args[]) {
login LOG = new login();
JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.setSize(500, 200);
panel.setBackground(Color.decode("#a020f0"));
LOG.lblUser.setBounds(72, 30, 100, 30);
LOG.lblUser.setBackground(Color.decode("#a020f0"));
LOG.lblUser.setFont(new Font("Arial",Font.BOLD,14));
LOG.fieldUser.setBounds(202, 30, 200, 30);
LOG.lblPass.setBounds(72, 60, 100, 30);
LOG.lblPass.setBackground(Color.decode("#a020f0"));
LOG.lblPass.setFont(new Font("Arial",Font.BOLD,14));
LOG.fieldPass.setBounds(202, 60, 200, 30);
LOG.btnLogin.setBounds(302, 100, 100, 30);
LOG.btnLogin.setFont(new Font("Arial",(Font.BOLD),12));
LOG.btnLogin.setBackground(Color.decode("#7d26cd"));
frame.setSize(500, 200);
frame.setVisible(true);
frame.add(LOG.lblUser);
frame.add(LOG.fieldPass);
frame.add(LOG.lblPass);
frame.add(LOG.fieldUser);
frame.add(LOG.btnLogin);
frame.add(panel);
}
}
Laptop class
import java.awt.*;
import java.io.*;
import javax.swing.*;
public class Laptop extends JFrame{
JFrame frame = new JFrame();
JButton btnLaptop, btnTrans, btnHist;
public Laptop(){
function();
}
private void function() {
btnLaptop = new JButton();
btnTrans = new JButton();
btnHist = new JButton();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
btnLaptop.setText("Laptop Data");
btnTrans.setText("Transaction");
btnHist.setText("Transaction History");
}
public static void main(String[] args) {
Laptop LAP = new Laptop();
JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.setSize(900, 600);
panel.setBackground(Color.decode("#a020f0"));
LAP.btnLaptop.setBounds(20, 20, 120, 30);
LAP.btnLaptop.setFont(new Font("Arial",(Font.BOLD),15));
LAP.btnLaptop.setBackground(Color.decode("#7d26cd"));
LAP.btnTrans.setBounds(160, 20, 120, 30);
LAP.btnTrans.setFont(new Font("Arial",(Font.BOLD),15));
LAP.btnTrans.setBackground(Color.decode("#7d26cd"));
LAP.btnHist.setBounds(300, 20, 120, 30);
LAP.btnHist.setFont(new Font("Arial",(Font.BOLD),15));
LAP.btnHist.setBackground(Color.decode("#7d26cd"));
frame.setVisible(true);
frame.setSize(900, 600);
frame.add(LAP.btnLaptop);
frame.add(LAP.btnTrans);
frame.add(LAP.btnHist);
frame.add(panel);
}
}
You are running login.class file. So main function of Laptop class never called.
You can do the things into btnLoginActionPerformed the things you have done into the main method of Laptop class.
So your btnLoginActionPerformed method of login class will be like this.....
private void btnLoginActionPerformed(java.awt.event.ActionEvent evt) {
try{
readFile();
if (login==true) {
JOptionPane.showMessageDialog(null, "login Success");
Laptop LAP = new Laptop();
JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.setSize(900, 600);
panel.setBackground(Color.decode("#a020f0"));
LAP.btnLaptop.setBounds(20, 20, 120, 30);
LAP.btnLaptop.setFont(new Font("Arial",(Font.BOLD),15));
LAP.btnLaptop.setBackground(Color.decode("#7d26cd"));
LAP.btnTrans.setBounds(160, 20, 120, 30);
LAP.btnTrans.setFont(new Font("Arial",(Font.BOLD),15));
LAP.btnTrans.setBackground(Color.decode("#7d26cd"));
LAP.btnHist.setBounds(300, 20, 120, 30);
LAP.btnHist.setFont(new Font("Arial",(Font.BOLD),15));
LAP.btnHist.setBackground(Color.decode("#7d26cd"));
frame.setVisible(true);
frame.setSize(900, 600);
frame.add(LAP.btnLaptop);
frame.add(LAP.btnTrans);
frame.add(LAP.btnHist);
frame.add(panel);
}
else{
JOptionPane.showMessageDialog(null, "Login Failed");
}
}
catch(IOException ioe){
}
}
you can also remove the main method of Laptop class. because it is useless.
Related
I have tried telling it to dispose the file explorer and recreate it works but I cannot seem to get my file image on it now any help in making it not quit in the first place?
here is the code(btw I am on IntelliJ IDEA CE):
package os_pack;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class OS extends JFrame implements ActionListener {
String title = "waliOS";
String message = "please login";
int width = 600;
int height = 400;
JButton b;
JLabel label;
JTextField text;
JLabel c;
JPasswordField pass;
JFrame f;
JFrame f2;
JLabel username;
JLabel password;
JLabel welcomeMain;
JFrame folderFrame;
JFrame textFrame;
JLabel folderLabel;
OS() {
f = new JFrame(title);
f.setSize(width, height);
f.setLocationRelativeTo(null);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
label = new JLabel(message);
label.setBounds(200, 100, 200, 50);
label.setForeground(Color.WHITE);
text = new JTextField();
text.setBounds(200, 150, 200, 30);
b = new JButton("login");
b.setBounds(200, 250, 200, 50);
b.addActionListener(this);
pass = new JPasswordField();
pass.setBounds(200, 200, 200, 30);
c = new JLabel();
c.setBounds(200, 300, 200, 50);
c.setForeground(Color.WHITE);
username = new JLabel("username");
username.setBounds(130, 140, 200, 50);
username.setForeground(Color.WHITE);
password = new JLabel("password");
password.setBounds(130, 190, 200, 50);
password.setForeground(Color.WHITE);
f.add(password);
f.add(username);
f.add(c);
f.add(pass);
f.add(b);
f.add(label);
f.add(text);
f.setLayout(null);
f.setVisible(true);
f.setResizable(false);
f.getContentPane().setBackground(Color.BLACK);
}
public void mainPage(){
f.dispose();
f2 = new JFrame();
f2.setTitle(title);
f2.setSize(width, height);
f2.setLocationRelativeTo(null);
f2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f2.setResizable(false);
f2.setLayout(null);
f2.setVisible(true);
f2.setResizable(false);
f2.getContentPane().setBackground(Color.BLACK);
welcomeMain = new JLabel("this is the home page");
welcomeMain.setForeground(Color.WHITE);
welcomeMain.setBounds(200, 100, 200, 50);
f2.add(welcomeMain);
ImageIcon folder = new ImageIcon(getClass().getResource("OS_file.png"));
JLabel folderLabel = new JLabel(folder);
folderLabel.setBounds(300, 200, 80, 80);
folderLabel.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent me) {
folderPage();
}
});
ImageIcon textEdit = new ImageIcon(getClass().getResource("text_edit.png"));
JLabel textImage = new JLabel(textEdit);
textImage.setBounds(200, 200, 80, 80);
textImage.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent em){
textEditPage();
}
});
f2.add(folderLabel);
f2.add(textImage);
}
public void folderPage() {
f2.dispose();
folderFrame = new JFrame(title + " folder");
folderFrame.setSize(width, height);
folderFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
folderFrame.setLocationRelativeTo(null);
folderFrame.setResizable(false);
folderFrame.setLayout(null);
folderFrame.setVisible(true);
folderFrame.getContentPane().setBackground(Color.BLACK);
JLabel test = new JLabel("this is the folder page");
test.setForeground(Color.WHITE);
test.setBounds(300, 200, 200, 50);
JButton back = new JButton("back");
back.setBounds(10, 10, 100, 30);
back.addActionListener (new ActionListener() {
#Override
public void actionPerformed (ActionEvent e) {
mainPage();
folderFrame.dispose();
}
});
JPopupMenu menu = new JPopupMenu();
JMenuItem newFolder = new JMenuItem("new Folder");
newFolder.addActionListener(this);
newFolder.setActionCommand("NF");
menu.add(newFolder);
folderFrame.addMouseListener((new MouseListener() {
#Override
public void mouseClicked(MouseEvent e) {}
#Override
public void mousePressed(MouseEvent e) {
if(SwingUtilities.isRightMouseButton(e)){
menu.show(folderFrame, e.getX(), e.getY());
}
}
#Override
public void mouseReleased(MouseEvent e) {}
#Override
public void mouseEntered(MouseEvent e) {}
#Override
public void mouseExited(MouseEvent e) {}
}));
ImageIcon folder = new ImageIcon("folder.png");
folderLabel = new JLabel(folder);
folderLabel.setBounds(300, 200, 80, 80);
folderFrame.add(test);
folderFrame.add(back);
}
public void textEditPage() {
f2.dispose();
textFrame = new JFrame(title + " text editor");
textFrame.setResizable(false);
textFrame.setLayout(null);
textFrame.setSize(width, height);
textFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
textFrame.setVisible(true);
textFrame.setLocationRelativeTo(null);
textFrame.getContentPane().setBackground(Color.BLACK);
JTextArea textArea = new JTextArea();
Font font = new Font(
Font.MONOSPACED,
Font.PLAIN,
textArea.getFont().getSize());
textArea.setFont(font);
textArea.setBounds(1, 30, 599, 399);
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
JLabel title = new JLabel("Text Editor");
title.setBounds(250, 2, 100, 30);
title.setForeground(Color.WHITE);
JButton back = new JButton("back");
back.setBounds(10, 4, 100, 30);
back.addActionListener (new ActionListener() {
#Override
public void actionPerformed (ActionEvent e) {
mainPage();
textFrame.dispose();
}
});
textFrame.add(back);
textFrame.add(title);
textFrame.add(textArea);
}
public static void main(String[] args){
new OS();
}
#Override
public void actionPerformed(ActionEvent e) {
String user = text.getText();
String pass1 = pass.getText();
if (user.trim().equals("wali") && pass1.trim().equals("haider")) {
c.setText("welcome wali");
mainPage();
} else if(user.trim().equals("admin") && pass1.trim().equals("admin")) {
c.setText("welcome admin");
mainPage();
} else {
c.setText("wrong user");
}
String command = e.getActionCommand();
switch (command) {
case "NF":
System.out.println("done");
folderPage();
folderFrame.dispose();
System.out.print("hello");
folderFrame.add(folderLabel);
}
}
}
can I please get some help on this because I am really stuck if you have questions tell me in the comments that will be very helpful
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));
This is my LoginGUI class, I want to move from this GUI class to another "StudentGUI" class. It seems so simple but I can't figure out
JButton btnNewButton_1 = new JButton("Log In");
btnNewButton_1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
if(Username.equals(textField1.getText())){
if(Password.equals(textField2.getText())){
// close(LoginGUI);
// run(StudentGUI);
**Missing function**
msg = "Loged in!";
}else{
msg = "Login Denied";
}
}else{
msg = "Login Denied";
}
JOptionPane.showMessageDialog(null,msg);
}
});
btnNewButton_1.setBounds(157, 230, 89, 23);
frame.getContentPane().add(btnNewButton_1);
}
}
If you would like to switch between multiple views, use the CardLayout Here's a simple example
package main.frames;
import javax.swing.*;
import java.awt.*;
public class MainFrame extends JFrame
{
static JPanel homeContainer;
static JPanel homePanel;
static JPanel otherPanel;
static CardLayout cl;
public MainFrame()
{
JButton showOtherPanelBtn = new JButton("Show Other Panel");
JButton backToHomeBtn = new JButton("Show Home Panel");
cl = new CardLayout(5, 5);
homeContainer = new JPanel(cl);
homeContainer.setBackground(Color.black);
homePanel = new JPanel();
homePanel.setBackground(Color.blue);
homePanel.add(showOtherPanelBtn);
homeContainer.add(homePanel, "Home");
otherPanel = new JPanel();
otherPanel.setBackground(Color.green);
otherPanel.add(backToHomeBtn);
homeContainer.add(otherPanel, "Other Panel");
showOtherPanelBtn.addActionListener(e -> cl.show(homeContainer, "Other Panel"));
backToHomeBtn.addActionListener(e -> cl.show(homeContainer, "Home"));
add(homeContainer);
cl.show(homeContainer, "Home");
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setLocationRelativeTo(null);
setExtendedState(JFrame.MAXIMIZED_BOTH);
setTitle("CardLayout Example");
pack();
setVisible(true);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(MainFrame::new);
}
}
As I said in the title, I am writing a code for a small program in java. I used Internal Frames to implement it. The thing is I am trying to add a login option to the program. The login class is a jInternalFrame and I want it to Enable/Disable specific buttons in my main window. I tried google-ing a solution but didn't seem to find it. (Keep in mind that I'm really new to programing so I expect there might be other problems in my code I don't see at the moment).
Main Window code:
import javax.swing.JDesktopPane;
public class FereastraPrincipala extends JFrame {
private static final long serialVersionUID = 1L;
JDesktopPane jdpDesktop;
static int openFrameCount = 0;
public FereastraPrincipala() {
super("Fereastra Principala");
// Make the main window positioned as 50 pixels from each edge of the
// screen.
int inset = 50;
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
setBounds(inset, inset, screenSize.width - inset * 2,screenSize.height - inset * 2);
// Add a Window Exit Listener
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
// Create and Set up the GUI.
jdpDesktop = new JDesktopPane();
// A specialized layered pane to be used with JInternalFrames
setContentPane(jdpDesktop);
setJMenuBar(createMenuBar());
// Make dragging faster by setting drag mode to Outline
jdpDesktop.putClientProperty("JDesktopPane.dragMode", "outline");
}
private JMenuBar createMenuBar() {
JMenuBar menuBar = new JMenuBar();
JMenu mnFile = new JMenu("File");
mnFile.setMnemonic(KeyEvent.VK_F);
JMenuItem mntmLogin = new JMenuItem("Login");
mnFile.add(mntmLogin);
mntmLogin.setMnemonic(KeyEvent.VK_N);
menuBar.add(mnFile);
mntmLogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
login();
}
});
JMenuItem mntmLogout = new JMenuItem("Logout");
mnFile.add(mntmLogout);
mntmLogout.setEnabled(true);
JMenuItem mntmCreazaUser = new JMenuItem("Creaza User");
mntmCreazaUser.setMnemonic(KeyEvent.VK_C);
mnFile.add(mntmCreazaUser);
mntmCreazaUser.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
creazaUser();
}
});
JMenuItem mntmExit = new JMenuItem("Exit");
mntmExit.setMnemonic(KeyEvent.VK_X);
mnFile.add(mntmExit);
mntmExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
JMenu mnAdministrator = new JMenu("Administrator");
mnAdministrator.setMnemonic(KeyEvent.VK_N);
menuBar.add(mnAdministrator);
mnAdministrator.setEnabled(true);
JMenu mnPresedinte = new JMenu("Presedinte");
mnPresedinte.setMnemonic(KeyEvent.VK_P);
menuBar.add(mnPresedinte);
mnPresedinte.setEnabled(true);
JMenuItem mnHelp = new JMenuItem("Help");
mnHelp.setMnemonic(KeyEvent.VK_H);
menuBar.add(mnHelp);
mnHelp.setEnabled(true);
mnHelp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
help();
}
});
return menuBar;
}
protected void login() {
Login frame = new Login();
frame.setVisible(true);
// Every JInternalFrame must be added to content pane using JDesktopPane
jdpDesktop.add(frame);
try {
frame.setSelected(true);
} catch (java.beans.PropertyVetoException e) {
}
}
protected void help() {
Help frame1 = new Help();
frame1.setVisible(true);
jdpDesktop.add(frame1);
try {
frame1.setSelected(true);
} catch (java.beans.PropertyVetoException e) {
}
}
protected void creazaUser() {
CreazaUser frame = new CreazaUser();
frame.setVisible(true);
jdpDesktop.add(frame);
try {
frame.setSelected(true);
} catch (java.beans.PropertyVetoException e) {
}
}
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException {
FereastraPrincipala frame = new FereastraPrincipala();
frame.setVisible(true);
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
}
Login class code:
import java.awt.EventQueue;
public class Login extends JInternalFrame {
private static Login instance = null;
private JTextField textField;
private JPasswordField passwordField;
public static Login getInstance(){
if(instance == null) {instance = new Login(); }
return instance;
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Login frame = new Login();
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Login() {
super("Login", false, true, false, false);
setVisible(true);
setBounds(200, 200, 290, 173);
JPanel panel = new JPanel();
getContentPane().add(panel, BorderLayout.CENTER);
panel.setLayout(null);
JLabel lblNewLabel = new JLabel("Username:");
lblNewLabel.setBounds(22, 29, 79, 14);
panel.add(lblNewLabel);
JLabel label = new JLabel("Parola:");
label.setBounds(22, 54, 79, 14);
panel.add(label);
textField = new JTextField();
textField.setColumns(10);
textField.setBounds(123, 26, 98, 20);
panel.add(textField);
passwordField = new JPasswordField();
passwordField.setBounds(123, 51, 98, 20);
panel.add(passwordField);
JButton button = new JButton("Autentificare");
button.setBounds(80, 97, 112, 23);
panel.add(button);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String user = textField.getText();
String pass = passwordField.getText();
if(user.equals("admin") && pass.equals("admin")) {
FereastraPrincipala(mntmLogout.setEnabled(true));
FereastraPrincipala(mnAdministrator.setEnabled(true));
JOptionPane.showMessageDialog(null,"Login esuat","Login esuat",JOptionPane.ERROR_MESSAGE);
} else if (user.equals("prez") && pass.equals("prez")) {
/* FereastraPrincipala(mntmLogout.setEnabled(true)):
FereastraPrincipala(mnPresedinte.setEnabled(true)); */
JOptionPane.showMessageDialog(null,"Login esuat","Login esuat",JOptionPane.ERROR_MESSAGE);
} else { JOptionPane.showMessageDialog(null,"Login esuat","Login esuat",JOptionPane.ERROR_MESSAGE);}
}
});
}
}
i have written a code to create a sms form and i want to add the ability to show error message when the text area is empty. i put JOptionpane in my code but diologe dose not appear when i run the program! here is my code
private void initialize() {
frame = new JFrame("?????? ? ????? ?????");
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JOptionPane optionPane = new JOptionPane();
JPanel middlePanel = new JPanel();
txtPath = new JTextField();
txtPath.setBounds(150, 10, 200, 21);
frame.getContentPane().add(txtPath);
txtPath.setColumns(10);
txtPath2 = new JTextField();
txtPath2.setBounds(150, 65, 200, 21);
frame.getContentPane().add(txtPath2);
txtPath2.setColumns(20);
JButton btnBrowse = new JButton("?????");
btnBrowse.setBounds(5, 10, 87, 23);
frame.getContentPane().add(btnBrowse);
final JButton ok = new JButton("?????");
ok.setBounds(250, 230, 87, 23);
frame.getContentPane().add(ok);
JButton cancel = new JButton("???");
cancel.setBounds(110, 230, 87, 23);
frame.getContentPane().add(cancel);
final JTextArea textarea = new JTextArea();
textarea.setBounds(50, 100, 300, 100);
frame.getContentPane().add(textarea);
textarea.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
JProgressBar progressBar = new JProgressBar(0, 100);
progressBar.setSize(10, 1);
progressBar.setForeground(Color.blue);
frame.getContentPane().add(progressBar);
btnBrowse.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser fileChooser = new JFileChooser();
// For Directory
fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
// For File
//fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
fileChooser.setAcceptAllFileFilterUsed(false);
int rVal = fileChooser.showOpenDialog(null);
if (rVal == JFileChooser.APPROVE_OPTION) {
txtPath.setText(fileChooser.getSelectedFile().toString());
fileChooser.setFileFilter(new FileNameExtensionFilter("Text Files", "txt", "rtf"));
}
}
});
ok.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(textarea.getLineCount()>=1)
{
test t=new test();
ReadTextFile readTextFile=new ReadTextFile();
t.testMethode(txtPath2.getText(), textarea.getText(),readTextFile.readFile(txtPath.getText()) );
}
else
JOptionPane.showMessageDialog(null, "alert", "alert", JOptionPane.ERROR_MESSAGE);
}
});
cancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
});
}
}
GUI's are event driven environments. Something happens, you respond to it.
You if-else statement will never be false because the time it is executed, the textarea will be blank (have no text).
You need to respond to some event (ie send for example) at which time you would make your check to valid the form.
Take a look at Creating a GUI with Swing for more details
Updated with example
public class Example {
public static void main(String[] args) {
new Example();
}
public Example() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private final JTextArea msg;
public TestPane() {
msg = new JTextArea(10, 20);
JButton send = new JButton("Send");
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
add(new JScrollPane(msg), gbc);
add(send, gbc);
send.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (msg.getText().trim().length() > 0) {
// Send msg
} else {
JOptionPane.showMessageDialog(TestPane.this, "Please write something (nice)", "Error", JOptionPane.ERROR_MESSAGE);
}
}
});
}
}
}
Updated based on changes to the answer by the OP
if(textarea.getLineCount()>=1) will always return true. Try using msg.getText().trim().length() > 0 instead to determine the JTextArea contains text or not...
Updated
mKobel has made an excellent point. You really should avoid using null layouts. You don't control what font size or screen DPI/resolution your application might need to work on. Layout managers take out the guess work.
You should try checking out A visual guide to layout managers and Using layout managers for more details