poojavb 29 Junior Poster

Hello,

I am stuck with this problem....

I have few folders that contains a filename as registration.txt --- note the folder names are different since as and when a new user will register a folder gets created with its name and then the text file with the details of the user....

I have to read the user id from the text files to the Listbox and then check if any user id has been repeated in the list box....(stuck here)

I have able to read the data but just not able to perform the check on the id...

Please someone help me in this

See the code below what I tried....

Imports System.IO

Public Class Form3
     Dim filename As String
     Private Sub Form3_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
          Dim di As New IO.DirectoryInfo("D:\UserDetails\") '----folder where all the user data is saved
          Dim diar1 As IO.DirectoryInfo() = di.GetDirectories()
          Dim dra As IO.DirectoryInfo
          Dim sr As StreamReader
          Dim line As String
          Dim Fields() As String
          Dim lines As String()
          For Each dra In diar1
               Dim filename1 As FileInfo = New FileInfo(di.ToString + dra.ToString + "\UserRegEntry.txt")
               If filename1.Exists Then
                    filename = di.ToString + dra.ToString + "\UserRegEntry.txt"
                    sr = New StreamReader(filename)
                    line = sr.ReadLine()
                    If line <> String.Empty Then
                         lines = IO.File.ReadAllLines(filename)
                         Fields = line.Split("*") '---* is the delimiter
                         ListBox1.Items.Add(dra.ToString + "----------" + Fields(0)) '---just to read the User ID
                    Else
                         ListBox3.Items.Add(dra.ToString)
                    End If
               Else
                    ListBox2.Items.Add(dra.ToString)
               End If

          Next
          Label1.Text = ListBox1.Items.Count.ToString + " UserRegEntry.txt files found"
          Label2.Text = ListBox2.Items.Count.ToString + …
poojavb 29 Junior Poster

i think it should be this way

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Form1.Personal_InfoTableAdapter.Insert(Me.TextBox1.Text, Me.TextBox2.Text, _
        Me.TextBox3.Text, Me.TextBox4.Text, _
        Me.TextBox5.Text, Me.TextBox6.Text, _
        Me.TextBox7.Text, Me.TextBox8.Text, _
        Me.TextBox9.Text, Me.TextBox10.Text)
        MsgBox("Complete")

Just check once

poojavb 29 Junior Poster

My PC has 3 drives C, D, E...when I insert the removable CD drive it should detect that the drive is the F:...
it may vary for different systems...how can I find which will can be the CD drive...

I had written the following code

Try
    For Each drive In DriveInfo.GetDrives()
        If drive.DriveType = DriveType.CDRom Then
           MessageBox.Show(drive.ToString())
           CD_Targetpath = drive.ToString
        Else
           MessageBox.Show("CD drive does not exist")
           Exit Sub
        End If
    Next
Catch ex As Exception
      MsgBox(ex.Message)
End Try

But as soon as it detects any other drive it exits from the sub

poojavb 29 Junior Poster

Please specify more details....

poojavb 29 Junior Poster

Below example is in MS SQL...same can be done in Access database just change the SQLCommant to OLEDBCommand

First open the connection and then

Dim myCommand As SqlCommand
myCommand = New SqlCommand("CREATE TABLE Tablename (col1 datatype1,col2 datatype2)", myconn) 'where myconn is the connection object
myCommand.ExecuteNonQuery()

'Keep adding the table names as many as u want
myCommand = New SqlCommand("CREATE TABLE Tablename2 (col1 datatype1,col2 datatype2)", myconn) 'where myconn is the connection object
myCommand.ExecuteNonQuery() 

.
.
.
.

CLose the connection

poojavb 29 Junior Poster

Try textbox_TextChangeEvent

Label1.Text=Textbox1.text
poojavb 29 Junior Poster

Create a module in your vb.net project....

create functions for open connection and close connection....

In open connection give the database complete connection and in close connection just close the connection object.....

To call the connections in the form u can call the functions respectively....

find the code below its for MS SQL connection.....

Imports System.Data.SqlClient
Imports System.IO

Module DBConnection
    Public Connection As SqlConnection = New SqlConnection()

    'Open Connection
    Public Function Open_DB_Connection() As String
        Try
            Connection.ConnectionString = "Data Source = LocalHost\;Initial Catalog = Databasename;Integrated Security  = True"
            Connection.Open()
            'Debug.Print("Database connection opened successfully")
            Return "Success"
        Catch ex As Exception
            Return "Fail"
            Exit Function
        End Try
    End Function

    'CLosing Connection
    Public Function Close_DB_Connection() As String
        Try
            Connection.Close()
            'Debug.Print("Database connection closed successfully")
            Return "Success"
        Catch ex As Exception
            Return "Fail"
            Exit Function
        End Try
    End Function

End Module

For calling function on other forms. Suppose on a button click event

 Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
    Open_DB_Connection()
        'ur activity over here like queries
    Close_DB_Connection()

 End Sub
poojavb 29 Junior Poster

Label1 will display the number of days....

          Dim count = 0
          Dim totalDays = (DTLeavePayTo.Value - DTLeavePayFrom.Value).Days
          Dim startDate As Date

          For i = 0 To totalDays
               Dim weekday As DayOfWeek = startDate.AddDays(i).DayOfWeek
               If weekday <> DayOfWeek.Sunday Then
                    count += 1
               End If
          Next
          Label1.Text = count
poojavb 29 Junior Poster

User ID comes first....

"Provider=_______;Data Source=_________;User Id=__________;Password=__________;"

poojavb 29 Junior Poster

To take the back up in Text format on disk

Public Sub WritingTo_Textfiles(ByVal TableName As String)
          Try
               'Open connection here

               Dim line As String

               Dim mysqlCommand As SqlCommand
               mysqlCommand = New SqlCommand("SELECT * FROM " & TableName & " ", myconn)
               Dim myReader As SqlDataReader = mysqlCommand.ExecuteReader

               Dim fileName As String = "D:\" & TableName & ".txt"

               'create a stream object which can write text to a file
               Dim outputStream As StreamWriter = New StreamWriter(fileName)

               'Get all values from the current item on the reader as long as Read() returns true...
               Do While myReader.Read
                    'make an array the length of the available fields
                    Dim values(myReader.FieldCount - 1) As Object
                    'get all the field values
                    myReader.GetValues(values)
                    'write the text version of each value to a comma seperated string
                    line = String.Join("^", values)

                    'write the txt line to the file
                    outputStream.WriteLine(line)
               Loop

               myReader.Close()
               outputStream.Close()

               'close DB connection
               dbstatus = modMSSQL_DB.Close_DB_Connection(myconn)
          Catch ex As Exception
               MsgBox(ex.Message)
          End Try
     End Sub

When u need to take the backup call the function with table name

    WritingTo_Textfiles("Table name")
poojavb 29 Junior Poster

Table name shud not contain space

poojavb 29 Junior Poster

I wont use progress bar but just and loading gif image...
My issue is where I have written cboServer.Text="" or cboServer.Text="Select"...I am getting error at this place...so I dont know what delegat shud be used in this case....
Error is - Cross-thread operation not valid: Control 'cboServer' accessed from a thread other than the thread it was created on.

poojavb 29 Junior Poster

I get the following error

Cross-thread operation not valid: Control 'cboServer' accessed from a thread other than the thread it was created on.

Need help to work on delegate

poojavb 29 Junior Poster

I tried to work with the below tutorial but I am not aware as to how to use the delegate for my radio button and combo box....

Click Here

poojavb 29 Junior Poster

Need help while working with timer....

I am trying to do the database restoring part....

When the user clicks on the restore database button the progress bar shud be shown and as soon as the restoring is completed the progress bar shud stop and display success msg...

Right now I tried without timer using progress image but it is not working as expected...
the image shows just when the success msg is displayed....

below is my code

Imports Microsoft.Win32
Imports Microsoft.SqlServer.Management.Smo
Imports System.Data.SqlClient
Imports System.IO

Public Class frmDatabaseRestore

     Private Sub frmDatabaseRestore_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load

          lblAlert.Visible = False
          lblAlert.Image = My.Resources.Loading1 'my processing image

          txtDatabase.Text = "Databasename"
          cboServer.Text = "Servername"
     End Sub

     Private Sub btnClose_Click(sender As System.Object, e As System.EventArgs) Handles btnClose.Click
          If MessageBox.Show("Restoring Database Aborted, your system will shutdown", "Restore Database Aborted", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) = Windows.Forms.DialogResult.Yes Then
               Application.Exit()
          End If
     End Sub

     Private Sub btnRestore_Click(sender As System.Object, e As System.EventArgs) Handles btnRestore.Click
          If optBackupFile.Checked = False And optTextFile.Checked = False Then
               MessageBox.Show("Select any one option")
          ElseIf optBackupFile.Checked = True Then
               If cboServer.Text = "" Or cboServer.Text = "Select" Then
                    MessageBox.Show("Server Name is Mandatory")
               Else
                    lblAlert.Visible = True 'display the processing image
                    Try
                         Dim MySQL_Connection As SqlConnection = New SqlConnection()
                         MySQL_Connection.ConnectionString = "Data Source = " & cboServer.Text & ";Integrated Security  = True"
                         MySQL_Connection.Open()
                         Dim myCommand As SqlCommand
                         myCommand = New SqlCommand(" RESTORE DATABASE [Databasename] FROM  DISK = N'D:\Databasename_full.bak'", MySQL_Connection)
                         myCommand.ExecuteNonQuery()
                         MySQL_Connection.Close()
                         lblAlert.Visible = False
                         MessageBox.Show("Database Restored Successfully")
                         frmUserLogin.Show()
                         Me.Close()
                    Catch ex As Exception
                         WriteLog(New …
poojavb 29 Junior Poster

Add a try catch block around ur sql statements and the insert sql is not correct

 cmd.CommandText = "INSERT INTO table([Name], [Comment], [emailaddress]) VALUES('" + txtname + "','" + txtcomment+ "','" + txtemail + "')"
poojavb 29 Junior Poster

@Bar-I - Yes it is working...make sure u write the correct form and label names

poojavb 29 Junior Poster

The answer will be 2 only since subtracting higher to lower will give the result...if u want all the days inclusive just add 1 to ur result...

poojavb 29 Junior Poster

ur pie variable sets a new form every time so the value in the old form1 does not get updated

Comment the statement where u have declared the pie variable and just call the form name where u are declaring the variable to label
Like below

 'Dim pie As New Form1
          If ListBox1.SelectedIndex = 0 Then
               label1.text = 50
               Form1.Label1.Text = Label1.Text
               Me.close()
          ElseIf Listbox1.SelectedIndex = 1 Then
               label1.text = 75
               Form1.Label1.Text = Label1.Text
               Me.close()
          ElseIf ListBox1.selectedIndex = 2 Then
               label1.text = 100
               Form1.Label1.Text = Label1.Text
               Me.close()
          End If
poojavb 29 Junior Poster

u need to format ur way of displaying the records to display....
u can make use of the lines and design it in a table format...

poojavb 29 Junior Poster

Date variable is a keyword so try giving some other name in ur database

poojavb 29 Junior Poster

Try this

import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.List;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
// <applet code="AppletInterfaz" width="300" height="200"> </applet>
public class AppletInterfaz extends Applet implements ItemListener {
    List colors;
    public AppletInterfaz() {
        colors = new List(4);
        colors.add("Aqua");
        colors.add("Black");
        colors.add("Blue");
        colors.add("Fuchsia");
        colors.add("Gray");
        colors.add("Green");
        colors.add("Lime");
        colors.add("Maroon");
        colors.add("Navy");
        colors.add("Olive");
        colors.add("Purple");
        colors.add("Red");
        colors.add("Silver");
        colors.add("Teal");
        colors.add("White");
        colors.add("Yellow");
        add(colors);
        //colors.setSelectedIndex(0);
        colors.addItemListener(this);
    }
    public void itemStateChanged(ItemEvent ie) {
        repaint();
    }
    public void paint(Graphics g) {
        //colors.setSelectedIndex(colors.getSelectedIndex());
        int choice;
if (colors.getSelectedIndex()<= -1 )
{
    choice = colors.getSelectedIndex()+1;
}
else
{
    choice = colors.getSelectedIndex();
}
        System.out.println(choice);
        int red, green, blue;
        int colorMix[][] = { { 0, 255, 255 }, { 0, 0, 0 }, { 0, 0, 255 },
                { 255, 0, 255 }, { 128, 128, 128 }, { 0, 128, 0 },
                { 0, 255, 0 }, { 128, 0, 0 }, { 0, 0, 128 }, { 128, 128, 0 },
                { 128, 0, 128 }, { 255, 0, 0 }, { 192, 192, 192 },
                { 0, 128, 128 }, { 255, 255, 255 }, { 255, 255, 0 } };
        red = colorMix[choice][0];
        green = colorMix[choice][1];
        blue = colorMix[choice][2];
        Color fondo = new Color(red, green, blue);
        g.setColor(fondo);
        g.drawRect(0, 0, 300, 200);
        g.fillRect(0, 0, 300, 200);
    }
}

Actually ur choice variable gets value as -1 so it shows the error of OutofIndex....since no item is selected in the List...
bydefault select some item in the List and then assign the value to choice variable....

Kronolynx commented: thanks for the help +0
poojavb 29 Junior Poster

First u have to validate all the conditions and if all the conditions are passed then save to database....

Like

if emailvalidation =  false or other things like name and so on then 
    do this
else 
    save to database
poojavb 29 Junior Poster

UBound is not having one opening parenthesis

poojavb 29 Junior Poster

u need a table which will have the userid, logintime, logouttime columns...

whenever the user logs into the application save the system date time into the database with userid as the criteria
when the user logs off or directly closes the application then prompt with a yes / no msg whether he wants to log out...
if he selects yes then save the logout time in the database with the same userid as criteria

poojavb 29 Junior Poster

Every time u delete a record from the datagridview (database) make sure u load the datagridview again completely...and if suppose any data is returned then enable ur delete button else disable...

u can add the enabling and disabling of delete button in all ur control events wherever u r dealing with datagridview (database)

something like this:
this code is written in delete button click event

Dim i As Integer
          Dim ID As String
          i = DataGridView1.CurrentRow.Index
          ID = DataGridView1.Item(0, i).Value
          MsgBox("ID: " & ID.ToString)

          Dim myCommand1 As SqlCommand

          myCommand1 = New SqlCommand("DELETE FROM  Names Where ID = '" & ID & "'", Connection)
          myCommand1.ExecuteNonQuery()

          Try
               Dim myCommand As SqlCommand
               myCommand = New SqlCommand("SELECT * FROM Names", Connection)
               Dim dt As New DataTable
               dt.Load(myCommand.ExecuteReader)
               MsgBox("dt value: " & dt.Rows.Count.ToString)
               If dt.Rows.Count <= 0 Then
                    With DataGridView1
                         .DataSource = Nothing
                    End With
                    btnDelete.Enabled = False
               Else
                    With DataGridView1
                         .AutoGenerateColumns = True
                         .DataSource = dt
                    End With
                    btnDelete.Enabled = True
               End If
          Catch ex As Exception
               MsgBox(ex.Message)
          End Try
poojavb 29 Junior Poster
               Dim strSQL As String = "SELECT distinct deptid,deptname FROM tablename"
               Dim da As New OleDbDataAdapter(strSQL, Connection)
               Dim ds As New DataSet
               da.Fill(ds, "tablename")
               With combobox1
                    .DataSource = ds.Tables("tablename")
                    .DisplayMember = "deptname"
                    .ValueMember = "deptid"
               End With
poojavb 29 Junior Poster

Drop a viewer in ur form...in ur forms load event try the below code

Imports CrystalDecisions.CrystalReports.Engine
Imports CrystalDecisions.Shared

Public Class rptFinance
     Dim oRead As System.IO.StreamReader

 Private Sub rptFinance_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
      Dim crtableLogoninfos As New TableLogOnInfos
      Dim crtableLogoninfo As New TableLogOnInfo
      Dim crConnectionInfo As New ConnectionInfo
      Dim CrTables As Tables
      Dim CrTable As Table

      Dim cryRpt As New ReportDocument
      cryRpt.Load(Application.StartupPath & "\Reports\CrystalReport1.rpt") 'Path where ur report is placed

      With crConnectionInfo
           .ServerName = "path wherer ur access database is present"
           .DatabaseName = "path wherer ur access database is present"
           .UserID = ""
           .Password = ""
      End With
      CrTables = cryRpt.Database.Tables
      For Each CrTable In CrTables
           crtableLogoninfo = CrTable.LogOnInfo
           crtableLogoninfo.ConnectionInfo = crConnectionInfo
           CrTable.ApplyLogOnInfo(crtableLogoninfo)
      Next

      crvFinance.ReportSource = cryRpt
      crvFinance.Refresh()

      'crvFinance is the report viewer name
poojavb 29 Junior Poster
 MessageBox.Show("WELCOME TO MAGIC BEANS INC. ^_^ :* :)) :p", Me.Text, MessageBoxButtons.OK, MessageBoxIcon.Information)
          Dim button As DialogResult
          button = MessageBox.Show("Would you like to become a member? (note: membership fee Php 500, non-member 250 for)", Me.Text, MessageBoxButtons.YesNo, MessageBoxIcon.Information)
          If button = Windows.Forms.DialogResult.Yes Then
               Me.Show()
               'Me.Dispose(False)
          ElseIf button = Windows.Forms.DialogResult.No Then
               Form2.Show()
               Me.Dispose(False)
          End If
gelmi commented: haha laughing at myself right now. Thanks anyway :) +0
poojavb 29 Junior Poster

I have created a class as below

public class MyTextField extends JTextField implements KeyListener
{
int size;
    public MyTextField(int size)
    {
        super(15);
        this.size=size;
        addKeyListener(this);
    }
    public void keyTyped(KeyEvent e)
    {   
        char ch=e.getKeyChar();     
        String specialchar="!@#$%^&*()~?>'<:{}|+_/\".,;'][=-` \\";

        if (specialchar.indexOf(ch)>-1)
        {
            JOptionPane.showMessageDialog(null, "SPECIAL CHARACTER IS NOT ALLOWED","",JOptionPane.WARNING_MESSAGE);
            e.setKeyChar('\0');
        }
        if(getText().length()>size-1)
        e.setKeyChar('\0');

    }   
    public void keyPressed(KeyEvent e){}
    public void keyReleased(KeyEvent e){}
}

And then called the textfield as follows

MyTextField txtPatientID =new MyTextField(15);
poojavb 29 Junior Poster

Hello Friends,

I want to set the length of the textfield in java...

Please check my below code....it works finely if I press the keys one by one slowly...
But suppose if I press any key for a longer time the actual length exceeds and so the validation is not done correctly...

Can anyone help me to set the length??

public class TextValidation extends KeyAdapter
    {
        public void keyReleased(KeyEvent key)
        {
            Object txt=key.getSource();
            if(txt==txtPatientId)
            {
                char ch=key.getKeyChar();       
                String specialchar="!@#$%^&*()~?>'<:{}|+_/\".,;'][=-` \\";
                if (txtPatientId.getText().trim().length() <= 10)
                {
                    if (specialchar.indexOf(ch)>-1)
                    {
                        JOptionPane.showMessageDialog(null, "SPECIAL CHARACTER IS NOT ALLOWED","Title",JOptionPane.WARNING_MESSAGE);
                        txtPatientId.setText(txtPatientId.getText().substring(0, txtPatientId.getText().length()-1));
                    }
                }
                else
                {
                    JOptionPane.showMessageDialog(null, "MAXIMUM 10 CHARACTERS","Title",JOptionPane.WARNING_MESSAGE);
                    txtPatientId.setText(txtPatientId.getText().substring(0, txtPatientId.getText().length()-1));       
                }
            }
        }
    }
poojavb 29 Junior Poster

So u need to show some id based on the selection of ur textbox to some other text box....
u need to add a select query based on ur auto complete text box in the text change event...

like

select * from tablename where colname='"+Autotextbox.Text+"'

later u need to declare a reader and assign the reader value to the other textbox

poojavb 29 Junior Poster

U want to change the datatype in database right??? which database are u using???

poojavb 29 Junior Poster

Just a brief idea...
calculate the length of the array data....check if the last data in the length is , and then try to remove it....

else show some part of ur code...

poojavb 29 Junior Poster

Try something like this

Private Sub FindMySpecificString(ByVal searchString As String)
   ' Ensure we have a proper string to search for.'
   If searchString <> String.Empty Then

       Dim index As Integer = listBox1.FindStringExact(searchString)
       ' Determine if a valid index is returned. Select the item if it is valid.'
       If index <> ListBox.NoMatches Then
          ListBox1.SetSelected(index, True)
          MsgBox("Got it")
       Else
          MsgBox("The search string did not find any items in the ListBox")
          TextBox4.Text = "" 'the textbox u require
       End If
   Else
       MsgBox("Empty")
   End If
End Sub

call this function in the button click event

poojavb 29 Junior Poster

Debug ur code and check the flow of ur code...u will come to know where u are facing problem....by clicking F8

poojavb 29 Junior Poster

u can give the command SET NOEXEC ON and then the sql query...it will just compile

poojavb 29 Junior Poster

in which event are u writing this code???
below code works...is this what u want....type in textbox3 and get the same thing in textbox4

Private Sub TextBox3_TextChanged(sender As System.Object, e As System.EventArgs) Handles TextBox3.TextChanged
          TextBox4.Text = TextBox3.Text
     End Sub
poojavb 29 Junior Poster

U have two variables

Dim total as Integer and it wont be accessible
Public tolal as Double is accessible

but in your code

 Public tolal As Double ' tolal is public
 Form18.total = Module1.dailytotalamount ' total is not public....

u have declared tolal as public but not total

Begginnerdev commented: What I figured! Very nice, pooja! +6
poojavb 29 Junior Poster

U need to give a try before posting....

will give some way
restrict ur text box to number and max length as 3
then when clicking on the button....
give ur if conditions....before that just convert ur string to number and then display

poojavb 29 Junior Poster
Dim bill As integer=textbox14.text
Module1.billno = bill
Form18.txtbillno = Module1.billno

txtbillno is a textbox so u are getting the error....
u need to add .Text after the textbox object

Form18.txtbillno.Text = Module1.billno
poojavb 29 Junior Poster

Could u please show ur code???

poojavb 29 Junior Poster

Check if this will be fine for u

Dim cmd As New OleDbCommand("SELECT colname FROM Tablename", Connection)
Dim reader As OleDbDataReader = cmd.ExecuteReader
combobox1.Items.Clear()
While reader.Read
      combobox1.Items.Add(reader("colname"))
End While
reader.close()
poojavb 29 Junior Poster

IsDigit code will allow to enter everything apart from digits....

  'accepts only alphabets
          If (Microsoft.VisualBasic.Asc(e.KeyChar) < 65) Or (Microsoft.VisualBasic.Asc(e.KeyChar) > 90) _
          And (Microsoft.VisualBasic.Asc(e.KeyChar) < 97) Or (Microsoft.VisualBasic.Asc(e.KeyChar) > 122) Then
               e.Handled = True
          End If
          If (Microsoft.VisualBasic.Asc(e.KeyChar) = 8) Then
               e.Handled = False
          End If
Reverend Jim commented: unnecessarily complicated and has redundant code +0
poojavb 29 Junior Poster
 Private Sub TextBox1_KeyPress(sender As Object, e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
     'accepts only numbers
     If (Microsoft.VisualBasic.Asc(e.KeyChar) < 48) Or (Microsoft.VisualBasic.Asc(e.KeyChar) > 57) Then
         e.Handled = True
     End If
     If (Microsoft.VisualBasic.Asc(e.KeyChar) = 8) Then
         e.Handled = False
     End If
 End Sub
Reverend Jim commented: does the opposite of what was asked -2
poojavb 29 Junior Poster

GregorianCalendar

poojavb 29 Junior Poster

Is there a way to set Max date in Java for the calendar control or restrict the user from selecting the future dates?

poojavb 29 Junior Poster
public class ButtonHandler implements ActionListener
 {
   public void actionPerformed(ActionEvent ae)
    {
      Object button =ae.getSource();
      if(button==Apply)
       {
             newColor = ColorChooser.getColor();
          setVisible(false);
       }
      if(button==Cancel)
      {
        setVisible(false);
       }
     }
  }//event
poojavb 29 Junior Poster

Hello,

I want to implement Change Listener in the Action Listener of a Button

I have a color graph chooser and 2 buttons...Apply and Cancel

to select the color of the color chooser i have implemented the Change Listener
but I want the change listener to act on the Apply button click...

Since the listener which I have written is not in the apply button it takes place even when I click on cancel button....

code for change listener

final JColorChooser ColorChooser = new JColorChooser(Color.black);
   ColorChooser.getSelectionModel().addChangeListener(new ChangeListener()
   {
     public void stateChanged(ChangeEvent e)
      {
         newColor = ColorChooser.getColor();
      }
     }
   );

code for action listener

public class ButtonHandler implements ActionListener
 {
   public void actionPerformed(ActionEvent ae)
    {
      Object button =ae.getSource();
      if(button==Apply)
       {
          setVisible(false);
       }
      if(button==Cancel)
      {
        setVisible(false);
       }
     }
  }//event
poojavb 29 Junior Poster

the attachments are not visible...could u please attach the images again....not in link format...