I'm using jEditorPane to act kinda as some editor, the one who asked for this of me, also needed a find replace search... so I wanted to let him select in find and then do replace on need.
so I provide this simple code:
private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {
int start = (jEditorPane1.getSelectionStart()>jEditorPane1.getSelectionEnd())?jEditorPane1.getSelectionEnd():jEditorPane1.getSelectionStart();
int max = (start>jEditorPane1.getSelectionStart())?start:jEditorPane1.getSelectionStart();
String searchWord = jTextField3.getText();
int searchIndex = jEditorPane1.getText().indexOf(searchWord, max);
if(searchIndex != -1){
jEditorPane1.select(searchIndex, searchIndex+searchWord.length());
}
else{
jEditorPane1.setSelectionStart(-1);
jEditorPane1.setSelectionEnd(-1);
}
}
fortunatelly the application return good indexes, but unfortunatelly on view windows I see no selection.
I'm also new to java, please help
PS. buttons action are provided by netbeans itself
THe sample you requested
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* test.java
*
* Created on Jun 12, 2013, 8:23:19 PM
*/
package wordchecker;
/**
*
* #author Hassan
*/
public class test extends javax.swing.JFrame {
/** Creates new form test */
public test() {
initComponents();
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
jTextPane1 = new javax.swing.JTextPane();
jTextField1 = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jScrollPane1.setViewportView(jTextPane1);
jTextField1.setText("jTextField1");
jButton1.setText("jButton1");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(24, 24, 24)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton1))
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 366, Short.MAX_VALUE))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 234, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton1))
.addContainerGap(14, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
int startFrom = jTextPane1.getSelectionStart();
if(jTextPane1.getSelectionStart() == jTextPane1.getSelectionEnd()){
startFrom = -1;
}
String searchWord = jTextField1.getText();
int searchIndex = jTextPane1.getText().indexOf(searchWord, startFrom);
if(searchIndex != -1){
jTextPane1.select(searchIndex, searchIndex+searchWord.length());
}
else{
jTextPane1.setSelectionStart(0);
jTextPane1.setSelectionEnd(0);
}
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new test().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextPane jTextPane1;
// End of variables declaration
}
The selection of a text component is only displayed when the text component has focus. When you click on the button it gains focus so you don't see the text selection. You could make the button non-focusable or you can add the following to the bottom of your actionPerformed() method:
jTextPane1.requestFocusInWindow();
Also, don't use the getText() method. This will cause problems with offsets.
int searchIndex = jTextPane1.getText().indexOf(searchWord, startFrom);
See Text and New Lines for more information and a solution. The basics of this link is to use:
int length = textPane.getDocument().getLength();
String text = textPane.getDocument().getText(0, length);
The above will only return "\n" as the EOL string so the offsets will match when you do a search and then select the text.
Edit:
I generally use code like the following:
int startFrom = jTextPane1.getCaretPosition();
Related
I'm doing a project where I need 4 buttons and each button will perform a different mathematical function of some sort. I have all of the functions written in programs separate from the program with the buttons.
I'm going to just use a sample program that I made in NetBeans instead of posting the whole code on my actual project.
public class NewJPanel extends javax.swing.JPanel {
/**
* Creates new form NewJPanel
*/
public NewJPanel() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jTextField1 = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
jTextField1.setText("jTextField1");
jButton1.setText("jButton1");
jButton2.setText("jButton2");
jButton3.setText("jButton3");
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(27, 27, 27)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jButton1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton3))
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(79, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(29, 29, 29)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 149, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton1)
.addComponent(jButton2)
.addComponent(jButton3))
.addGap(78, 78, 78))
);
}// </editor-fold>
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JTextField jTextField1;
// End of variables declaration
}
So that is the program with the buttons. Now how would I execute a program called Celsius after pressing one of the JButtons?
You must not reason in terms of programs starting other programs, but in terms of classes using other classes.
So let's say your Celsius program has a Celsius class with the method
int convertToFahrenheit(int celsiusDegrees)
Your program will make sure to have the jar file of the celsius program, containing the Celsius class, in its classpath, and will simply use, when a button is clicked
Celsius celsius = new Celsius();
int fahrenheit = celsius.convertToFehrenheit(someCelsiusDegrees);
So, to be short, the celsius program will become a library used by your new Swing program.
import java.io.*;
public class CallHelloPgm
{
public static void main(String args[])
{
Process theProcess = null;
BufferedReader inStream = null;
// call the Hello class
try
{
theProcess = Runtime.getRuntime().exec("java someProgram"); // Your magic line
}
catch(IOException e)
{
System.err.println("Error on exec() method");
e.printStackTrace();
}
// read from the called program's standard output stream
try
{
inStream = new BufferedReader(
new InputStreamReader( theProcess.getInputStream() ));
System.out.println(inStream.readLine());
}
catch(IOException e)
{
System.err.println("Error on inStream.readLine()");
e.printStackTrace();
}
} // end method
} // end class
Can someone please help me because I have to get this project in by the end of tomorrow?
Every time I try and set the text of a text field my program crashes and gives a null pointer exception. How can I overcome this?
Here is sample code where the error also occurred:
package disciplinesys;
public class NewJFrame extends javax.swing.JFrame {
/** Creates new form NewJFrame */
public NewJFrame() {
jTextField1.setText("Yes");
initComponents();
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jTextField1 = new javax.swing.JTextField();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(120, 120, 120)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 139, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(141, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(116, 116, 116)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(164, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new NewJFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JTextField jTextField1;
// End of variables declaration
}
Call jTextField1.setText("Yes"); after the initComponents();
Like this:
/** Creates new form NewJFrame */
public NewJFrame() {
initComponents();
jTextField1.setText("Yes");
}
This is because your textfield variable isn't created until the initComponents();
I have 3 java files.
DBConn - This Class conencts to the database and execute query.
UserLogin - This jFrame will take username and password and compare with "users" table
if it matches it will display "Login Successfull" in LibSysMain java file
LibSysMain - This is the main file which shows the menu.
This is the jFrame which is displayed first when application is run.
The problem is I am not able to set the "Login Successful" message in LibSysMain.
My Database is MS Access. Table name is "users". Field is "username" and "password". Both of them are of string type.
A help would be highly apprecited.
I am new in Java. I am using NetBeans 6.9.1.
Here is the list:
DBConn:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package LibSystem;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSet;
import javax.swing.JOptionPane;
/**
*
* #author Administrator
*/
public class DBConn {
Connection con;
Statement stmt;
ResultSet rs;
public void DoConnect(String querydb)
{
String SQL;
SQL=querydb;
try
{
// CONNECT TO THE DATABASE
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=C:\\Database\\libsys\\libsys.mdb";
con = DriverManager.getConnection(url);
System.out.println("\nConnected to the database");
//QUERY THE DATABASE
stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
//String SQL ="Select * from Members";
rs=stmt.executeQuery(SQL);
//MOVE CURSOR AT FIRST RECORD AND FETCH DATA
rs.next();
}
catch(ClassNotFoundException e)
{
System.out.println("\nClass not found. Check Path");
e.printStackTrace();
}
catch (SQLException err)
{
JOptionPane.showMessageDialog(null, err.getMessage());
}
}
}
UserLogin:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* UserLogin.java
*
* Created on Apr 23, 2011, 8:46:59 PM
*/
package LibSystem;
import java.sql.*;
import javax.swing.JOptionPane;
import java.lang.*;
/**
*
* #author Administrator
*/
public class UserLogin extends javax.swing.JFrame {
private String user;
private String password;
private String status;
/** Creates new form UserLogin */
public UserLogin() {
initComponents();
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
txtUserName = new javax.swing.JTextField();
txtPassword = new javax.swing.JTextField();
btnClose = new javax.swing.JButton();
btnLogin = new javax.swing.JButton();
lbUserName = new javax.swing.JLabel();
lbPassword = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
btnClose.setText("Close");
btnClose.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnCloseActionPerformed(evt);
}
});
btnLogin.setText("Login");
btnLogin.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnLoginActionPerformed(evt);
}
});
lbUserName.setText("User Name");
lbPassword.setText("Password");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(34, 34, 34)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(lbPassword)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 134, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(lbUserName)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 128, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(btnClose)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 64, Short.MAX_VALUE)
.addComponent(btnLogin))
.addComponent(txtUserName, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtPassword, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 180, Short.MAX_VALUE))))
.addGap(35, 35, 35))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(26, 26, 26)
.addComponent(lbUserName)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtUserName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(lbPassword)
.addGap(5, 5, 5)
.addComponent(txtPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnClose)
.addComponent(btnLogin))
.addContainerGap(39, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void btnLoginActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
//CREATE AN INSTANCE OF DBCONN CLASS TO CONNECT TO THE DATABASE
//WE TAKE THE USERNAME FROM THE LOGIN WINDOW AND SEARCH THE USER
//BASED ON THAT USER. IF FOUND, COMPARE IT WITH THE LOGIN WINDOW.
//IF NOT FOUND DISPLAY ERROR MESSAGE.
DBConn dbc = new DBConn();
String qry = "Select * from users where username=" + "'" + txtUserName.getText() + "'";
dbc.DoConnect(qry);
try
{
setUsername(dbc.rs.getString("username"));
setPassword(dbc.rs.getString("password"));
//TEST PRINTOUT OF USERNAME AND PASSWORD FOR DEBUGGING
System.out.println(getUsername());
System.out.println(getPassword());
if (user.equals(txtUserName.getText()) && password.equals(txtPassword.getText()))
{
JOptionPane.showMessageDialog(UserLogin.this, "Login Successfull");
this.setStatus("pass");
dispose();
}
else
{
JOptionPane.showMessageDialog(UserLogin.this, "Login unsuccessful");
setStatus("fail");
}
}
catch (SQLException err)
{
JOptionPane.showMessageDialog(UserLogin.this, err.getMessage());
}
}
private void btnCloseActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
this.dispose();
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new UserLogin().setVisible(true);
}
});
}
public void setUsername(String u)
{
user = u;
}
public void setPassword(String p)
{
password = p;
}
public String getUsername()
{
return user;
}
public String getPassword()
{
return password;
}
public void setStatus(String stat)
{
status = stat;
}
public String getStatus()
{
return status;
}
// Variables declaration - do not modify
private javax.swing.JButton btnClose;
private javax.swing.JButton btnLogin;
private javax.swing.JLabel lbPassword;
private javax.swing.JLabel lbUserName;
private javax.swing.JTextField txtPassword;
private javax.swing.JTextField txtUserName;
// End of variables declaration
}
LibSysMain:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* LibsysMain.java
*
* Created on Apr 23, 2011, 6:48:18 PM
*/
package LibSystem;
import javax.swing.JOptionPane;
/**
*
* #author Administrator
*/
public class LibsysMain extends javax.swing.JFrame {
String q;
/** Creates new form LibsysMain */
public LibsysMain()
{
initComponents();
//DBConn dbc = new DBConn();
//q="Select * from users";
//dbc.DoConnect(q);
}
// LibsysMain frame1 = new LibsysMain();
// UserLogin frame2 = new UserLogin(frame1);
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jPanel2 = new javax.swing.JPanel();
jPanel1 = new javax.swing.JPanel();
jPanel3 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jSeparator1 = new javax.swing.JSeparator();
jMenuBar1 = new javax.swing.JMenuBar();
miLogin = new javax.swing.JMenu();
jMenuItem1 = new javax.swing.JMenuItem();
jMenuItem2 = new javax.swing.JMenuItem();
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 100, Short.MAX_VALUE)
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 100, Short.MAX_VALUE)
);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowActivated(java.awt.event.WindowEvent evt) {
formWindowActivated(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 539, Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 328, Short.MAX_VALUE)
);
jLabel1.setText("Status");
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addContainerGap(518, Short.MAX_VALUE))
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 25, Short.MAX_VALUE)
);
jSeparator1.setAlignmentX(0.0F);
jSeparator1.setMinimumSize(new java.awt.Dimension(10, 10));
miLogin.setText("Connect");
miLogin.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
miLoginActionPerformed(evt);
}
});
jMenuItem1.setText("Login");
jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem1ActionPerformed(evt);
}
});
miLogin.add(jMenuItem1);
jMenuItem2.setText("Exit");
jMenuItem2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem2ActionPerformed(evt);
}
});
miLogin.add(jMenuItem2);
jMenuBar1.add(miLogin);
setJMenuBar(jMenuBar1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jSeparator1, javax.swing.GroupLayout.DEFAULT_SIZE, 559, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(4, 4, 4)
.addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
);
pack();
}// </editor-fold>
private void miLoginActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
UserLogin ul = new UserLogin();
ul.setVisible(true);
//SET THE STATUS IF LOGIN IS SUCCESSFULL
if (ul.getStatus() == "pass")
{
jLabel1.setText("Logged In");
}
else
{
jLabel1.setText("Cannot Log in");
}
}
private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
System.exit(0);
}
private void formWindowActivated(java.awt.event.WindowEvent evt) {
// TODO add your handling code here:
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new LibsysMain().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JLabel jLabel1;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JMenuItem jMenuItem1;
private javax.swing.JMenuItem jMenuItem2;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JSeparator jSeparator1;
private javax.swing.JMenu miLogin;
// End of variables declaration
}
I have a couple of suggestions:
For one, don't compare Strings with == as you do here if (ul.getStatus() == "pass") as this checks to see if two variables refer to the same String object (which you don't care about) but rather use either the equals or the equalsIgnoreCase method which checks to see if the two Strings contain the same String data (which you do care about). e.g., if (ul.getStatus().equalsIgnoreCase("pass"))
Be sure to do all of your database queries and whatnot in a thread background to the GUI's thread, the EDT such as can be achieved by using a SwingWorker object. This article will tell you what I said but will give you the details: Concurrency in Swing.
Consider using a single JFrame and modal dialogs to act as dialog windows to the main app. This can be achieved by using JOptionPanes or modal JDialogs, in particular for your UserLogin window.
For this reason, I like to gear my GUI's towards creating JPanels rather than top level windows such as JFrames. This way I can place my GUI/JPanel into any type of window I desire depending on the situation be it a JFrame, a JApplet, a JDialog, a JOptionPane, or even nested into another JPanel. This gives you an amazing amount of flexibilty.
I realize that if you are having a same selection in JComboBox, using up/down arrow key, will not help you to navigate the selection around. How I can avoid this behavior?
See the screenshot below:
alt text http://sites.google.com/site/yanchengcheok/Home/jcombobox.png
public class NewJFrame extends javax.swing.JFrame {
/** Creates new form NewJFrame */
public NewJFrame() {
initComponents();
/* If you are having 3 same strings here. Using, up/down arrow key,
* will not move the selection around.
*/
this.jComboBox1.addItem("Intel");
this.jComboBox1.addItem("Intel");
this.jComboBox1.addItem("Intel");
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jComboBox1 = new javax.swing.JComboBox();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jComboBox1.setEditable(true);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(105, 105, 105)
.addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 158, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(137, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(63, 63, 63)
.addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(217, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new NewJFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JComboBox jComboBox1;
// End of variables declaration
}
Quit cross posting.
The answer has already been given in that posting.
I'm using the Netbeans GUI builder, but it's a little confusing now. How can I add an image to a panel? I think i'm doing it correct, but it's not showing up. I think it should be in the init() method, but netbeans does not allow me to change that part of the code. This is the code I added for the image:
//these four lines I added to add the image
imageIcon = new ImageIcon("login_icon.png");
image = new JLabel(imageIcon);
image.setToolTipText("SGS Security");
topPanel.add(image);
My Class starts here:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* Login.java
*
* Created on Oct 27, 2009, 8:34:15 PM
*/
package sgs;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
public class Login extends javax.swing.JFrame {
JLabel image;
ImageIcon imageIcon;
/** Creates new form Login */
public Login() {
initComponents();
//these four lines I added to add the image
imageIcon = new ImageIcon("login_icon.png");
image = new JLabel(imageIcon);
image.setToolTipText("SGS Security");
topPanel.add(image);
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
topPanel = new javax.swing.JPanel();
userLabel = new javax.swing.JLabel();
passwordLabel = new javax.swing.JLabel();
connectLabel = new javax.swing.JLabel();
forgotPassLabel = new javax.swing.JLabel();
forgotPassCheckBox = new javax.swing.JCheckBox();
cancelButton = new javax.swing.JButton();
okButton = new javax.swing.JButton();
passwordTextField = new javax.swing.JTextField();
userTextField = new javax.swing.JTextField();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setBackground(new java.awt.Color(216, 156, 60));
topPanel.setBackground(new java.awt.Color(28, 90, 198));
javax.swing.GroupLayout topPanelLayout = new javax.swing.GroupLayout(topPanel);
topPanel.setLayout(topPanelLayout);
topPanelLayout.setHorizontalGroup(
topPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 406, Short.MAX_VALUE)
);
topPanelLayout.setVerticalGroup(
topPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 71, Short.MAX_VALUE)
);
userLabel.setText("User name:");
passwordLabel.setText("Password:");
connectLabel.setText("Connect to SGS");
forgotPassLabel.setText("Forgot password");
forgotPassCheckBox.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
forgotPassCheckBoxActionPerformed(evt);
}
});
cancelButton.setText("Cancel");
okButton.setText("OK");
okButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
okButtonActionPerformed(evt);
}
});
userTextField.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
userTextFieldActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(connectLabel)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(passwordLabel)
.addComponent(userLabel)))
.addGap(30, 30, 30)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(userTextField)
.addComponent(passwordTextField)
.addGroup(layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(forgotPassCheckBox)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(forgotPassLabel))
.addGroup(layout.createSequentialGroup()
.addGap(32, 32, 32)
.addComponent(okButton, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(28, 28, 28)
.addComponent(cancelButton, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap())
.addComponent(topPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(topPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(27, 27, 27)
.addComponent(connectLabel)
.addGap(34, 34, 34)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(userLabel)
.addComponent(userTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(passwordLabel)
.addComponent(passwordTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(forgotPassLabel)
.addComponent(forgotPassCheckBox))
.addGap(23, 23, 23)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(okButton, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(cancelButton, javax.swing.GroupLayout.DEFAULT_SIZE, 31, Short.MAX_VALUE))
.addContainerGap())
);
pack();
}// </editor-fold>
private void forgotPassCheckBoxActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void userTextFieldActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Login().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton cancelButton;
private javax.swing.JLabel connectLabel;
private javax.swing.JCheckBox forgotPassCheckBox;
private javax.swing.JLabel forgotPassLabel;
private javax.swing.JButton okButton;
private javax.swing.JLabel passwordLabel;
private javax.swing.JTextField passwordTextField;
private javax.swing.JPanel topPanel;
private javax.swing.JLabel userLabel;
private javax.swing.JTextField userTextField;
// End of variables declaration
}
Ditch the GUI builder and learn how to create GUIs on your own. That way you spend time learning Java instead of learning an IDE. There is probably some GroupLayout property that is not properly set and since GroupLayout was designed to be used by IDEs and not humans I have no idea what the problem might be.
The other possibility is that the IDE can't find your image. Did you add a System.out.println to diplay the image and make sure its not null.
I suggest you read the section from the Swing tutorial on How to Use Icons for a working example that you can download and test to see if it works. Just replace the icons in the tutorial with your icons to make sure they are found.
Edit:
After having a second look at the code I believe my original suggestion is correct. You attempt to add the label to the panel using a single line of code:
topPanel.add(image);
Look at the code generated by the IDE. The add statements are NOT that simple. If you want to manually add a component after the fact then you need read the section from the tutorial on "How to Use Group Layout" to understand the various constraints and methods used.
Or you need to figure out how to do it in the IDE. Thats why I prefer the do it yourself approach. Then you are responsible for the code, not the IDE.
This is one of the weird behaviors in Java (GUIs). You can manually paint the image on a panel.
Here is what I use:
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2= (Graphics2D) g;
if (currentImage != null) {
g2.drawImage(currentImage, null, 0, 0);
}
}
Also you should create a "ImagePanel" component, which is an JPanel that encapsolates the Image.
The middle arguement for drawImage is null, because I do not intend on performing an image operation on it.