JButton.setEnabled(false) - clickable

Hello,
i'm writing a Swing Application, therefor i'm using javax.swing.JButton
. At awt i could use button.setEnabled(false) and so this certain Button is not clickable, events will not be recieved, and his Layout is modified to "disabled". But with JButtons i'm able to recieve events from them, even if they're disabled? So how to disable, and then at some time enable them?
(Sorry, I'm new to Swing)
Thank you.
Best regards.
Nico

Hello,
i'm a bit confused. I'm using sun studio 4 for giu editing. So i set in the properties of the button the "enabled" property to false. So the generated code looks like:
private javax.swing.JButton disconnect_button;
disconnect_button = new javax.swing.JButton();
disconnect_button.setFont(new java.awt.Font("MS Sans Serif", 1, 11));
disconnect_button.setText("disconnect");
disconnect_button.setEnabled(false);
disconnect_button.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseReleased(java.awt.event.MouseEvent evt) {
disconnect_buttonMouseReleased(evt);
But what happens is: the button seems to be diabled, so he looks like. But i am able to recieve events from the button. So when i click on the button (mouse released event), the method "disconnect_buttonMouseReleased(evt)" is executed.
Thanks,
Nico

Similar Messages

  • How to make A JButton not look disabled when it is  setEnabled(false);

    how do i make a jbutton not look disabled when i setEnabled(false) because when u disabled abutton it changes and takes away the frame of the button it self..is there a way to make it make a sound when its disabled and not take the frame away...example look at windows calculator when u have an answer for example 2 + 2 when the answer is displayed if u try to click the backspacebutton at this point it makes a sound..is this possible in java thanks

    Why did you repost this question??????
    You where given an answer in the other posting. You have not explained why the solution won't work and you haven't provided any further information about your question.
    You also haven't listened to the other advice, you just reposted the question word for word.

  • JRadioButton setEnable(false) not refreshing correctly

    I have a JFrame class that implements customerConfigurationPanel with a ComboBox with 2 Radio Buttons in a button group. I have created a CustomerConfiguration class that represents the cutomerConfigurationPanel. The JFrame class is an Observer of the CustomerConfiguration class. Here is where it gets tricky, I use the JComboBox to set the CustomerConfiguration class and when I do a setVar() it notifies the JFrame class that it has been updated. At this point I enable or disable the RadioButton based on the CustomerConfiguration class. The issue is that the RadioButtons do not grey out correctly or in any pattern that I can tell. I have tried repaint on the JFrame and the panel, I have tried validate(), invalidate(), and revalidate() to stop and start the panel while I am updating the JRadio Buttons. I need to stop the JFrame or Panel, set the state of the JRadio Buttons, and start the panel again. I have a lot of code in place so its not very easy to put an example in place but Ill start working on it to give an example.
    The problem in its most basic form is that I have a JRadio Button in a button group that doenst grey out correctly.

    Here is a sample of the code I am using: I have a button that may or may not be setSelected in a previous state. So I want to clear the button state and reset it to the new state. In this example I have a radioButton group Truck/Trailer and I want to clear both buttons, set Trailer so it is not selected and then not enabled and then set Enable Truck and select truck. I belive the code is correct but the behavior is not. I have this same code just 10 lines later in my program and it works everytime. I think its a timing issue with repainting of the container somehow. Also if I use isVisible() instead of setEnabled() it works everytime.
    jrbTrailer.setEnabled(true);
    jrbTrailer.setSelected(false);
    jrbTrailer.setEnabled(false);
    jrbTruck.setSelected(true);
    // None of these work
    //jrbTrailer.repaint()
    //jrbTrailer.revalidate()
    //jrbTrailer.validate()

  • JButton setEnabled method is not refreshing state

    Hi there, I have a problem, I'm putting a few JButtons into a JPanel, so that I can display the options that an user has.
    I validate the user options so I can put the set enabled method with argument true or false.
    The app show a login JFrame and then the screen that has these options, that is like the main form.
    The fact is that is try to login again via a change user option located on the main form,, then the login JFrame is displayed again and eventually the main form.
    When I try enable the user options again, the method setEnabled of the JButton doesn´t seem to be working, it just doesn't change the state, I have the debugged it and it reaches in both cases the setEnabled line (((JButton) jpnlSistemas1.getComponents()).setEnabled(true);)
            Sistema sistema;
            JButton boton;
            for (int i = 0; i < jpnlSistemas1.getComponents().length; i++) {
                if (jpnlSistemas1.getComponents() instanceof JButton) {
    boton = (JButton) jpnlSistemas1.getComponents()[i];
    Iterator iteradorSistemas = global.getUsuario().getSistemas().iterator();
    while (iteradorSistemas.hasNext()) {
    sistema = (Sistema) iteradorSistemas.next();
    if (((JButton) jpnlSistemas1.getComponents()[i]).getName().equals(sistema.getIdSistema())) {
    ((JButton) jpnlSistemas1.getComponents()[i]).setEnabled(true);
    any ideas about what could it be?
    thanks.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    I'd do it differently. I'd have whatever class that holds the JButtons have a enableButton() method, and then simply call that method rather than searching for buttons among all the components of a window.

  • SwingWorker problem!!! How can I run it 2 times or more?

    Hello!!
    I am new in Java. I use the following code:
    SwingWorker SWorker = new SwingWorker<String, Void>()
       public String doInBackground() {
       return CargarInformacion();
    public void done() {
       try {
          JTextAreaReport.append(get());
       } catch(InterruptedException ie)
          System.out.println(ie.toString());
       } catch(java.util.concurrent.ExecutionException ee)
          System.out.println(ee.toString());
    private String CargarInformacion()
       try
          in = new BufferedReader(new FileReader(file));
          <read file...>
       return StrMessage;
    }The problem is that when this code runs for the first time it works perfect!!! but I need to use it several times with other file names. In the java docs I found the following text:
    "SwingWorker is only designed to be executed once. Executing a SwingWorker more than once will not result in invoking the doInBackground method twice."
    How can I resolve this?
    thank's.
    David.
    Edited by: davigre on Oct 1, 2008 8:42 PM

    I am trying to do this as well. For some reason, it is not working for me. I have a class "Task" that extends Swingworker with a doInBackground() and done(). Each time I click "submit" I create a new "Task" and call task.execute(). But the second time around, the doInBackground() never gets called. Can someone help me out? Here are a couple of the relevant functions.
    Thanks
    Mike
    Here is where the thread is started:
    public void readDataLogger() {
            jButton.setEnabled(false);
            jBox.setEnabled(false);
            String deleteData = JOptionPane.showInputDialog("Would you like to erase all the data off this logger after it is downloaded? (y/n)");
            if (deleteData == null || deleteData.equalsIgnoreCase("n") || deleteData.equalsIgnoreCase("no")) {
                // user clicked cancel or typed n/no
            } else if (deleteData.equalsIgnoreCase("y") || deleteData.equalsIgnoreCase("yes")) {
                erase = true;
            routeNum.setText("Route Num: " + (String) jBox.getSelectedItem());
            waiting.setText("Please wait a moment...");
            Thread stepper = new BarThread(progressBar);
            stepper.start();
            this.add(progressBar);
            Task task = new Task();
            task.execute();
        }And the thread classes:
    class BarThread extends Thread {
            JProgressBar progressBar;
            public BarThread(JProgressBar bar) {
                progressBar = bar;
            public void run() {
        class Task extends SwingWorker<Void, Void>{
            boolean wrongPort;
            long timeGoneBy = 0;
             * Main task. Executed in background thread.
            public Void doInBackground() {
                wrongPort = true;
                try {
                    logWriter.append("starting new thread");
                    logWriter.flush();
                } catch (IOException ex) {
                    Logger.getLogger(DDAGPS.class.getName()).log(Level.SEVERE, null, ex);
                Runtime rt = Runtime.getRuntime();
                File propertiesFile = new File("port.properties");
                Properties properties = new Properties();
                String command = "";
                int portTry = 0;
                boolean propPort = false;
                if (propertiesFile.exists()) {
                    try {
                        properties.load(new FileInputStream("port.properties"));
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    if (properties.containsKey("port")) {
                        portTry = Integer.parseInt((String) properties.get("port"));
                        try {
                            logWriter.append("port from properties: " + portTry + "\r\n");
                            logWriter.flush();
                        } catch (IOException ex) {
                            ex.printStackTrace();
                        command = baseDir + "GPSBabel/gpsbabel.exe -p \"\" -w -t -i mtk";
                        if (erase) {
                            command += ",erase";
                        command += " -f com" + portTry + ": -o gpx,gpxver=1.0 -F " + baseDir + "Temp/" + jBox.getSelectedItem() + "-" + numbLoggers + ".gpx";
                        launching.setText("trying it on COM" + portTry);
                        try {
                            logWriter.append("command using port from props: " + command + "\r\n");
                            logWriter.flush();
                            Process p = rt.exec(command);
                            File bin = new File(baseDir + "data.bin");
                            boolean fileExists = false;
                            double time = 0.0;
                            while (!procDone(p) && !fileExists && time < 10) {
                                logWriter.append("waiting and looking for bin file: " + time + "\r\n");
                                logWriter.flush();
                                Thread.sleep(200);
                                time += .2;
                                if (bin.exists() && bin.length() > 0) {
                                    wrongPort = false;
                                    launching.setText("it worked on COM" + portTry + ", building data file...");
                                    propPort = true;
                                    fileExists = true;
                            if (!fileExists) {
                                logWriter.append("it did not work using the port from the properties file");
                                logWriter.flush();
                        } catch (IOException ex) {
                            try {
                                logWriter.append("error: " + ex.getMessage() + " trying to use GPSBabel with port from properties file\r\n");
                                logWriter.flush();
                            } catch (IOException ex1) {
                                ex1.printStackTrace();
                        } catch (InterruptedException ex) {
                            ex.printStackTrace();
                //if (!propPort) {
                    try {
                        Process p = rt.exec("mode.com");
                        String s = null;
                        ArrayList<Integer> ports = new ArrayList<Integer>();
                        BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
                        logWriter.append("Here is the standard output of the command:\r\n");
                        logWriter.flush();
                        int lines = 0;
                        int po = -1;
                        while ((s = stdInput.readLine()) != null) {
                            String port = "";
                            logWriter.append("line: " + s + "\r\n");
                            logWriter.flush();
                            if (lines > 0) {
                                if (s.contains("Baud") && s.contains("115200")) {
                                    logWriter.append("adding port: " + po + "\r\n");
                                    logWriter.flush();
                                    ports.add(po);
                                lines--;
                            if (s.startsWith("Status for device COM")) {
                                port = s.substring(s.indexOf("M") + 1, s.indexOf(":"));
                                po = Integer.parseInt(port);
                                lines = 2;
                        stdInput.close();
                        portTry = 0;
                        logWriter.append("wrongPort: " + wrongPort);
                        logWriter.flush();
                        while (portTry < ports.size() && wrongPort) {
                            command = baseDir + "GPSBabel/gpsbabel.exe -p \"\" -w -t -i mtk";
                            if (erase) {
                                command += ",erase";
                            command += " -f com";
                            command += ports.get(portTry) + ": -o gpx,gpxver=1.0 -F " + baseDir + "Temp/" + jBox.getSelectedItem() + "-" + numbLoggers + ".gpx";
                            System.out.println("command: " + command);
                            Long currentTime1 = System.currentTimeMillis();
                            launching.setText("trying it on COM" + ports.get(portTry));
                            logWriter.append("command: " + command + "\r\n");
                            logWriter.flush();
                            p = rt.exec(command);
                            boolean fileExists = false;
                            while (!procDone(p) && wrongPort && !fileExists) {
                                Thread.sleep(100);
                                long currentTime2 = System.currentTimeMillis();
                                timeGoneBy = (currentTime2 - currentTime1);
                                Long seconds = timeGoneBy / 1000;
                                int hundreds = (int) (timeGoneBy / 100) % 10;
                                timer.setText(seconds + "." + hundreds + " s");
                                logWriter.append("still working: " + seconds + " seconds\r\n");
                                logWriter.flush();
                                File bin = new File(baseDir + "data.bin");
                                if (!(bin.exists() && bin.length() > 0)) {
                                    wrongPort = true;
                                } else {
                                    logWriter.append("bin exists: " + bin.exists() + "\r\n");
                                    logWriter.flush();
                                    //File port = new File(baseDir + "port.properties");
                                    //FileWriter fw = new FileWriter(port);
                                    //fw.append("port=" + String.valueOf((ports.get(portTry))));
                                    //fw.flush();
                                    //fw.close();
                                    launching.setText("it worked on COM" + ports.get(portTry) + ", building data file...");
                                    wrongPort = false;
                                if (seconds > 15) {
                                    takeAWhile.setText("This could take a minute or two depending on how much data you have to pull off.");
                                File file = new File(baseDir + "Temp/" + jBox.getSelectedItem() + "-" + numbLoggers + ".gpx");
                                if (file.exists()) {
                                    fileExists = true;
                                logWriter.append("wrongPort: " + wrongPort + "\r\n");
                                logWriter.flush();
                                logWriter.append("fileExists: " + fileExists + "\r\n");
                                logWriter.flush();
                                logWriter.append("procDone: " + procDone(p) + "\r\n");
                                logWriter.flush();
                            portTry++;
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    } catch (InterruptedException ex) {
                        ex.printStackTrace();
                return null;
            private boolean procDone(Process p) {
                try {
                    int v = p.exitValue();
                    return true;
                } catch (IllegalThreadStateException e) {
                    return false;
             * Executed in event dispatch thread
            public void done() {
                try {
                    logWriter.append("in done!\r\n");
                    logWriter.append("wrongPort: " + wrongPort);
                    logWriter.flush();
                } catch (IOException ex) {
                    Logger.getLogger(DDAGPS.class.getName()).log(Level.SEVERE, null, ex);
                launching.setText("");
                ddagps.repaint();
                File bin = new File(baseDir + "data.bin");
                if (wrongPort) {
                    //wrongPort = false;
                    String message = "Something went wrong.  Please make sure the device is turned on and replug the " +
                            "device into the USB port and hit OK.";
                    int response = redo(message);
                    if (response == 1) {
                        System.exit(0);
                    } else {
                        timer.setText("");
                        readDataLogger();
                } else {
                    try {
                        logWriter.append("i am in done's else!\r\n");
                        logWriter.flush();
                    } catch (IOException ex) {
                        Logger.getLogger(DDAGPS.class.getName()).log(Level.SEVERE, null, ex);
                    launching.setText("creating gpx file");
                    ddagps.repaint();
                    File file = new File(baseDir + "Temp/" + jBox.getSelectedItem() + "-" + numbLoggers + ".gpx");
                    while (!file.exists()) {
                        try {
                            Thread.sleep(100);
                        } catch (InterruptedException ex) {
                            ex.printStackTrace();
                    //System.out.println("f1 does not exist");
                    numbLoggers++;
                    ddagps.remove(progressBar);
                    takeAWhile.setText("");
                    Toolkit.getDefaultToolkit().beep();
                    jBox.setEnabled(true);
                    jButton.setEnabled(true);
                    waiting.setText("Done!\n");
                    String moreDevices = JOptionPane.showInputDialog("Do you have any more devices to enter in? (y/n)");
                    if (moreDevices == null) {
                        // user clicked cancel
                    } else if (moreDevices.equalsIgnoreCase("y") || moreDevices.equalsIgnoreCase("yes")) {
                        JOptionPane.showMessageDialog(null, "Hit OK when the next logger is plugged in.");
                        timer.setText("");
                        bin.delete();
                        readDataLogger();
                    } else if (moreDevices.equalsIgnoreCase("n") || moreDevices.equalsIgnoreCase("no")) {
                        launching.setText("Merging files...");
                        ddagps.repaint();
                        int numb = numbLoggers - 1;
                        File f = new File(baseDir + "Temp/" + jBox.getSelectedItem() + "-" + numb + ".gpx");
                        while (!f.exists()) {
                            try {
                                Thread.sleep(200);
                            } catch (InterruptedException ex) {
                                ex.printStackTrace();
                        //System.out.println("f2 does not exist");
                        //System.out.println("found " + f.getName());
                        ParseAndCombineKMLs pack = new ParseAndCombineKMLs(numbLoggers, jBox.getSelectedItem());
                        if (pack.parseAndCombine()) {
                            f = new File(baseDir + "Output/" + jBox.getSelectedItem() + ".kml");
                            while (!f.exists()) {
                                try {
                                    Thread.sleep(100);
                                } catch (InterruptedException ex) {
                                    ex.printStackTrace();
                            //System.out.println("f3 does not exist");
                            Uploader up = new Uploader(upload);
                            if (up.pushFile(baseDir + "Output/" + jBox.getSelectedItem() + ".kml")) {
                                launching.setText("Upload Successful");
                                Runtime rt = Runtime.getRuntime();
                                try {
                                    rt.exec("C:/Program Files/Mozilla Firefox/firefox.exe " + view + "?route=" + jBox.getSelectedItem());
                                    bin = new File(baseDir + "data.bin");
                                    bin.delete();
                                    launching.setText("Launching browswer with your data...");
                                } catch (IOException ex) {
                                    ex.printStackTrace();
                        try {
                            logWriter.close();
                        } catch (IOException ex) {
                            ex.printStackTrace();
        }Edited by: dmikester1 on Nov 5, 2008 8:50 AM

  • Decompiled Sun's Active X Bridge Bean Examples

    The examples you can download, JCalendarPanel and JellyBean, I unzipped the jar files and then ran each class file through a decompiler which produced some decent code to look at.
    It at least gave me one perspective to see what was going on...on the Java side of things.
    See one of the main classes for calendar below...
    package wkw.beans.ui;
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.beans.PropertyChangeListener;
    import java.beans.PropertyChangeSupport;
    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    import java.util.*;
    import javax.swing.*;
    // Referenced classes of package wkw.beans.ui:
    //            ArrowIcon
    public class JCalendarPanel extends JPanel
        implements ActionListener
        private static final int BUTTON_COUNT = 42;
        private static final int LABEL_COUNT = 7;
        private transient JButton days[];
        private transient JLabel dayOfWeekLabel[];
        private transient JButton selectedButton;
        private transient JComboBox monthChoice;
        private transient JLabel yearLabel;
        private transient int selectedMonth;
        private transient int selectedYear;
        private transient int selectedDay;
        private transient int cellHeight;
        private transient int cellWidth;
        private transient int sundayColumnIndex;
        private transient JPanel headerPanel;
        private transient JPanel calendarGridPanel;
        private transient JButton nextYearButton;
        private transient JButton prevYearButton;
        private transient JButton nextMonthButton;
        private transient JButton prevMonthButton;
        private static final int numDays[] = {
            31, 28, 31, 30, 31, 30, 31, 31, 30, 31,
            30, 31
        private transient Vector months;
        private Date selectedDate;
        private transient PropertyChangeSupport changes;
        public JCalendarPanel()
            days = new JButton[42];
            dayOfWeekLabel = new JLabel[7];
            selectedButton = null;
            sundayColumnIndex = 0;
            months = new Vector(12);
            selectedDate = new Date();
            changes = new PropertyChangeSupport(this);
            setFont(new Font("Dialog", 0, 12));
            FontMetrics fontmetrics = getFontMetrics(getFont());
            cellHeight = fontmetrics.getHeight() + 10;
            cellWidth = fontmetrics.stringWidth("WWW") + 10;
            setLayout(new BorderLayout());
            headerPanel = new JPanel();
            calendarGridPanel = new JPanel();
            headerPanel.setLayout(new FlowLayout());
            calendarGridPanel.setLayout(new GridLayout(7, 7));
            add(headerPanel, "North");
            add(calendarGridPanel, "Center");
            Insets insets = new Insets(1, 1, 1, 1);
            yearLabel = new JLabel("");
            nextMonthButton = new JButton(new ArrowIcon(1));
            nextMonthButton.setAlignmentY(0.5F);
            nextMonthButton.setMargin(insets);
            nextMonthButton.addActionListener(this);
            prevMonthButton = new JButton(new ArrowIcon(2));
            prevMonthButton.setAlignmentY(0.5F);
            prevMonthButton.setMargin(insets);
            prevMonthButton.addActionListener(this);
            nextYearButton = new JButton(new ArrowIcon(0));
            nextYearButton.setAlignmentY(0.5F);
            nextYearButton.setMargin(insets);
            nextYearButton.addActionListener(this);
            prevYearButton = new JButton(new ArrowIcon(3));
            prevYearButton.setAlignmentY(0.5F);
            prevYearButton.setMargin(insets);
            prevYearButton.addActionListener(this);
            buildMonths();
            monthChoice = new JComboBox(months);
            monthChoice.addActionListener(this);
            headerPanel.add(prevYearButton);
            headerPanel.add(prevMonthButton);
            headerPanel.add(monthChoice);
            headerPanel.add(yearLabel);
            headerPanel.add(nextMonthButton);
            headerPanel.add(nextYearButton);
            buildDays();
            buildCells();
            Date date = new Date();
            setSelectedDate(date);
        public void actionPerformed(ActionEvent actionevent)
            Object obj = actionevent.getSource();
            if(obj == nextMonthButton)
                nextMonth();
                return;
            if(obj == prevMonthButton)
                lastMonth();
                return;
            if(obj == nextYearButton)
                nextYear();
                return;
            if(obj == prevYearButton)
                lastYear();
                return;
            if(obj == monthChoice)
                JComboBox jcombobox = (JComboBox)obj;
                selectedMonth = jcombobox.getSelectedIndex();
                setButtonState(selectedButton, false);
                selectedButton = null;
                Calendar calendar = Calendar.getInstance();
                calendar.set(selectedYear, selectedMonth, selectedDay);
                setSelectedDate(calendar.getTime());
                return;
            if(obj instanceof JButton)
                for(int i = 0; i < 42; i++)
                    if(obj == days)
    if(selectedButton != null)
    setButtonState(selectedButton, false);
    selectedButton = days[i];
    setButtonState(selectedButton, true);
    selectedDay = Integer.parseInt(days[i].getText());
    Calendar calendar1 = Calendar.getInstance();
    calendar1.set(selectedYear, selectedMonth, selectedDay);
    setSelectedDate(calendar1.getTime());
    return;
    public void addPropertyChangeListener(PropertyChangeListener propertychangelistener)
    changes.addPropertyChangeListener(propertychangelistener);
    private void buildCells()
    int i = sundayColumnIndex;
    for(int j = 0; j < 42; j++)
    JButton jbutton = new JButton(" ");
    jbutton.setEnabled(false);
    jbutton.setSize(cellWidth, cellHeight);
    jbutton.addActionListener(this);
    jbutton.setSelected(false);
    jbutton.setBorderPainted(false);
    if(j == i)
    jbutton.setForeground(Color.red);
    i += 7;
    calendarGridPanel.add(jbutton);
    days[j] = jbutton;
    private void buildDays()
    Calendar calendar = Calendar.getInstance();
    SimpleDateFormat simpledateformat = (SimpleDateFormat)DateFormat.getDateInstance(0);
    simpledateformat.applyPattern("EEE");
    boolean flag = false;
    int i = calendar.getFirstDayOfWeek();
    for(int j = 0; j < 7; j++)
    if(i == 1)
    calendar.set(1997, 5, j + 1);
    } else
    calendar.set(1997, 8, j + 1);
    StringTokenizer stringtokenizer = new StringTokenizer(simpledateformat.format(calendar.getTime()));
    JLabel jlabel = new JLabel(stringtokenizer.nextElement().toString(), 0);
    jlabel.setSize(cellWidth, cellHeight);
    if(!flag && calendar.get(7) == 1)
    jlabel.setForeground(Color.red);
    sundayColumnIndex = j;
    flag = true;
    calendarGridPanel.add(jlabel);
    dayOfWeekLabel[j] = jlabel;
    private void buildMonths()
    Calendar calendar = Calendar.getInstance();
    SimpleDateFormat simpledateformat = (SimpleDateFormat)DateFormat.getDateInstance(0);
    simpledateformat.applyPattern("MMMM");
    for(int i = 0; i < 12; i++)
    calendar.set(1997, i, 2);
    months.addElement(simpledateformat.format(calendar.getTime()));
    private int getDaysInMonth(int i, int j)
    int k = j;
    int l = numDays[i];
    if(i == 1 && k % 4 == 0 && (k % 100 != 0 || k % 400 == 0))
    l = 29;
    return l;
    public Date getSelectedDate()
    Calendar calendar = Calendar.getInstance();
    calendar.set(selectedYear, selectedMonth, selectedDay);
    return calendar.getTime();
    private void lastMonth()
    setButtonState(selectedButton, false);
    selectedButton = null;
    if(--selectedMonth < 0)
    selectedMonth = 11;
    selectedYear--;
    Calendar calendar = Calendar.getInstance();
    calendar.set(selectedYear, selectedMonth, selectedDay);
    setSelectedDate(calendar.getTime());
    private void lastYear()
    setButtonState(selectedButton, false);
    selectedButton = null;
    selectedYear--;
    Calendar calendar = Calendar.getInstance();
    calendar.set(selectedYear, selectedMonth, selectedDay);
    setSelectedDate(calendar.getTime());
    private void nextMonth()
    setButtonState(selectedButton, false);
    selectedButton = null;
    if(++selectedMonth > 11)
    selectedMonth = 0;
    selectedYear++;
    Calendar calendar = Calendar.getInstance();
    calendar.set(selectedYear, selectedMonth, selectedDay);
    setSelectedDate(calendar.getTime());
    private void nextYear()
    setButtonState(selectedButton, false);
    selectedButton = null;
    selectedYear++;
    Calendar calendar = Calendar.getInstance();
    calendar.set(selectedYear, selectedMonth, selectedDay);
    setSelectedDate(calendar.getTime());
    protected String paramString()
    StringBuffer stringbuffer = new StringBuffer("selectedDate=");
    SimpleDateFormat simpledateformat = (SimpleDateFormat)DateFormat.getDateInstance(0);
    stringbuffer.append(simpledateformat.format(selectedDate));
    stringbuffer.append(", locale=");
    stringbuffer.append(Locale.getDefault().getDisplayName());
    return stringbuffer.toString();
    public void removePropertyChangeListener(PropertyChangeListener propertychangelistener)
    changes.removePropertyChangeListener(propertychangelistener);
    private void setButtonState(JButton jbutton, boolean flag)
    if(jbutton != null)
    jbutton.setBorderPainted(flag);
    jbutton.setSelected(flag);
    public void setSelectedDate(Date date)
    if(date != null)
    Date date1 = selectedDate;
    selectedDate = date;
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(selectedDate);
    selectedMonth = calendar.get(2);
    selectedYear = calendar.get(1);
    selectedDay = calendar.get(5);
    changes.firePropertyChange("selectedDate", date1, date);
    updateDisplay();
    public String toString()
    return getClass().getName() + "[" + paramString() + "]";
    private void updateDisplay()
    Calendar calendar = Calendar.getInstance();
    calendar.set(selectedYear, selectedMonth, 1);
    Date date = calendar.getTime();
    calendar.setTime(date);
    int i = calendar.get(7) - calendar.getFirstDayOfWeek();
    int j = 1;
    int k = getDaysInMonth(selectedMonth, selectedYear);
    for(int l = 0; l < 42; l++)
    JButton jbutton = days[l];
    if(l < i)
    jbutton.setVisible(false);
    } else
    jbutton.setText(Integer.toString(j));
    if(j == selectedDay)
    if(selectedButton != null)
    setButtonState(selectedButton, false);
    selectedButton = jbutton;
    setButtonState(selectedButton, true);
    if(j <= k)
    jbutton.setEnabled(true);
    jbutton.setVisible(true);
    j++;
    } else
    jbutton.setVisible(false);
    yearLabel.setText(Integer.toString(selectedYear));
    monthChoice.setSelectedIndex(selectedMonth);

    It might be helpful to note that a good place to see how to use this stuff is here:
    http://java.sun.com/j2se/1.4.2/docs/guide/beans/axbridge/developerguide/
    and that the point is not to know the implementation. The point is to know the interface.
    From http://home1.pacific.net.sg/~wongkw/TestCal4.java
    import java.awt.*;
    import java.awt.event.*;
    import java.beans.*;
    import java.util.*;
    import java.text.*;
    import javax.swing.*;
    import wkw.beans.ui.JCalendarPanel;
    public class TestCal4 implements PropertyChangeListener {
        JTextField date = new JTextField(15);
        wkw.beans.ui.JCalendarPanel cal = null;
        DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.SHORT);
        public static void main(String args[]) {
            TestCal4 tc = new TestCal4();
        public TestCal4() {
            try {
                cal = (wkw.beans.ui.JCalendarPanel)Beans.instantiate(
                        TestCal4.class.getClassLoader(), "wkw.beans.ui.JCalendarPanel");
                if (cal == null) {
                    System.err.println("Unable to load bean, aborting...");
                    System.exit(-1);
            } catch (Exception e) {
                System.err.println(
                        "Exception when loading bean, aborting..." + e);
                System.exit(-1);
    //        cal = new wkw.beans.ui.JCalendarPanel();
            cal.addPropertyChangeListener(this);
            JFrame f = new JFrame("Test JCalendarPanel");
            f.addWindowListener(new WindowAdapter() {
                        public void windowClosing(WindowEvent evt) {
                            Window win = evt.getWindow();
                            win.setVisible(false);
                            win.dispose();
                            System.exit(0);
            f.getContentPane().setLayout(new BorderLayout());
            f.getContentPane().add(cal, BorderLayout.CENTER);
            JPanel input = new JPanel();
            JButton set = new JButton("Set");
            set.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent act) {
                            try {
                                Date setDate = dateFormat.parse(date.getText());
                                if (setDate != null) {
                                    cal.setSelectedDate(setDate);
                            } catch (ParseException e) {
                                //do nothing
            input.add(date);
            input.add(set);
            f.getContentPane().add(input, BorderLayout.SOUTH);
            f.pack();
            f.show();
        public void propertyChange(PropertyChangeEvent event) {
            Date oldDate = (Date)event.getOldValue();
            Date newDate = (Date)event.getNewValue();
            Date selectedDate = cal.getSelectedDate();
            System.out.println("==========================");
            System.out.println("Old date= " + oldDate);
            System.out.println("New date= " + newDate);
            System.out.println("Selected date= " + selectedDate);
            System.out.println("==========================");
    }One other comment: I usually play some childish game rather than simply admit that I use reverse compilers. It frustrates those who would otherwise bug me about reverse-engineering something that I do not have permission to do so.
    One last comment: I suspect that the original, much-more-readable source is available. If I find it, I will provide a pointer.

  • SetEnabled to false for a JSpinner

    hi all,
    I've got a little problem that I hope someone can solve for me.
    I'm trying to setEnabled() to false for my JSpinners, at run time, even though it is set to false, the JSpinner is still enabled and allows editing.
    Is this because JSpinners doesn't allow it to be disabled, or I have done something fatally wrong?
    Here is a snipet of my code.
    SpinnerNumberModel spinDays = new SpinnerNumberModel(days,0,30,1);
    spinnerDays = new JSpinner(spinDays);
    spinnerDays.addChangeListener(new ChangeListener(){
         public void stateChanged(ChangeEvent e){
         setSpinnerDays();     
    spinnerDays.setEnabled(false);
    Gabriel.

    This bug has been fixed in JDK1.4 beta 2. Download the latest version.
    Cheers,
    Joris
    http://www.esus.com

  • How do i use jbutton for mutiple frames(2frames)???

    im an creating a movie database program and i have a problem with the jButtons on my second frame i dont know how to make them work when clicked on. i managed to make the jButtons work on my first frame but not on the second....
    here is that code so far----
    import java.awt.Container;
    import java.awt.Dimension;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.Insets;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.KeyEvent;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.JTextField;
    * real2.java
    * Created on December 7, 2007, 9:00 AM
    * To change this template, choose Tools | Template Manager
    * and open the template in the editor.
    * @author J
    public class real2 extends JPanel  implements ActionListener{
        private JButton addnew;
        private JButton help;
        private JButton exit;
        private JFrame frame1;
        private JButton save;
        private JButton cancel;
        private JButton save2;
        private JLabel moviename;
        private JTextField moviename2;
        private JLabel director;
        private JTextField director2;
        private JLabel year;
        private JTextField year2;
        private JLabel genre;
        private JTextField genre2;
        private JLabel plot;
        private JTextField plot2;
        private JLabel rating;
        private JTextField rating2;
        /** Creates a new instance of real2 */
        public real2() {
            super(new GridBagLayout());
            //Create the Buttons.
            addnew = new JButton("Add New");
            addnew.addActionListener(this);
            addnew.setMnemonic(KeyEvent.VK_E);
            addnew.setActionCommand("Add New");
            help = new JButton("Help");
            help.addActionListener(this);
            help.setActionCommand("Help");
            exit = new JButton("Exit");
            exit.addActionListener(this);
            exit.setActionCommand("Exit");
           String[] columnNames = {"First Name",
                                    "Last Name",
                                    "Sport",
                                    "# of Years",
                                    "Vegetarian"};
            Object[][] data = {
                {"Mary", "Campione",
                 "Snowboarding", new Integer(5), new Boolean(false)},
                {"Alison", "Huml",
                 "Rowing", new Integer(3), new Boolean(true)},
                {"Kathy", "Walrath",
                 "Knitting", new Integer(2), new Boolean(false)},
                {"Sharon", "Zakhour",
                 "Speed reading", new Integer(20), new Boolean(true)},
                {"Philip", "Milne",
                 "Pool", new Integer(10), new Boolean(false)}
            final JTable table = new JTable(data, columnNames);
            table.setPreferredScrollableViewportSize(new Dimension(600, 100));
            table.setFillsViewportHeight(true);
            //Create the scroll pane and add the table to it.
            JScrollPane scrollPane = new JScrollPane(table);
            //Add the scroll pane to this panel.
            add(scrollPane);
            GridBagConstraints c = new GridBagConstraints();
            c.weightx = 1;
            c.gridx = 0;
            c.gridy = 1;
            add(addnew, c);
            c.gridx = 0;
            c.gridy = 2;
            add(help, c);
            c.gridx = 0;
            c.gridy = 3;
            add(exit, c);
        public static void addComponentsToPane(Container pane){
            pane.setLayout(null);
            //creating the components for the new frame
            JButton save = new JButton("Save");
            JButton save2 = new JButton("Save and add another");
            JButton cancel = new JButton("Cancel");
            JLabel moviename= new JLabel("Movie Name");
            JTextField moviename2 = new JTextField(8);
            JLabel director = new JLabel("Director");
            JTextField director2 = new JTextField(8);
            JLabel genre = new JLabel("Genre");
            JTextField genre2 = new JTextField(8);
            JLabel year = new JLabel("year");
            JTextField year2 = new JTextField(8);
            JLabel plot = new JLabel("Plot");
            JTextField plot2 = new JTextField(8);
            JLabel rating = new JLabel("Rating(of 10)");
            JTextField rating2 = new JTextField(8);
            //adding components to new frame
            pane.add(save);
            pane.add(save2);
            pane.add(cancel);
            pane.add(moviename);
            pane.add(moviename2);
            pane.add(director);
            pane.add(director2);
            pane.add(genre);
            pane.add(genre2);
            pane.add(year);
            pane.add(year2);
            pane.add(plot);
            pane.add(plot2);
            pane.add(rating);
            pane.add(rating2);
            //setting positions of components for new frame
                Insets insets = pane.getInsets();
                Dimension size = save.getPreferredSize();
                save.setBounds(100 , 50 ,
                         size.width, size.height);
                 size = save2.getPreferredSize();
                save2.setBounds(200 , 50 ,
                         size.width, size.height);
                 size = cancel.getPreferredSize();
                cancel.setBounds(400 , 50 ,
                         size.width, size.height);
                 size = moviename.getPreferredSize();
                moviename.setBounds(100 , 100 ,
                         size.width, size.height);
                size = moviename2.getPreferredSize();
                moviename2.setBounds(200 , 100 ,
                         size.width, size.height);
                 size = director.getPreferredSize();
                director.setBounds(100, 150 ,
                         size.width, size.height);
                 size = director2.getPreferredSize();
                director2.setBounds(200 , 150 ,
                         size.width, size.height);
                size = genre.getPreferredSize();
                genre.setBounds(100 , 200 ,
                         size.width, size.height);
                 size = genre2.getPreferredSize();
                genre2.setBounds(200 , 200 ,
                         size.width, size.height);
                 size = year.getPreferredSize();
                year.setBounds(100 , 250 ,
                         size.width, size.height);
                size = year2.getPreferredSize();
                year2.setBounds(200 , 250 ,
                         size.width, size.height);
                 size = plot.getPreferredSize();
                plot.setBounds(100 , 300 ,
                         size.width, size.height);
                 size = plot2.getPreferredSize();
                plot2.setBounds(200 , 300 ,
                         size.width, size.height);
                size = rating.getPreferredSize();
                rating.setBounds(100 , 350 ,
                         size.width, size.height);
                 size = rating2.getPreferredSize();
                rating2.setBounds(200 , 350 ,
                         size.width, size.height);
        private static void createAndShowGUI() {
            //Create and set up the window.
            JFrame frame = new JFrame();
            frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
            frame.add(new real2());
            //Display the window.
            frame.setSize(600, 360);
            frame.setVisible(true);
            frame.pack();
        public static void main(String[] args) {
            //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
        public void actionPerformed(ActionEvent e) {
            if ("Add New".equals(e.getActionCommand())){
               frame1 = new JFrame("add");
               frame1.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
               addComponentsToPane(frame1.getContentPane());
               frame1.setSize(600, 500);
               frame1.setVisible(true);
                //disableing first frame etc:-
                if (frame1.isShowing()){
                addnew.setEnabled(false);
                help.setEnabled(false);
                exit.setEnabled(true);
                frame1.setVisible(true);
               }else{
                addnew.setEnabled(true);
                help.setEnabled(true);
                exit.setEnabled(true);           
            if ("Exit".equals(e.getActionCommand())){
                System.exit(0);
            if ("Save".equals(e.getActionCommand())){
                // whatever i ask it to do it wont for example---
                help.setEnabled(true);
            if ("Save" == e.getSource()) {
                //i tried this way too but it dint work here either
                help.setEnabled(true);
    }so if someone could help me by either telling me what to type or by replacing what iv done wrong that would be great thanks...

    (1)Java class name should begin with a capital letter. See: http://java.sun.com/docs/codeconv/
            JButton save = new JButton("Save");
            JButton save2 = new JButton("Save and add another");
            // ... etc. ...(2)Don't redeclare class members in a method as its local variable. Your class members become eternally null, a hellish null.
    how to make them work when clicked on(3)Add action listener to them.

  • Problem in displaying Icon on JButton

    Hi,
    I have a problem ..
    In my program I have to set Icon for a Jbutton and wait for 2 secs and then remove the Icon..
    I used jb.setIcon(Imageicon) (jb is button reference) to set the icon and jb.setIcon(null) to remove Icon
    Now no Icon is displayed on the button at all....
    My code looks like below mentioned
    jb.setIcon(Imageicon)
    Thread.sleep(2000);
    jb.setIcon(null)
    plz reply mee at the earliest...

    the code snipped is like this..
    the below mentioned code is in actionPerformed method
    pres.setIcon(iial.get(Integer.parseInt(pres.getName())));  //icon for prev is already set
              System.out.println("Icon for pres is set now");
    // need to wait for 2 seconds before both the icons are set to null
              prev.setIcon(null);
              pres.setIcon(null);Here prev and pres are references to JButtons.
    I tried the swing timers but couldnt succeed (i might be implemented them in an incorrect way coz im not familiar with them)
    plz cud you provide me with am example program or a solution to above scenario in a program.....
    Here is the actual program if you want you can run it with keeping atleast 9 images in tn folder and changing maxpics value to 9
    Game.java
    package com;
    //Concentration Game
    import java.awt.BorderLayout;
    import java.awt.Container;
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.lang.reflect.InvocationTargetException;
    import java.util.ArrayList;
    import java.util.Collections;
    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.SwingUtilities;
    public class Game extends JFrame implements ActionListener {
         private static final long serialVersionUID = 1L;
         public static void main(String args[]) throws InterruptedException,
                   InvocationTargetException {
    System.out.println();
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
             Game cg = new Game();
              cg.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         Logic logic;
         private int[][] arr;
         private Container contents;
         private JLabel controlLabel;
         private JPanel controlPanel;
         private JButton[][] gameBoardLabel;
         private JPanel gamePanel;
         private ArrayList<ImageIcon> iial;
         private boolean isNewAction = true, isFirstAction = true;
         private JButton prev, pres;
         private long s_time, e_time, t_time;
         private int SIZE, arrvalue, maxpics = 51, pairscount, no_of_pairs;
         public Game() {
              super("Concentration Game");
              logic = new Logic();
              logic.populateArray();
              logic.shuffle();
              logic.printArray();
              arr = logic.getArray();
              SIZE = logic.getSize();
              no_of_pairs = (SIZE * SIZE) / 2;
              iial = new ArrayList<ImageIcon>();
              for (int i = 1; i <= maxpics; i++) {
                   iial.add(new ImageIcon(this.getClass().getClassLoader()
                             .getResource("tn/image" + i + ".jpg")));
              Collections.shuffle(iial);
              System.out.println("Completed loading images");
              contents = getContentPane();
              contents.setLayout(new BorderLayout());
              gameBoardLabel = new JButton[SIZE][SIZE];
              new JPanel();
              gamePanel = new JPanel();
              controlPanel = new JPanel();
              gamePanel.setLayout(new GridLayout(SIZE, SIZE, 5, 5));
              controlLabel = new JLabel("Game not started");
              for (int r = 0; r < gameBoardLabel.length; r++) {
                   for (int c = 0; c < gameBoardLabel[r].length; c++) {
                        arrvalue = arr[r][c];
                        System.out.println(arrvalue);
                        if (arr[r][c] == 0) {
                             gameBoardLabel[r][c] = new JButton();
                             gameBoardLabel[r][c].setEnabled(false);
                        else
                             gameBoardLabel[r][c] = new JButton();
                        gameBoardLabel[r][c].addActionListener(this);
                        gameBoardLabel[r][c].setName("" + arrvalue);
                        gameBoardLabel[r][c].setPressedIcon(iial.get(arrvalue));
                        gamePanel.add(gameBoardLabel[r][c]);
              controlPanel.add(controlLabel);
              contents.add(gamePanel, BorderLayout.CENTER);
              contents.add(controlPanel, BorderLayout.SOUTH);
              setSize(400, 500);
              setVisible(true);
              System.out.println(this);
         @Override
         public void actionPerformed(ActionEvent e) {
              JButton jb = (JButton) e.getSource();
              // System.out.println(jb.getName());
              System.out.println(e.getSource());
              if (isFirstAction) {
                   controlLabel.setText("Game Started");
                   s_time = System.currentTimeMillis();
                   isFirstAction = false;
                   System.out.println(this);
              if (isNewAction) {
                   prev = pres = jb;
                   jb.setIcon(iial.get(Integer.parseInt(jb.getName())));
                   isNewAction = false;
                   return;
              prev = pres;
              pres = jb;
              if (pres == prev)
                   return;
              if (pres.getName().equals(prev.getName())) {
                   pres.setIcon(iial.get(Integer.parseInt(pres.getName())));
                   pres.removeActionListener(this);
                   prev.removeActionListener(this);
                   controlLabel.setText("pair matched");
                   resetAttributes();
                   System.out.println("haha----last count==" + ++pairscount);
                   if (pairscount == no_of_pairs) {
                        e_time = System.currentTimeMillis();
                        t_time = (e_time - s_time) / 1000;
                        controlLabel.setText("Game Over in " + t_time + " secs");
                        System.out.println("done");
              System.out.println(pres);
              pres.setIcon(iial.get(Integer.parseInt(pres.getName())));
              controlLabel.setText("pair didn't match");
              System.out.println("pres is set now");
              prev.setIcon(null);
              pres.setIcon(null);
              resetAttributes();
         private void resetAttributes() {
              prev = pres = null;
              isNewAction = true;
    Logic.java
    package com;
    import java.util.ArrayList;
    import java.util.Collections;
    import javax.swing.JOptionPane;
    public class Logic{
          ArrayList<Integer> al;
          int arr[][],arrlist[][],elements=1;
          int SIZE;
    int[][] getArray()
              return arrlist;
    int getSize(){
         return SIZE;
    public static void main(String args[]){
         Logic logic =new Logic();
                logic.populateArray();
               logic.shuffle();
               logic.printArray();
               //System.out.println(logic.elements);
    void populateArray(){
         String input=JOptionPane.showInputDialog(null,"Enter Size of the array (less than 11)" );
         SIZE=Integer.parseInt(input);
         int cnt = 0;
         arrlist=new int[SIZE][SIZE];
         al=new ArrayList<Integer>();
         for (int r = 0; r < SIZE; r++)
              for (int c = 0; c < SIZE; c++)
                   al.add(elements);
                   cnt++;
                   if (cnt == 2)
                        cnt = 0;
                        elements++;
    public  void printArray() {
         for (int i = 0; i < SIZE; i++)
          for (int j = 0; j < SIZE; j++)
            arrlist[i][j] = al.get(j + i * SIZE);
            System.out.print(" "+arrlist[i][j]);
          System.out.println();
    public  void shuffle() {
              Collections.shuffle(al);
         if(SIZE%2!=0)
              int cindex=(SIZE*SIZE)/2; //center index
              int celement=al.get(cindex); //center element
              int lindex=al.indexOf(elements); //index of large element
              //al.remove(cindex);
              //al.add(cindex, 0);
              al.remove(lindex);
              al.add(lindex, celement);
              al.remove(cindex);
              al.add(cindex, 0);
    }

  • JButton keeps JFrame from succesfully implementing KeyListener?!

    Look at this code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Test extends JFrame implements KeyListener
         private JButton myButton;
         public Test()
              Container c = getContentPane();
              c.setLayout( new FlowLayout() );
              myButton = new JButton();
              myButton.setEnabled( true );
              c.add( myButton );
              addKeyListener( this );
              setSize( 100, 100 );
              show();
         public void keyPressed( KeyEvent e )
                System.out.println( "keyPressed" );
         public void keyReleased( KeyEvent e )
              System.out.println( "keyReleased" );
         public void keyTyped( KeyEvent e )
              System.out.println( "keyTyped" );
         public static void main( String args[] )
              Test window = new Test();
    }When you execute this program, the JFrame does not resolve keystrokes. It should though, because it implements KeyListener and overrides all required methods. But here is the strange thing: Try changing
    myButton.setEnabled( true );to
    myButton.setEnabled( false );Now the JFrame is able to respond to keystrokes by executing the proper methods! But what use is a button if it is not enabled. I need my buttons in the JFrame, but I also need the JFrame to respond to the keystrokes.
    Anyone know about this problem and how to solve it??
    Thank you!

    ?? Say you want to make a small game. A square is drawn onto the frame. The user presses the up button on the keybord and the square 'moves' up (it is repainted at a different coordinate). But the user also needs to be able to (re)start the game and exit through the use of JButtons. That is the purpose and the problem is stated in my first post...
    Anyone else has an idea?
    thx

  • Problem disabling JButton in ActionListener after setText of JLabel

    What i want is when i click View to see the label say "Viewing ..." and in the same time the btnView (View Button) to be disabled.
    I want the same with the other 2 buttons.
    My problem is in ActionListener of the button. It only half works.
    I cannot disable (setEnabled(false)) the button after it is pressed and showing the JLabel.
    The code i cannot run is the 3 buttons setEnabled (2 in comments).
    Any light?
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    class BTester extends JFrame implements ActionListener { 
         JButton btnView, btnBook, btnSearch;
         BTester(){     //Constructor
              JPanel p = new JPanel();
         JButton btnView = new JButton( "View" );
         btnView.setActionCommand( "View" );
         btnView.addActionListener(this);
         JButton btnBook = new JButton( "Book" );
         btnBook.setActionCommand( "Book" );
         btnBook.addActionListener(this);
         JButton btnSearch = new JButton( "Search" );
         btnSearch.setActionCommand( "Search" );
         btnSearch.addActionListener(this);
         p.add(btnView);
         p.add(btnBook);
         p.add(btnSearch);
         getContentPane().add(show, "North"); //put text up
    getContentPane().add(p, "South"); //put panel of buttons down
    setSize(400,200);
    setVisible(true);
    setTitle("INITIAL BUTTON TESTER");
    show.setFont(new Font("Tahoma",Font.BOLD,20));
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);     
         //actionPerformed implemented (overrided)
         public void actionPerformed( ActionEvent ae) {
    String actionName = ae.getActionCommand().trim();
    if( actionName.equals( "View" ) ) {
    show.setText("Viewing ...");
         btnView.setEnabled(false); // The line of problem
    //btnBook.setEnabled(true);
    //btnSearch.setEnabled(true);
    else if( actionName.equals( "Book" ) ) {
    show.setText("Booking ...");
    //btnView.setEnabled(true);
    //btnBook.setEnabled(false);
    //btnSearch.setEnabled(true);
    else if( actionName.equals( "Search" ) ) {
    show.setText("Searching ...");
    //btnView.setEnabled(true);
    //btnBook.setEnabled(true);
    //btnSearch.setEnabled(false);
    } //end actionPerformed
         private JLabel show = new JLabel( "Press a button ... " );
    public static void main(String[] args) { 
         new BTester();
    } // End BTester class

    1. Use code formatting when posting code.
    2. You have a Null Pointer Exception since in your constructor you create the JButtons and assign them to a local variable instead of the class member.
    Change this
    JButton btnView = new JButton( "View" );to:
    btnView = new JButton( "View" );

  • Renderer problem for a JButton in a JTable

    Hi all,
    Here is my requirement -
    When the value of a particular cell in a JTable gets changed, another cell in the same selected row should display a JButton. The button should remain displayed for that row. Other rows should not have the button displayed unless there is any change in value of other columns in that row.
    I have the problem in displaying the button only when the values of a particular row is changed. The button gets displayed if I click that button cell which should not happen as the values are not changed for the corresponding row. Also, once the button is displayed for a particular row, if i click some other row, button gets disappeared for the previously selected row.
    Here is the code I have implemented. Please correct me where I am going wrong.
    Renderer code for the button-
    ==================
    class ButtonRenderer extends JButton implements TableCellRenderer {
    public ButtonRenderer() {
    setOpaque(true);
    public Component getTableCellRendererComponent(JTable table, Object value,
    boolean isSelected, boolean hasFocus, int row, int column)
    if (isSelected) {
    setForeground(table.getSelectionForeground());
    setBackground(table.getSelectionBackground());
    } else{
    setForeground(table.getForeground());
    setBackground(UIManager.getColor("Button.background"));
    TableModel model = table.getModel();
    // get values from the table model's selected row and specific column
    if(// check if values are changed from old ones)
    setText("Undo");
    setVisible(true);
    return (JButton) value;
    else
    JButton button = new JButton("");
    button.setBackground(Color.white);
    button.setBorderPainted(false);
    button.setMargin(new Insets(0, 0, 0, 0));
    button.setEnabled(false);
    return button;
    Editor code for the button -
    =======================
    class ButtonCellEditor extends DefaultCellEditor
    public ButtonCellEditor(JButton aButton)
    super(new JTextField());
    setClickCountToStart(0);
    aButton.setOpaque(true);
    aButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    fireEditingStopped();
    editorComponent = aButton;
    protected void fireEditingStopped()
    super.fireEditingStopped();
    public Object getCellEditorValue()
    return editorComponent;
    public boolean stopCellEditing()
    return super.stopCellEditing();
    public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column)
    return editorComponent;
    Code setting the renderer/editor -
    ==================================
    TableColumn column = colModel.getColumn(6);
    button.setVisible(true);
    button.setEnabled(true);
    column .setCellRenderer(new ButtonRenderer());
    column .setCellEditor(new ButtonCellEditor(button));
    Please correct me where I am going wrong.
    Thanks in advance!!

    Hope this is what you want...edit the column "Value" and type "Show" to get the desired result.
    import java.awt.Component;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.DefaultCellEditor;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JOptionPane;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.JTextField;
    import javax.swing.table.AbstractTableModel;
    import javax.swing.table.DefaultTableCellRenderer;
    public class TableEdit2 extends JFrame
         Object[] columns =
         { "A", "Value", "Action" };
         Object[][] data =
         { "A0", "B0", "" },
         { "A1", "B1", "" },
         { "A2", "B2", "" },
         { "A3", "B3", "" },
         { "A4", "B4", "" },
         { "A5", "B5", "" },
         { "A6", "B6", "" },
         { "A7", "B7", "" },
         { "A8", "B8", "" },
         { "A9", "B9", "" },
         { "A10", "B10", "" },
         { "A11", "B11", "" } };
         JTable table = null;
         public TableEdit2()
              super("Table Edit");
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              createGUI();
              setLocationRelativeTo(null);
              setSize(400, 300);
              setVisible(true);
         private void createGUI()
              table = new JTable(data, columns)
                   public void setValueAt(Object value, int row, int column)
                        super.setValueAt(value, row, column);
                        ((AbstractTableModel) table.getModel()).fireTableRowsUpdated(
                                  row, row);
              table.getColumn("Action").setCellRenderer(new ButtonRenderer());
              table.getColumn("Action").setCellEditor(new MyTableEditor(new JTextField()));
              JScrollPane sc = new JScrollPane(table);
              add(sc);
         class ButtonRenderer extends DefaultTableCellRenderer
              JButton undoButton = new JButton("Undo");
              public ButtonRenderer()
                   super();
              public Component getTableCellRendererComponent(JTable table,
                        Object value, boolean isSelected, boolean hasFocus, int row,
                        int column)
                   Component comp = super.getTableCellRendererComponent(table, value,
                             isSelected, hasFocus, row, column);
                   if (column == 2)// The Action Column
                        Object checkValue = table.getValueAt(row, 1);
                        if ("Show".equals(String.valueOf(checkValue)))
                             return undoButton;
                   return comp;
         class MyTableEditor extends DefaultCellEditor
              JButton undoButton = new JButton("Undo");
              public MyTableEditor(JTextField dummy)
                   super(dummy);
                   setClickCountToStart(0);
                   undoButton.addActionListener(new ActionListener()
                        public void actionPerformed(ActionEvent e)
                             JOptionPane.showMessageDialog(null, "Do your Action Here");
              public Component getTableCellEditorComponent(JTable table,
                        Object value, boolean isSelected, int row, int column)
                   Component comp = super.getTableCellEditorComponent(table, value, isSelected, row, column);
                   if (column == 2)// The Action Column
                        Object checkValue = table.getValueAt(row, 1);
                        if ("Show".equals(String.valueOf(checkValue)))
                             return undoButton;
                   return comp;
              public Object getCellEditorValue()
                   return "";
          * @param args
         public static void main(String[] args)
              // TODO Auto-generated method stub
              new TableEdit2();
    }

  • How at add closd function in the JButton??

    Hi, sir:
    I hope to add a closd function in the JButton, ie, like a JPanel or JFrame, there is a "X" sign icon on the right upper coner, when we click this X sign,
    whole window or JPanel or JFrame will be closed, here I hope to add a "x" sign in JButton, when I click it, itthis button b2 will be vanished.
    I update following code, but looks like not work, I hope Text and its icon on the leading Left, but closed sign is on the extreme end of right.
    Can guru help??
    Thanks
    import javax.swing.AbstractButton;
    import javax.swing.Icon;
    import javax.swing.JButton;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JFrame;
    import javax.swing.ImageIcon;
    import javax.swing.SwingConstants;
    import javax.swing.GroupLayout.Alignment;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.KeyEvent;
    * ButtonDemo.java requires the following files:
    *   images/right.gif
    *   images/middle.gif
    *   images/left.gif
    public class ButtonDemo2 extends JPanel  implements ActionListener {
        protected JButton  b2,bclosed;
        public ButtonDemo2() {
             Icon closedIcon  = new ImageIcon("images/ActionButton/closed.PNG");
            ImageIcon middleButtonIcon = new ImageIcon("images/little.gif");
            JLabel label1 = new JLabel("Image and Text", middleButtonIcon, JLabel.CENTER);
            bclosed = new JButton(closedIcon);
            bclosed.setBorder(null);
            bclosed.setToolTipText("closed");
            b2 = new JButton("Middle button", middleButtonIcon);
            b2.setText("Middle button");
            b2.setVerticalTextPosition(AbstractButton.BOTTOM);
            b2.add(bclosed, -1);
            b2.setIcon(middleButtonIcon);
            b2.setHorizontalTextPosition(AbstractButton.LEFT);
            b2.setAlignmentX(LEFT_ALIGNMENT);
            b2.setMnemonic(KeyEvent.VK_M);
              b2.setToolTipText("This middle button does nothing when you click it.");
            //Add Components to this container, using the default FlowLayout.
            add(label1);
            add(b2);
        public void actionPerformed(ActionEvent e) {
            if ("disable".equals(e.getActionCommand())) {
                b2.setEnabled(false);
            } else {
                b2.setEnabled(true);
        private static void createAndShowGUI() {
            //Create and set up the window.
            JFrame frame = new JFrame("ButtonDemo");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //Create and set up the content pane.
            ButtonDemo2 newContentPane = new ButtonDemo2();
            newContentPane.setOpaque(true); //content panes must be opaque
            frame.setContentPane(newContentPane);
            //Display the window.
            frame.pack();
            frame.setVisible(true);
        public static void main(String[] args) {
            //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
    }

    Thanks, I add as follows:
    package a.border;
    import javax.swing.AbstractButton;
    import javax.swing.Icon;
    import javax.swing.JButton;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JFrame;
    import javax.swing.ImageIcon;
    import javax.swing.SwingConstants;
    import javax.swing.GroupLayout.Alignment;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.KeyEvent;
    * ButtonDemo.java requires the following files:
    *   images/right.gif
    *   images/middle.gif
    *   images/left.gif
    public class ButtonDemo2 extends JPanel  implements ActionListener {
        protected JButton  b2,bclosed;
        public ButtonDemo2() {
             Icon closedIcon  = new ImageIcon("images/ActionButton/closed.PNG");
            ImageIcon middleButtonIcon = new ImageIcon("images/little.gif");
            JLabel label1 = new JLabel("Image and Text", middleButtonIcon, JLabel.CENTER);
            bclosed = new JButton(closedIcon);
            bclosed.setBorder(null);
            bclosed.setToolTipText("closed");
            bclosed.setActionCommand("closed");
            b2 = new JButton("Middle button", middleButtonIcon);
            b2.setText("Middle button");
            b2.setVerticalTextPosition(AbstractButton.BOTTOM);
            b2.add(bclosed, -1);
            b2.setIcon(middleButtonIcon);
            b2.setHorizontalTextPosition(AbstractButton.LEFT);
            b2.setAlignmentX(LEFT_ALIGNMENT);
            b2.setMnemonic(KeyEvent.VK_M);
            bclosed.addActionListener(this);
            b2.setToolTipText("This middle button does nothing when you click it.");
            //Add Components to this container, using the default FlowLayout.
            add(label1);
            add(b2);
        public void actionPerformed(ActionEvent e) {
            if ("disable".equals(e.getActionCommand())) {
                b2.setEnabled(!b2.isEnabled());
            if             ("closed".equals(e.getActionCommand())) {
                  System.out.println("OK closed is pressed");
                  remove(b2);
        private static void createAndShowGUI() {
            //Create and set up the window.
            JFrame frame = new JFrame("ButtonDemo");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //Create and set up the content pane.
            ButtonDemo2 newContentPane = new ButtonDemo2();
            newContentPane.setOpaque(true); //content panes must be opaque
            frame.setContentPane(newContentPane);
            //Display the window.
            frame.pack();
            frame.setVisible(true);
        public static void main(String[] args) {
            //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
    }But I cannot see the First Image I add in b2 such as little.gif and "Image and Text" on it, only I can see bclosed icon.
    what is wrong here??
    Thanks a lot
    Good weekend

  • Setenabled works but not on panel initialization

    I have a panel with several components.
    I have 2 radio buttons that control some logic, and depending on which radio button is selected, different components are enabled
    I have a listener that fires for the radio buttons, and the application seems to work correctly at run time,
    so that the right conmponents do get enabled and disabled when the buttons are manually clicked.
    My problem though is that I need to set which one is enabled by default upon initialization,
    but calling setEnabled(false) does not seem to have any effect in my initialization code,
    but it does work when called from the listeners when each radio button is clicked.
    I dont have a easy example to post as the class is pretty big...
    I'm just checking if there is anything obvious to look for?
    Edited by: dingfelder on Apr 1, 2008 11:38 AM

    For instance, this is an SSCCE of sorts that does nothing but enables and disables JPanels on pressing a JRadioButton. It defaults to the middle button being selected:
    import java.awt.Component;
    import java.awt.GridLayout;
    import javax.swing.BorderFactory;
    import javax.swing.BoxLayout;
    import javax.swing.ButtonGroup;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JRadioButton;
    import javax.swing.event.ChangeEvent;
    import javax.swing.event.ChangeListener;
    class FuSwing1 extends JPanel
        private static final int BTN_COUNT = 3;
        private JRadioButton[] rBtns = new JRadioButton[BTN_COUNT];
        private JPanel[] btnPnls = new JPanel[BTN_COUNT];
        FuSwing1()
            setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
            ButtonGroup btnGrp = new ButtonGroup();
            for (int i = 0; i < rBtns.length; i++)
                rBtns[i] = new JRadioButton("Radio Button " + (i + 1));
                btnGrp.add(rBtns);
    JPanel panel = new JPanel();
    panel.add(rBtns[i]);
    btnPnls[i] = createBtnPanel();
    if (i == BTN_COUNT / 2) // select middle button on startup
    btnPnls[i].setEnabled(true);
    rBtns[i].setSelected(true);
    else
    btnPnls[i].setEnabled(false);
    btnPnls[i].setBorder(BorderFactory.createTitledBorder("Button Panel " + (i + 1)));
    panel.add(btnPnls[i]);
    final int index = i;
    rBtns[i].addChangeListener(new ChangeListener()
    public void stateChanged(ChangeEvent e)
    JRadioButton rBtn = (JRadioButton)e.getSource();
    if (rBtn.isSelected())
    btnPnls[index].setEnabled(true);
    else
    btnPnls[index].setEnabled(false);
    add(panel);
    private JPanel createBtnPanel()
    JPanel bp = new JPanel()
    @Override // since panels don't disable children by default
    public void setEnabled(boolean enabled)
    Component[] components = getComponents();
    for (Component component : components)
    component.setEnabled(enabled);
    super.setEnabled(enabled);
    bp.setLayout(new GridLayout(0, 2, 20, 20));
    for (int i = 0; i < 4; i++)
    JButton btn = new JButton("Button " + i);
    bp.add(btn);
    return bp;
    private static void createAndShowGUI()
    JFrame frame = new JFrame("FuSwing1 Application");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().add(new FuSwing1());
    frame.pack();
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
    public static void main(String[] args)
    javax.swing.SwingUtilities.invokeLater(new Runnable()
    public void run()
    createAndShowGUI();

  • Problem AbstractAction - JButton.setRolloverIcon()

    Hi,
    Since i (and i don't understand why) couldn't really find anything in google, or in this forum search, i'm requesting you guys' help
    Here's a brief description of the problem:
    When just using a JButton (with some text on it), without any Actions assigned to it, it's no problem at all to assign a disabledIcon, rolloverIcon (setDisabledIcon, setRolloverIcon) to the button.
    BUT
    once you apply an action class to it (in my case i'm extending my action class from AbstractAction), things go wrong:
    - Apparently, you CAN pass on an Icon (the default icon on the image) to the action class, and then calling the super(String command, Icon icon) constructor.
    - But how to set a disabledIcon or rolloverIcon using this action class ? You can't pass this on the the super constructor like the default icon. I'm really not seeing what i 'm doing wrong here :-(
    Thanks in advance for your replies and help,
    Regards,
    Sander
    PS: i'm new to this forum, if i'm giving you guys to little information, please let me know.

    but using action isn't the best idea. The benefit of using an Action is that it can be shared by multiple components. A typical GUI design would have a menu item and a toolbar button to invoke the same action. The coding is easy:
    Action someAction = new SomeAction(...);
    JMenuItem someItem = new JMenuItem( someAction );
    JButton someButton = new JButton( someAction );
    If you ever need to disable the Action you would do:
    someAction.setEnable( false );
    and the menu item and toolbar button would both be updated.

Maybe you are looking for

  • Material Ledger - confirmation in different months

    Hi Gurus, I have a problem as follows: We are using material ledger for actual costing. When we post partial confirmation for a production order in period t, goods receipt and goods issue is posted for period t. However, in some cases, confirmation i

  • Archiving ZIP files in SAP

    Hi all, I have the following requirements : 1.Archive the ZIP file(containing a couple of files) into the IXOS content server, using a  ABAP function call. 2.Attach the ZIPped file into a invoice document in SAP. Any ideas on how to proceed ?

  • History columns in  custom security setting

    Hi JDeveloper 11.1.2.2.0 JHeadstart 11.1.2.1.28 Authentication type = Custom Authorisation type = Custom i changed the base class of application module in my model project to (oracle.jheadstart.model.adfbc.v2.JhsApplicationModuleImpl) and i add , in

  • Problem in the Function module

    Dear All,         I am using the ECC 6.0 with all the service packs applied. when i am creating a function module, i am getting an error like " Tables parameters are obsolete". My requirement is to get the internal table structure what should i do???

  • Ipad Photo App

    Almost everything i try to view my photos i can look at them for a few seconds but then the ipad restarts itself.. is this a default that a lot of people have or should i try get it fixed by apple?