While developing our ERP application we need to show a list of
all accounts in a dialog box and upon selecting an account the
base form will be updated. For this we need our custom dialog
box to show the list of accounts. Here i give an example of how
can you show your own custom dialog box and get desired value on
closing the dialog.
At first i like to describe the custom dialog class.
import javax.swing.JDialog;
import javax.swing.JFrame;
/**
* @author ratul
*/
public class CustomDialog extends JDialog {
private javax.swing.JLabel jLabel1;
private javax.swing.JButton jbtOK;
private javax.swing.JTextField jtfInput;
private String inputString = "";
public CustomDialog(JFrame frame, boolean modal) {
super(frame, modal);
initComponents();
pack();
setLocationRelativeTo(frame);
setVisible(true);
}
private void initComponents() {
jbtOK = new javax.swing.JButton();
jtfInput = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jbtOK.setText("OK");
jbtOK.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jbtOKActionPerformed(evt);
}
});
add(jbtOK, new org.netbeans.lib.awtextra.AbsoluteConstraints(160, 190,
-1,-1));
jtfInput.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
jtfInputKeyReleased(evt);
}
});
add(jtfInput, new org.netbeans.lib.awtextra.AbsoluteConstraints(180, 120,
160, 20));
jLabel1.setText("Input some text here:");
add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(70, 120,
-1, -1));
}
private void jbtOKActionPerformed(java.awt.event.ActionEvent evt)
{
this.dispose();
}
private void jtfInputKeyReleased(java.awt.event.KeyEvent evt)
{
inputString += evt.getKeyChar();
}
public String getInputText()
{
return inputString;
}
}
The CustomDialog class extends the JDialog class. The first
parameter of the constructor is the parent frame, second parameter
determines whether the parent frame is disabled or enabled when
the dialog box will be shown.
In the key released action of the text field i populate the inputString.
The dialog box can be closed either by clicking the 'OK' button or close
button of the top right corner. You can get the value of the input
field from the parent from by calling the public String getInputText() method.
Now i describe how to open your custom dialog box:
In the action handler of a button in the parent frame write the following code
CustomDialog cDialog = new CustomDialog(this, true);
this.jtfShowText.setText(cDialog.getInputText());
This will show the dialog box. Now Input some text on the text field
and close the dialog box. The input text will be shown in the text
field of the parent frame.
NB: use null or absolute layout to design the custom dialog box.