JButton Label

hi
I'm trying to assign a lable in arabic language for a JButton but the label appears as question marks. how can i change the character encoding to UTF-8 or AMERICAN_AMERICA.AR8MSWIN1256
please help me
thanx

Call JButton.setFont with a font that has characters for those Unicode characters.

Similar Messages

  • JButton labels.

    Is there any way to meake the label on a button invisible, without removing it. I have a number of buttons, but the action Listener for them is in a different class. So at present Im using (ActionEvent) e.getActionCommabd() to return the label of the button that caused it, and working from that, which is fine. Except, I don't want the labels appearing on my application....

    Because Im using the labels to determine which button
    was pressed, and therefore take the appropriate
    action. using setText("") will set my label as "" and
    so my action listener won't know what action to
    take...
    I need to either, hide the text, without removing the
    label. Or, have a different method for the
    actionlistener to decide what to do... I know
    e.getSource() will return the source of
    the action event, but i don't know how to work from
    that...Read Through the API docs more on ActionListener especially setActionCommand
    then do something like this:
                         JButton blankButton = new JButton();
                         blankButton.setActionCommand("ChosenActionCommand");
                         blankButton.addActionListener( this ); // or however you are doing it
                         this.add( blankButton );
                       public void actionPerformed( ActionEvent event )
                                       String s = event.getActionCommand();
                                       if( s.equals( "ChosenActionCommand") )
                                                     doStuff();
                                      else
                                                  //blah blah
                      }

  • JButton label disappear after adding action

    Hello
    I have a problem, when I add an action (button.setAction(..)) to my JButton, the label on button disappeared.
    I tried to resize the button with setMinimumSize() but it didn't work.
    Could somebody help me?
    Regards

    You need to provide a "name" value when you create the Action.
    Read the section from the Swing tutorial on [How to Use Actions|http://java.sun.com/docs/books/tutorial/uiswing/TOC.html].

  • JButton not visible after use of Jpanel removeAll ..

    Hi!
    I'm having a calculator class that inherits JFrame. I need to add more buttons after setting an option from the (view) menu bar .. (from normal to scientific calculator). I needed to use the JPanel removeAll method and then add the normal buttons plus extra buttons. But the problem is, that the Buttons are only visible when I touch them with the mouse.
    Does anybody know why? Thanks for your help!
    See code below (still in construction phase):
    Name: Hemanth. B
    Original code from Website: java-swing-tutorial.html
    Topic : A basic Java Swing Calculator
    Conventions Used in Source code
         1. All JLabel components start with jlb*
         2. All JPanel components start with jpl*
         3. All JMenu components start with jmenu*
         4. All JMenuItem components start with jmenuItem*
         5. All JDialog components start with jdlg*
         6. All JButton components start with jbn*
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Calculator extends JFrame
    implements ActionListener {
    // Constants
    final int NORMAL = 0;
    final int SCIENTIFIC = 8;
    final int MAX_INPUT_LENGTH = 20;
    final int INPUT_MODE = 0;
    final int RESULT_MODE = 1;
    final int ERROR_MODE = 2;
    // Variables
    int displayMode;
    int calcType = SCIENTIFIC;
    boolean clearOnNextDigit, percent;
    double lastNumber;
    String lastOperator, title;
    private JMenu jmenuFile, jmenuView, jmenuHelp;
    private JMenuItem jmenuitemExit, jmenuitemAbout;
    private JRadioButtonMenuItem jmenuItemNormal = new JRadioButtonMenuItem("Normal");
    private JRadioButtonMenuItem jmenuItemScientific = new JRadioButtonMenuItem("Scientific");
    private     ButtonGroup viewMenuButtonGroup = new ButtonGroup();
    private JLabel jlbOutput;
    private JButton jbnButtons[];
    private JPanel jplButtons, jplMaster, jplBackSpace, jplControl;
    * Font(String name, int style, int size)
    Creates a new Font from the specified name, style and point size.
    Font f12 = new Font("Verdana", 0, 12);
    Font f121 = new Font("Verdana", 1, 12);
    // Constructor
    public Calculator(String title) {
    /* Set Up the JMenuBar.
    * Have Provided All JMenu's with Mnemonics
    * Have Provided some JMenuItem components with Keyboard Accelerators
         //super(title);
         this.title = title;
         //displayCalculator(title);
    }     //End of Contructor Calculator
    private void displayCalculator (String title) {
         //add WindowListener for closing frame and ending program
         addWindowListener (
         new WindowAdapter() {     
         public void windowClosed(WindowEvent e) {
         System.exit(0);
         //setResizable(false);
    //Set frame layout manager
         setBackground(Color.gray);
         validate();
         createMenuBar();
         createMasterPanel();      
         createDisplayPanel();
         clearAll();
         this.getContentPane().validate();
         requestFocus();
         pack();
         //getContentPane().
         setVisible(true);
    private void createMenuBar() {
    jmenuFile = new JMenu("File");
    jmenuFile.setFont(f121);
    jmenuFile.setMnemonic(KeyEvent.VK_F);
    jmenuitemExit = new JMenuItem("Exit");
    jmenuitemExit.setFont(f12);
    jmenuitemExit.setAccelerator(KeyStroke.getKeyStroke( KeyEvent.VK_X,
                                            ActionEvent.CTRL_MASK));
    jmenuFile.add(jmenuitemExit);
    jmenuView = new JMenu("View");
    jmenuFile.setFont(f121);
    jmenuFile.setMnemonic(KeyEvent.VK_W);
    jmenuItemNormal.setMnemonic(KeyEvent.VK_N);
    viewMenuButtonGroup.add(jmenuItemNormal);
    jmenuView.add(jmenuItemNormal);
    jmenuItemScientific.setMnemonic(KeyEvent.VK_S);
    viewMenuButtonGroup.add(jmenuItemScientific);
    jmenuView.add(jmenuItemScientific);
    if (jmenuItemNormal.isSelected() == false &&
    jmenuItemScientific.isSelected() == false)
    jmenuItemScientific.setSelected(true);
         jmenuHelp = new JMenu("Help");
         jmenuHelp.setFont(f121);
         jmenuHelp.setMnemonic(KeyEvent.VK_H);
         jmenuitemAbout = new JMenuItem("About Calculator");
         jmenuitemAbout.setFont(f12);
         jmenuHelp.add(jmenuitemAbout);
         JMenuBar menubar = new JMenuBar();
         menubar.add(jmenuFile);
         menubar.add(jmenuView);
         menubar.add(jmenuHelp);
         setJMenuBar(menubar);
         jmenuItemNormal.addActionListener(this);
         jmenuItemScientific.addActionListener(this);
         jmenuitemAbout.addActionListener(this);
         jmenuitemExit.addActionListener(this);
    private void createDisplayPanel() {
         if (jlbOutput != null) {
         jlbOutput.removeAll();     
         jlbOutput = new JLabel("0",JLabel.RIGHT);
         jlbOutput.setBackground(Color.WHITE);
         jlbOutput.setOpaque(true);
         // Add components to frame
         getContentPane().add(jlbOutput, BorderLayout.NORTH);
         jlbOutput.setVisible(true);
    private void createMasterPanel() {
         if (jplMaster != null) {
         jplMaster.removeAll();     
         jplMaster = new JPanel(new BorderLayout());
         createCalcButtons();      
         jplMaster.add(jplBackSpace, BorderLayout.WEST);
         jplMaster.add(jplControl, BorderLayout.EAST);
         jplMaster.add(jplButtons, BorderLayout.SOUTH);
         ((JPanel)getContentPane()).revalidate();
         // Add components to frame
         getContentPane().add(jplMaster, BorderLayout.SOUTH);
         jplMaster.setVisible(true);
    private void createCalcButtons() {
         int rows = 4;
         int cols = 5 + calcType/rows;
         jbnButtons = new JButton[31];
         // Create numeric Jbuttons
         for (int i=0; i<=9; i++) {
         // set each Jbutton label to the value of index
         jbnButtons[i] = new JButton(String.valueOf(i));
         // Create operator Jbuttons
         jbnButtons[10] = new JButton("+/-");
         jbnButtons[11] = new JButton(".");
         jbnButtons[12] = new JButton("=");
         jbnButtons[13] = new JButton("/");
         jbnButtons[14] = new JButton("*");
         jbnButtons[15] = new JButton("-");
         jbnButtons[16] = new JButton("+");
         jbnButtons[17] = new JButton("sqrt");
         jbnButtons[18] = new JButton("1/x");
         jbnButtons[19] = new JButton("%");
         jplBackSpace = new JPanel();
         jplBackSpace.setLayout(new GridLayout(1, 1, 2, 2));
         jbnButtons[20] = new JButton("Backspace");
         jplBackSpace.add(jbnButtons[20]);
         jplControl = new JPanel();
         jplControl.setLayout(new GridLayout(1, 2, 2 ,2));
         jbnButtons[21] = new JButton(" CE ");
         jbnButtons[22] = new JButton("C");
         jplControl.add(jbnButtons[21]);
         jplControl.add(jbnButtons[22]);
         //if (calcType == SCIENTIFIC) {     
         jbnButtons[23] = new JButton("s");
         jbnButtons[24] = new JButton("t");
         jbnButtons[25] = new JButton("u");
         jbnButtons[26] = new JButton("v");
         jbnButtons[27] = new JButton("w");
         jbnButtons[28] = new JButton("x");
         jbnButtons[29] = new JButton("y");
         jbnButtons[30] = new JButton("z");
    // Setting all Numbered JButton's to Blue. The rest to Red
         for (int i=0; i<jbnButtons.length; i++)     {
         //activate ActionListener
         System.out.println("add action listener: " + i);
         jbnButtons.addActionListener(this);
         //set button text font/colour
         jbnButtons[i].setFont(f12);
         jbnButtons[i].invalidate();
         if (i<10)
              jbnButtons[i].setForeground(Color.blue);               
         else
              jbnButtons[i].setForeground(Color.red);
         // container for Jbuttons
         jplButtons = new JPanel(new GridLayout(rows, cols, 2, 2));
    System.out.println("Cols: " + cols);      
         //Add buttons to keypad panel starting at top left
         // First row
         // extra left buttons for scientific
         if (calcType == SCIENTIFIC) {
         System.out.println("Adding Scientific buttons");
         setSize(400, 217);
         setLocation(200, 250);
         jplButtons.add(jbnButtons[23]);
         jplButtons.add(jbnButtons[27]);
         } else {
         setSize(241, 217);
         setLocation(200, 250);
         for(int i=7; i<=9; i++)          {
         jplButtons.add(jbnButtons[i]);
         // add button / and sqrt
         jplButtons.add(jbnButtons[13]);
         jplButtons.add(jbnButtons[17]);
         // Second row
         // extra left buttons for scientific
         if (calcType == SCIENTIFIC) {
         System.out.println("Adding Scientific buttons");
         jplButtons.add(jbnButtons[24]);
         jplButtons.add(jbnButtons[28]);
         for(int i=4; i<=6; i++)     {
         jplButtons.add(jbnButtons[i]);
         // add button * and x^2
         jplButtons.add(jbnButtons[14]);
         jplButtons.add(jbnButtons[18]);
         // Third row
         // extra left buttons for scientific
         if (calcType == SCIENTIFIC) {
         System.out.println("Adding Scientific buttons");
         jplButtons.add(jbnButtons[25]);
         jplButtons.add(jbnButtons[29]);
         for( int i=1; i<=3; i++) {
         jplButtons.add(jbnButtons[i]);
         //adds button - and %
         jplButtons.add(jbnButtons[15]);
         jplButtons.add(jbnButtons[19]);
         //Fourth Row
         // extra left buttons for scientific
         if (calcType == SCIENTIFIC) {
         System.out.println("Adding Scientific buttons");
         jplButtons.add(jbnButtons[26]);
         jplButtons.add(jbnButtons[30]);
         // add 0, +/-, ., +, and =
         jplButtons.add(jbnButtons[0]);
         jplButtons.add(jbnButtons[10]);
         jplButtons.add(jbnButtons[11]);
         jplButtons.add(jbnButtons[16]);
         jplButtons.add(jbnButtons[12]);
         jplButtons.revalidate();
    // Perform action
    public void actionPerformed(ActionEvent e){
         double result = 0;
         if(e.getSource() == jmenuitemAbout) {
         //JDialog dlgAbout = new CustomABOUTDialog(this,
         //                              "About Java Swing Calculator", true);
         //dlgAbout.setVisible(true);
         } else if(e.getSource() == jmenuitemExit) {
         System.exit(0);
    if (e.getSource() == jmenuItemNormal) {
    calcType = NORMAL;
    displayCalculator(title);
    if (e.getSource() == jmenuItemScientific) {
    calcType = SCIENTIFIC;
    displayCalculator(title);
    System.out.println("Calculator is set to "
    + (calcType == NORMAL?"Normal":"Scientific") + " :" + jbnButtons.length);      
         // Search for the button pressed until end of array or key found
         for (int i=0; i<jbnButtons.length; i++)     {
         if(e.getSource() == jbnButtons[i]) {
              System.out.println(i);
              switch(i) {
              case 0:
                   addDigitToDisplay(i);
                   break;
              case 1:
                   System.out.println("1");
                   addDigitToDisplay(i);
                   break;
              case 2:
                   addDigitToDisplay(i);
                   break;
              case 3:
                   addDigitToDisplay(i);
                   break;
              case 4:
                   addDigitToDisplay(i);
                   break;
              case 5:
                   addDigitToDisplay(i);
                   break;
              case 6:
                   addDigitToDisplay(i);
                   break;
              case 7:
                   addDigitToDisplay(i);
                   break;
              case 8:
                   addDigitToDisplay(i);
                   break;
              case 9:
                   addDigitToDisplay(i);
                   break;
              case 10:     // +/-
                   processSignChange();
                   break;
              case 11:     // decimal point
                   addDecimalPoint();
                   break;
              case 12:     // =
                   processEquals();
                   break;
              case 13:     // divide
                   processOperator("/");
                   break;
              case 14:     // *
                   processOperator("*");
                   break;
              case 15:     // -
                   processOperator("-");
                   break;
              case 16:     // +
                   processOperator("+");
                   break;
              case 17:     // sqrt
                   if (displayMode != ERROR_MODE) {
                   try {
                        if (getDisplayString().indexOf("-") == 0)
                        displayError("Invalid input for function!");
                        result = Math.sqrt(getNumberInDisplay());
                        displayResult(result);
                   catch(Exception ex) {
                        displayError("Invalid input for function!");
                        displayMode = ERROR_MODE;
                   break;
              case 18:     // 1/x
                   if (displayMode != ERROR_MODE){
                   try {
                        if (getNumberInDisplay() == 0)
                        displayError("Cannot divide by zero!");
                        result = 1 / getNumberInDisplay();
                        displayResult(result);
                   catch(Exception ex) {
                        displayError("Cannot divide by zero!");
                        displayMode = ERROR_MODE;
                   break;
              case 19:     // %
                   if (displayMode != ERROR_MODE){
                   try {
                        result = getNumberInDisplay() / 100;
                        displayResult(result);
                   catch(Exception ex) {
                        displayError("Invalid input for function!");
                        displayMode = ERROR_MODE;
                   break;
              case 20:     // backspace
                   if (displayMode != ERROR_MODE) {
                   setDisplayString(getDisplayString().substring(0,
                   getDisplayString().length() - 1));
                   if (getDisplayString().length() < 1)
                        setDisplayString("0");
                   break;
              case 21:     // CE
                   clearExisting();
                   break;
              case 22:     // C
                   clearAll();
                   break;
    void setDisplayString(String s) {
         jlbOutput.setText(s);
    String getDisplayString () {
         return jlbOutput.getText();
    void addDigitToDisplay(int digit) {
         if (clearOnNextDigit)
         setDisplayString("");
         String inputString = getDisplayString();
         if (inputString.indexOf("0") == 0) {
         inputString = inputString.substring(1);
         if ((!inputString.equals("0") || digit > 0)
                             && inputString.length() < MAX_INPUT_LENGTH) {
         setDisplayString(inputString + digit);
         displayMode = INPUT_MODE;
         clearOnNextDigit = false;
    void addDecimalPoint() {
         displayMode = INPUT_MODE;
         if (clearOnNextDigit)
         setDisplayString("");
         String inputString = getDisplayString();
         // If the input string already contains a decimal point, don't
         // do anything to it.
         if (inputString.indexOf(".") < 0)
         setDisplayString(new String(inputString + "."));
    void processSignChange() {
         if (displayMode == INPUT_MODE) {
         String input = getDisplayString();
         if (input.length() > 0 && !input.equals("0"))     {
              if (input.indexOf("-") == 0)
              setDisplayString(input.substring(1));
              else
              setDisplayString("-" + input);
         } else if (displayMode == RESULT_MODE) {
         double numberInDisplay = getNumberInDisplay();
         if (numberInDisplay != 0)
         displayResult(-numberInDisplay);
    void clearAll() {
         setDisplayString("0");
         lastOperator = "0";
         lastNumber = 0;
         displayMode = INPUT_MODE;
         clearOnNextDigit = true;
    void clearExisting() {
         setDisplayString("0");
         clearOnNextDigit = true;
         displayMode = INPUT_MODE;
    double getNumberInDisplay()     {
         String input = jlbOutput.getText();
         return Double.parseDouble(input);
    void processOperator(String op) {
         if (displayMode != ERROR_MODE) {
         double numberInDisplay = getNumberInDisplay();
         if (!lastOperator.equals("0")) {
              try {
              double result = processLastOperator();
              displayResult(result);
              lastNumber = result;
              catch (DivideByZeroException e)     {
              displayError("Cannot divide by zero!");
         } else {
         lastNumber = numberInDisplay;
         clearOnNextDigit = true;
         lastOperator = op;
    void processEquals() {
         double result = 0;
         if (displayMode != ERROR_MODE){
         try {
              result = processLastOperator();
              displayResult(result);
         catch (DivideByZeroException e) {
              displayError("Cannot divide by zero!");
         lastOperator = "0";
    double processLastOperator() throws DivideByZeroException {
         double result = 0;
         double numberInDisplay = getNumberInDisplay();
         if (lastOperator.equals("/")) {
         if (numberInDisplay == 0)
              throw (new DivideByZeroException());
         result = lastNumber / numberInDisplay;
         if (lastOperator.equals("*"))
         result = lastNumber * numberInDisplay;
         if (lastOperator.equals("-"))
         result = lastNumber - numberInDisplay;
         if (lastOperator.equals("+"))
         result = lastNumber + numberInDisplay;
         return result;
    void displayResult(double result){
         setDisplayString(Double.toString(result));
         lastNumber = result;
         displayMode = RESULT_MODE;
         clearOnNextDigit = true;
    void displayError(String errorMessage){
         setDisplayString(errorMessage);
         lastNumber = 0;
         displayMode = ERROR_MODE;
         clearOnNextDigit = true;
    public static void main(String args[]) {
         Calculator calci = new Calculator("My Calculator");
         calci.displayCalculator("My Calculator");
    System.out.println("Exitting...");
    }     //End of Swing Calculator Class.
    class DivideByZeroException extends Exception{
    public DivideByZeroException() {
         super();
    public DivideByZeroException(String s) {
         super(s);
    class CustomABOUTDialog extends JDialog implements ActionListener {
    JButton jbnOk;
    CustomABOUTDialog(JFrame parent, String title, boolean modal){
         super(parent, title, modal);
         setBackground(Color.black);
         JPanel p1 = new JPanel(new FlowLayout(FlowLayout.CENTER));
         StringBuffer text = new StringBuffer();
         text.append("Calculator Information\n\n");
         text.append("Developer:     Hemanth\n");
         text.append("Version:     1.0");
         JTextArea jtAreaAbout = new JTextArea(5, 21);
         jtAreaAbout.setText(text.toString());
         jtAreaAbout.setFont(new Font("Times New Roman", 1, 13));
         jtAreaAbout.setEditable(false);
         p1.add(jtAreaAbout);
         p1.setBackground(Color.red);
         getContentPane().add(p1, BorderLayout.CENTER);
         JPanel p2 = new JPanel(new FlowLayout(FlowLayout.CENTER));
         jbnOk = new JButton(" OK ");
         jbnOk.addActionListener(this);
         p2.add(jbnOk);
         getContentPane().add(p2, BorderLayout.SOUTH);
         setLocation(408, 270);
         setResizable(false);
         addWindowListener(new WindowAdapter() {
              public void windowClosing(WindowEvent e) {
                   Window aboutDialog = e.getWindow();
                   aboutDialog.dispose();
         pack();
    public void actionPerformed(ActionEvent e) {
         if(e.getSource() == jbnOk) {
         this.dispose();
    Message was edited by:
    dungorg

    Swing related questions should be posted in the Swing forum.
    After adding or removing components from a visible panel you need to use panel.revalidate() and sometimes panel.repaint();
    If you need further help then you need to create a [url http://homepage1.nifty.com/algafield/sscce.html]Short, Self Contained, Compilable and Executable, Example Program (SSCCE) that demonstrates the incorrect behaviour, because I can't guess exactly what you are doing based on the information provided.
    Don't forget to use the [url http://forum.java.sun.com/help.jspa?sec=formatting]Code Formatting Tags so the posted code retains its original formatting.

  • Open a UNIX terminal (with a remote login session) on JButton click

    All,
    -- The domain of this problem blurs the line which decides if this question has to be posed on a Java swing audience or a UNIX forum. To understand this problem apart from being a Java swing person, you would also need to have a basic understanding of UNIX concepts such as gnome-terminal, xterm and rsh --
    I am creating a network monitoring GUI which has a JTable having many entries that pertains to various system information about nodes in a network. I have overridden the default cellEditor in the table with a custom TableCellEditor (camickr's archive) and have a column containing JButtons labelled with hostnames.
    Now, when a user clicks on any of these buttons, I would like to open up a terminal (xterm or /usr/bin/gnome-terminal) followed by executing some commands on this NEW terminal shell. In other words, I would like to automate this process as if the user opens a terminal and then keys in commands to rsh into the remote host by specifying the hostname (which is the label on the JButton) and finally provide the user with this state, from where on she takes control on that remote login session.
    I tried searching through various previous posts. I did find a related one:
    http://forum.java.sun.com/thread.jspa?threadID=5180094&messageID=9699614#9699614
    But I still have difficulty in getting my problem solved.
    The following statements are executed when one such button (labelled by a hostname) is clicked:
    public void actionPerformed(ActionEvent e) {
             String hostname = e.getActionCommand();
                fireEditingStopped();
                System.out.println( "probing:  " + hostname); //This appears correctly on the console
                Process p;
                   try {
                        p = Runtime.getRuntime().exec("/usr/bin/gnome-terminal");
                        BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
                        BufferedWriter out = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
                                    out.write("rsh -l root "+hostname); //attempting to remote login in the NEW shell (terminal)..... I guess :|
                   } catch (IOException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
    .I guess I am not having control on the new terminal. Is there any way I could control the newly spawned shell?
    Appreciate,
    Rajiv

    Alright...
    assuming gnome-terminal is in /usr/bin path,
    /usr/bin/gnome-terminal -e "<command>"
    would solve this problem

  • JApplet, JButtons (Desperate)

    Create a JApplet which displays a smiley face (with eyes and mouth) upon startup. Provide two JButtons, labeled "Change Expression" and "Change Color". The "Change Expression" button should cause the face to toggle between a smile and a frown.The "Change Color" button should toggle the fill color of the face between two different colors of your choice, or randomly-generated colors.
    Please, can anyone help with this? I welcome any and all help.
    Thanks
    Jewel24

    Kaj, It is Homework. I think that if I could just get this part to get me started. That would be a big help. Create a JApplet which displays a smiley face (with eyes and mouth) upon startup

  • Need help with search function in my program

    Hello all, some of you may remeber me from my previous inventory programs. Well I am finally on my last one and I need to add a search option to the code. Here is the class that will contain that option.
    import java.util.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    public class Inventory2 extends JFrame implements ActionListener {
    //Utility class for displaying the picture
    //If we are going to use a class/method/variable inside that class only, we declare it private in that class
    private class MyPanel extends JPanel {
    ImageIcon image = new ImageIcon("Sample.jpg");
    int width = image.getIconWidth();
    int height = image.getIconHeight();
    long angle = 30;
    public MyPanel(){
    super();
    public void paintComponent(Graphics g){
         super.paintComponent(g);
         Graphics2D g2d = (Graphics2D)g;
         g2d.rotate (Math.toRadians(angle), 60+width/2, 60+height/2);
         g2d.drawImage(image.getImage(), 60, 60, this);
         g2d.dispose();
    }//end class MyPanel
    int currentIndex; //Currently displayed Item
    Product[] supplies = new Product[4];
    JLabel name ;
    JLabel number;
    JLabel rating;
    JLabel quantity;
    JLabel price;
    JLabel fee;
    JLabel totalValue;
    JTextField nameField = new JTextField(20);
    JTextField numberField = new JTextField(20);
    JTextField ratingField = new JTextField(20);
    JTextField quantityField = new JTextField(20);
    JTextField priceField = new JTextField(20);
    JPanel display;
    JPanel displayHolder;
    JPanel panel;
    boolean locked = false; //Notice how I've used this flag to keep the interface clean
    public Inventory2() {
    makeTheDataItems();
    setSize(700, 500);
    setTitle("Inventory Program");
    //make the panels
    display = new JPanel();
    JPanel other = new JPanel();
    other.setLayout(new GridLayout(2, 1));
    JPanel picture = new MyPanel();
    JPanel buttons = new JPanel();
    JPanel centerPanel = new JPanel();
    displayHolder = new JPanel();
    display.setLayout(new GridLayout(7, 1));
    //other.setLayout(new GridLayout(1, 1));
    //make the labels
    name = new     JLabel("Name :");
    number = new JLabel("Number :");
    rating = new JLabel("Rating     :");
    quantity = new JLabel("Quantity :");
    price = new JLabel("Price     :");
    fee = new JLabel("Restocking Fee (5%) :");
    totalValue = new JLabel("Total Value :");
    //Use the utility method to make the buttons
    JButton first = makeButton("First");
    JButton next = makeButton("Next");
    JButton previous = makeButton("Previous");
    JButton last = makeButton("Last");
    JButton search = makeButton("Search");
    //Other buttons
    JButton add = makeButton("Add");
    JButton modify = makeButton("Modify");
    JButton delete = makeButton("Delete");
    JButton save = makeButton("Save");
    JButton exit = makeButton("Exit");
    //Add the labels to the display panel
    display.add(name);
    display.add(number);
    display.add(rating);
    display.add(quantity);
    display.add(price);
    display.add(fee);
    //add the buttons to the buttonPanel
    buttons.add(first);
    buttons.add(previous);
    buttons.add(next);
    buttons.add(last);
    buttons.add(search);
    //Add the picture panel and display to the centerPanel
    displayHolder.add(display);
    centerPanel.setLayout(new GridLayout(2, 1));
    centerPanel.add(picture);
    centerPanel.add(displayHolder);
    other.add(buttons);
    JPanel forAdd = new JPanel(); // add the other buttons to this panel
    forAdd.add(add);
    forAdd.add(modify);
    forAdd.add(delete);
    forAdd.add(save);
    forAdd.add(exit);
    other.add(forAdd);
    //Add the panels to the frame
    getContentPane().add(centerPanel, "Center");
    getContentPane().add(other, "South");
    this.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
    setVisible(true);
    private void makeTheDataItems () {
    Product p1 = new DVD("The one", 001, 200, 100, "The one");
    Product p2 = new DVD("Once upon a time in China V", 002, 500, 10000, "Once upon a time in China V");
    Product p3 = new DVD("Rat Race", 003, 100, 3000, "Rat Race");
    Product p4 = new DVD("The Man in the Iron Mask", 004, 3000, 9000, "The Man in the Iron Mask");
    supplies[0] = p1;
    supplies[1] = p2;
    supplies[2] = p3;
    supplies[3] = p4;
    //Utility method for creating and dressing buttons
    private JButton makeButton(String label) {
    JButton button = new JButton(label);
    button.setPreferredSize(new Dimension(100, 25));
    button.setActionCommand(label);
    button.addActionListener(this);
    return button;
    private void addItem() {
    panel = new JPanel();
    JPanel add = new JPanel();
    add.setLayout(new GridLayout(7, 2));
    JButton addIt = makeButton("Add Item");
    JLabel name = new JLabel("Name :");
    JLabel rating = new JLabel("Rating     :");
    JLabel quantity = new JLabel("Quantity :");
    JLabel price = new JLabel("Price     :");
    add.add(name); add.add(nameField);
    add.add(rating); add.add(ratingField);
    add.add(quantity); add.add(quantityField);
    add.add(price); add.add(priceField);
    panel.add(add);
    JPanel forAddIt = new JPanel();
    forAddIt.add(addIt);
    panel.add(forAddIt);
    displayHolder.remove(display);
    displayHolder.add(panel);
    //display = panel;
    this.setVisible(true);
    public static void main( String args[]) {
    new Inventory2().displayFirst(); //The main method should not have too much code
    } // end main method
    public void actionPerformed(ActionEvent event) {
      String command = event.getActionCommand(); //This retrieves the command that we set for the button
      //Always compare strings using the .equals method and not using ==
      if(command.equals("First")) {
       if(!locked) {
         displayFirst();
      else if(command.equals("Next")) {
       if(!locked) {
         displayNext();
      else if(command.equals("Previous")) {
       if(!locked) {
         displayPrevious();
      else if(command.equals("Last")) {
       if(!locked) {
         displayLast();
      else if(command.equals("Exit")) {
       this.dispose();
       System.exit(0);
      else if(command.equals("Add")) {
       if(!locked) {
         addItem();
         locked = true;
      else if(command.equals("Add Item")) {
       addItemToArray();
      else if(command.equals("Modify")) {
       if(!locked) {
         modify();
         locked = true;
      else if(command.equals("Update")) {
          if(!locked) {
         modifyItemInArray();
         locked = true;
      else if(command.equals("Delete")) {
       if(!locked) {
         DVD dvd = (DVD)supplies[currentIndex];
            int confirm = JOptionPane.showConfirmDialog(this, "Are you sure you want to delete item "+dvd.getItemNumber());
                if(confirm == JOptionPane.YES_OPTION) {
          removeItemAt(currentIndex);
          displayFirst();
    private void modify() {
    DVD dvd = (DVD)supplies[currentIndex];
    panel = new JPanel();
    JPanel add = new JPanel();
    add.setLayout(new GridLayout(7, 2));
    JButton update = makeButton("Update");
    JLabel number = new JLabel("Number :");
    JLabel name = new JLabel("Name :");
    JLabel rating = new JLabel("Rating     :");
    JLabel quantity = new JLabel("Quantity :");
    JLabel price = new JLabel("Price     :");
    add.add(number);
    numberField.setText(""+dvd.getItemNumber()); numberField.setEditable(false); add.add(numberField);
    add.add(name);
    nameField.setText(dvd.getItemName()); add.add(nameField);
    ratingField.setText(dvd.getRating()); ratingField.setEditable(false);
    add.add(rating); add.add(ratingField);
    add.add(quantity);
    quantityField.setText(""+dvd.getStockQuantity());
    add.add(quantityField);
    add.add(price);
    add.add(priceField); priceField.setText(""+dvd.getItemPrice());
    panel.add(add);
    JPanel forAddIt = new JPanel();
    forAddIt.add(update);
    panel.add(forAddIt);
    displayHolder.remove(display);
    displayHolder.add(panel);
    //display = panel;
          this.setVisible(true);
    private void addItemToArray() {
    Product p = new DVD(nameField.getText(), supplies.length + 1, Long.parseLong(quantityField.getText()),
    Double.parseDouble(priceField.getText()), ratingField.getText());
    //Extend size of array by one first
    Product[] ps = new Product[supplies.length + 1];
    for(int i = 0; i < ps.length-1; i++) {
    ps[i] = supplies;
    ps[supplies.length] = p;
    supplies = ps;
    displayHolder.remove(panel);
    displayHolder.add(display);
    displayLast();
    this.setVisible(false);
    this.setVisible(true);
    //Utility method to ease the typing and reuse code
    //This method reduces the number of lines of our code
    private void displayItemAt(int index) {
    DVD product = (DVD)supplies[index];
    name.setText("Item Name: "+ product.getItemName());
    number.setText("Item Number: "+ product.getItemNumber());
    rating.setText("Rating: "+ product.getRating());
    quantity.setText("Quantity In Stock: "+ product.getStockQuantity());
    price.setText("Item Price: "+ product.getItemPrice());
    totalValue.setText("Total: " + product.calculateInventoryValue());
    fee.setText("Restocking Fee (5%) :"+product.calculateRestockFee());
    locked = false;
    this.repaint();
    this.setVisible(true);
    private void modifyItemInArray() {
    Product p = new DVD(nameField.getText(), supplies.length + 1, Long.parseLong(quantityField.getText()),
    Double.parseDouble(priceField.getText()), ratingField.getText());
    supplies[currentIndex] = p;
    displayHolder.remove(panel);
    displayHolder.add(display);
         displayItemAt(currentIndex);
    this.setVisible(false);
    this.setVisible(true);
    private void removeItemAt(int index) {
    Product[] temp = new Product[supplies.length-1];
    int counter = 0;
    for(int i = 0; i < supplies.length;i++) {
    if(i == index) { //skip the item to delete
    else {
         temp[counter++] = supplies[i];
    supplies = temp;
    public void displayFirst() {
    displayItemAt(0);
    currentIndex = 0;
    public void displayNext() {
    if(currentIndex == supplies.length-1) {
    displayFirst();
    currentIndex = 0;
    else {
    displayItemAt(currentIndex + 1);
    currentIndex++;
    public void displayPrevious() {
    if(currentIndex == 0) {
    displayLast();
    currentIndex = supplies.length-1;
    else {
    displayItemAt(currentIndex - 1);
    currentIndex--;
    public void displayLast() {
    displayItemAt(supplies.length-1);
    currentIndex = supplies.length-1;
    }//end class Inventory2
    I am not sure where to put it and how to set it up. If you guys need the other two classes let me know. Thanks in advanced.

    Here are the other two classes:
    import java.util.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    class Product implements Comparable {
    String name;
    int number;
    long stockQuantity;
    double price;
    public Product() {
      name = "";
          number = 0;
          stockQuantity = 0L;
          price = 0.0;
    public Product(String name, int number, long stockQuantity, double price) {
      this.name = name;
          this.number = number;
          this.stockQuantity = stockQuantity;
          this.price = price;
         public void setItemName(String name) {
      this.name = name;
    public String getItemName() {
      return name;
    public void setItemNumber(int number) {
      this.number = number;
    public int getItemNumber() {
      return number;
    public void setStockQuantity(long quantity) {
      stockQuantity = quantity;
    public long getStockQuantity() {
      return stockQuantity;
    public void setItemPrice(double price) {
      this.price = price;
    public double getItemPrice() {
      return price;
    public double calculateInventoryValue() {
      return getItemPrice() * getStockQuantity();
    public int compareTo (Object o) {
      Product p = (Product)o;
      return name.compareTo(p.getItemName());
    public String toString() {
      return "Name :"+getItemName() + "\nNumber"+number+"\nPrice"+price+"\nQuantity"+stockQuantity + "\nValue :"+calculateInventoryValue();
    class DVD extends Product implements Comparable {
    private String rating;
    public DVD() {
      super(); //Call the constructor in Product
      rating = ""; //Add the additonal attribute
    public DVD(String name, int number, long stockQuantity, double price, String rating) {
      super(name, number, stockQuantity, price); //Call the constructor in Product
      this.rating = rating; //Add the additonal attribute
         public void setRating(String rating) {
      this.rating = rating;
    public String getRating() {
      return rating;
    public double calculateInventoryValue() {
      return getItemPrice() * getStockQuantity() + getItemPrice()*getStockQuantity()*0.05;
    public double calculateRestockFee() {
      return getItemPrice() * 0.05;
    public int compareTo (Object o) {
      Product p = (Product)o;
      return getItemName().compareTo(p.getItemName());
    public String toString() {
      return "Name :"+getItemName() + "\nNumber"+getItemNumber()+"\nPrice"+getItemPrice()+"\nQuantity"+getStockQuantity() +"\nRating :"+getRating()+"\nValue"+calculateInventoryValue();
    }You should be able to search through these items, and any other items that have been added to the program.

  • Can anyone help me, please(again)

    Hello :
    I am sorry that my massage is not clearly.
    Please run my coding first, and get some view from my coding. you can see somes buttons are on the frame.
    Now I want to click the number 20 of the buttons, and then I want to display a table which from the class TableRenderDemo to sit under the buttons. I added some coding for this problem in the class DrawClalendar, the coding is indicated by ??.
    but it still can not see the table apear on on the frame with the buttons.
    Can anyone help me to solve this problem.please
    Thanks
    *This program for add some buttons to JPanel
    *and add listeners to each button
    *I want to display myTable under the buttons,
    *when I click on number 20, but why it doesn't
    *work, The coding for these part are indicated by ??????????????
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.GridLayout;
    public class DrawCalendar extends JPanel {
         private static DrawCalendar dC;
         private static TestMain tM;
         private static TableRenderDemo myTable;
         private static GridLayout gL;
         private static final int nlen = 35;
        private static String names[] = new String[nlen];
        private static JButton buttons[] = new JButton[nlen];
         public DrawCalendar(){
              gL=new GridLayout(5,7,0,0);
               setLayout(gL);
               assignValues();
               addJButton();
               registerListener();
        //assign values to each button
           private void assignValues(){
              names = new String[35];
             for(int i = 0; i < names.length; i++)
                names[i] = Integer.toString(i + 1);
         //create buttons and add them to Jpanel
         private void addJButton(){
              buttons=new JButton[names.length];
              for (int i=0; i<names.length; i++){
                   buttons=new JButton(names[i]);
         buttons[i].setBorder(null);
         buttons[i].setBackground(Color.white);
         buttons[i].setFont(new Font ("Palatino", 0,8));
    add(buttons[i]);
    //add listeners to each button
    private void registerListener(){
         for(int i=0; i<35; i++)
              buttons[i].addActionListener(new EventHandler());          
    //I want to display myTable under the buttons,
    //when I click on number 20, but why it doesn't
    //work
    private class EventHandler implements ActionListener{
         public void actionPerformed(ActionEvent e){
         for(int i=0; i<35; i++){
    //I want to display myTable under the buttons,
    //when I click on number 20, but why it doesn't
    //work
         if(i==20){  //???????????               
              tM=new TestMain(); //???????
              tM.c.removeAll(); //??????
              tM.c.add(dC); //???????
              tM.c.add(myTable); //????
              tM.validate();
         if(e.getSource()==buttons[i]){
         System.out.println("testing " + names[i]);
         break;
    *This program create a table with some data
    import javax.swing.table.AbstractTableModel;
    import javax.swing.table.TableColumn;
    import javax.swing.DefaultCellEditor;
    import javax.swing.table.TableCellRenderer;
    import javax.swing.table.DefaultTableCellRenderer;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class TableRenderDemo extends JScrollPane {
    private boolean DEBUG = true;
    public TableRenderDemo() {
    // super("TableRenderDemo");
    MyTableModel myModel = new MyTableModel();
    JTable table = new JTable(myModel);
    table.setPreferredScrollableViewportSize(new Dimension(700, 70));//500,70
    //Create the scroll pane and add the table to it.
    setViewportView(table);
    //Set up column sizes.
    initColumnSizes(table, myModel);
    //Fiddle with the Sport column's cell editors/renderers.
    setUpSportColumn(table.getColumnModel().getColumn(2));
    * This method picks good column sizes.
    * If all column heads are wider than the column's cells'
    * contents, then you can just use column.sizeWidthToFit().
    private void initColumnSizes(JTable table, MyTableModel model) {
    TableColumn column = null;
    Component comp = null;
    int headerWidth = 0;
    int cellWidth = 0;
    Object[] longValues = model.longValues;
    for (int i = 0; i < 5; i++) {
    column = table.getColumnModel().getColumn(i);
    try {
    comp = column.getHeaderRenderer().
    getTableCellRendererComponent(
    null, column.getHeaderValue(),
    false, false, 0, 0);
    headerWidth = comp.getPreferredSize().width;
    } catch (NullPointerException e) {
    System.err.println("Null pointer exception!");
    System.err.println(" getHeaderRenderer returns null in 1.3.");
    System.err.println(" The replacement is getDefaultRenderer.");
    comp = table.getDefaultRenderer(model.getColumnClass(i)).
    getTableCellRendererComponent(
    table, longValues[i],
    false, false, 0, i);
    cellWidth = comp.getPreferredSize().width;
    if (DEBUG) {
    System.out.println("Initializing width of column "
    + i + ". "
    + "headerWidth = " + headerWidth
    + "; cellWidth = " + cellWidth);
    //XXX: Before Swing 1.1 Beta 2, use setMinWidth instead.
    column.setPreferredWidth(Math.max(headerWidth, cellWidth));
    public void setUpSportColumn(TableColumn sportColumn) {
    //Set up the editor for the sport cells.
    JComboBox comboBox = new JComboBox();
    comboBox.addItem("Snowboarding");
    comboBox.addItem("Rowing");
    comboBox.addItem("Chasing toddlers");
    comboBox.addItem("Speed reading");
    comboBox.addItem("Teaching high school");
    comboBox.addItem("None");
    sportColumn.setCellEditor(new DefaultCellEditor(comboBox));
    //Set up tool tips for the sport cells.
    DefaultTableCellRenderer renderer =
    new DefaultTableCellRenderer();
    renderer.setToolTipText("Click for combo box");
    sportColumn.setCellRenderer(renderer);
    //Set up tool tip for the sport column header.
    TableCellRenderer headerRenderer = sportColumn.getHeaderRenderer();
    if (headerRenderer instanceof DefaultTableCellRenderer) {
    ((DefaultTableCellRenderer)headerRenderer).setToolTipText(
    "Click the sport to see a list of choices");
    class MyTableModel extends AbstractTableModel {
    final String[] columnNames = {"First Name",
    "Last Name",
    "Sport",
    "# of Years",
    "Vegetarian"};
    final Object[][] data = {
    {"Mary ", "Campione",
    "Snowboarding", new Integer(5), new Boolean(false)},
    {"Alison", "Huml",
    "Rowing", new Integer(3), new Boolean(true)},
    {"Kathy", "Walrath",
    "Chasing toddlers", new Integer(2), new Boolean(false)},
    {"Sharon", "Zakhour",
    "Speed reading", new Integer(20), new Boolean(true)},
    {"Angela", "Lih",
    "Teaching high school", new Integer(4), new Boolean(false)}
    public final Object[] longValues = {"Angela", "Andrews",
    "Teaching high school",
    new Integer(20), Boolean.TRUE};
    public int getColumnCount() {
    return columnNames.length;
    public int getRowCount() {
    return data.length;
    public String getColumnName(int col) {
    return columnNames[col];
    public Object getValueAt(int row, int col) {
    return data[row][col];
    * JTable uses this method to determine the default renderer/
    * editor for each cell. If we didn't implement this method,
    * then the last column would contain text ("true"/"false"),
    * rather than a check box.
    public Class getColumnClass(int c) {
    return getValueAt(0, c).getClass();
    * Don't need to implement this method unless your table's
    * editable.
    public boolean isCellEditable(int row, int col) {
    //Note that the data/cell address is constant,
    //no matter where the cell appears onscreen.
    if (col < 2) {
    return false;
    } else {
    return true;
    * Don't need to implement this method unless your table's
    * data can change.
    public void setValueAt(Object value, int row, int col) {
    if (DEBUG) {
    System.out.println("Setting value at " + row + "," + col
    + " to " + value
    + " (an instance of "
    + value.getClass() + ")");
    if (data[0][col] instanceof Integer
    && !(value instanceof Integer)) {
    //With JFC/Swing 1.1 and JDK 1.2, we need to create
    //an Integer from the value; otherwise, the column
    //switches to contain Strings. Starting with v 1.3,
    //the table automatically converts value to an Integer,
    //so you only need the code in the 'else' part of this
    //'if' block.
    try {
    data[row][col] = new Integer(value.toString());
    fireTableCellUpdated(row, col);
    } catch (NumberFormatException e) {
    JOptionPane.showMessageDialog(TableRenderDemo.this,
    "The \"" + getColumnName(col)
    + "\" column accepts only integer values.");
    } else {
    data[row][col] = value;
    fireTableCellUpdated(row, col);
    if (DEBUG) {
    System.out.println("New value of data:");
    printDebugData();
    private void printDebugData() {
    int numRows = getRowCount();
    int numCols = getColumnCount();
    for (int i=0; i < numRows; i++) {
    System.out.print(" row " + i + ":");
    for (int j=0; j < numCols; j++) {
    System.out.print(" " + data[i][j]);
    System.out.println();
    System.out.println("--------------------------");
    *This program for add some buttons and a table on JFrame
    import java.awt.*;
    import javax.swing.*;
    public class TestMain extends JFrame{
    private static TableRenderDemo tRD;
         private static TestMain tM;
    protected static Container c;
    private static DrawCalendar dC;
         public static void main(String[] args){
         tM = new TestMain();
         tM.setVisible(true);
         public TestMain(){
         super(" Test");
         setSize(800,600);
    //set up layoutManager
    c=getContentPane();
    c.setLayout ( new GridLayout(3,1));
    tRD=new TableRenderDemo();
    dC=new DrawCalendar();
    addItems();//add Buttons to JFrame
    private void addItems(){
         c.add(dC); //add Buttons to JFrame
         //c.add(tRD); //add Table to JFrame     

    I think this is what you are trying to do. Your code was not very clear so I wrote my own:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import java.text.*;
    public class TableButtons extends JFrame implements ActionListener
         Component southComponent;
        public TableButtons()
              JPanel buttons = new JPanel();
              buttons.setLayout( new GridLayout(5, 7) );
              Dimension buttonSize = new Dimension(20, 20);
              for (int j = 0; j < 35; j++)
                   // this is a trick to convert an integer to a string
                   String label = "" + (j + 1);
                   JButton button = new JButton( label );
                   button.setBorder( null );
                   button.setBackground( Color.white );
                   button.setPreferredSize( buttonSize );
                   button.addActionListener( this );
                   buttons.add(button);
              getContentPane().add(buttons, BorderLayout.NORTH);
         public void actionPerformed(ActionEvent e)
              JButton button = (JButton)e.getSource();
              String command = button.getActionCommand();
              if (command.equals("20"))
                   displayTable();
              else
                   System.out.println("Button " + command + " pressed");
                   if (southComponent != null)
                        getContentPane().remove( southComponent );
                        validate();
                        pack();
                        southComponent = null;
         private void displayTable()
            String[] columnNames = {"Student#", "Student Name", "Gender", "Grade", "Average"};
            Object[][] data =
                {new Integer(1), "Bob",   "M", "A", new Double(85.5) },
                {new Integer(2), "Carol", "F", "B", new Double(77.7) },
                {new Integer(3), "Ted",   "M", "C", new Double(66.6) },
                {new Integer(4), "Alice", "F", "D", new Double(55.5) }
            JTable table = new JTable(data, columnNames);
            table.setPreferredScrollableViewportSize(table.getPreferredSize());
            JScrollPane scrollPane= new JScrollPane( table );
            getContentPane().add(scrollPane, BorderLayout.SOUTH);
            validate();
            pack();
            southComponent = scrollPane;
        public static void main(String[] args)
            TableButtons frame = new TableButtons();
            frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
            frame.pack();
            frame.setVisible(true);
    }

  • Please add keyboard focus events to swing calculator.  Its very argent.

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    A frame with a calculator panel.
    class CalculatorFrame1 extends JFrame
         private static final long serialVersionUID=0;
    public CalculatorFrame1()
    setTitle("Calculator");
    Container contentPane = getContentPane();
    CalculatorPanel panel = new CalculatorPanel();
    contentPane.add(panel);
    pack();
    setVisible(true);
    public static void main(String[] args)
    CalculatorFrame1 frame = new CalculatorFrame1();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //frame.show();
    A panel with calculator buttons and a result display.
    class CalculatorPanel extends JPanel implements KeyListener
    private static final long serialVersionUID=0;
    private JTextField display;
    private JPanel panel;
    private double result;
    private String lastCommand;
    private boolean start;
    public CalculatorPanel()
    setLayout(new BorderLayout());
    result = 0;
    lastCommand = "=";
    start = true;
    // add the display
    display = new JTextField("");
    // display.addKeyListener(this);
    // display.addKeyListener(this);
    add(display, BorderLayout.NORTH);
    display.setFocusable(true);
    ActionListener insert = new InsertAction();
    ActionListener command = new CommandAction();
    // add the buttons in a 4 x 4 grid
    panel = new JPanel();
    panel.setLayout(new GridLayout(5, 4));
    addButton("7", insert);
    addButton("8", insert);
    addButton("9", insert);
    addButton("/", command);
    addButton("4", insert);
    addButton("5", insert);
    addButton("6", insert);
    addButton("*", command);
    addButton("1", insert);
    addButton("2", insert);
    addButton("3", insert);
    addButton("-", command);
    addButton("0", insert);
    addButton(".", insert);
    addButton("=", command);
    addButton("+", command);
    addButton("Clear", command);
    add(panel, BorderLayout.CENTER);
    //this.addKeyListener(this);
    Adds a button to the center panel.
    @param label the button label
    @param listener the button listener
    private void addButton(String label, ActionListener listener)
    JButton button = new JButton(label);
    button.addActionListener(listener);
    panel.add(button);
    This action inserts the button action string to the
    end of the display text.
    private class InsertAction implements ActionListener
    public void actionPerformed(ActionEvent event)
    String input = event.getActionCommand();
    if (start)
    display.setText("");
    start = false;
    display.setText(display.getText() + input);
    This action executes the command that the button
    action string denotes.
    private class CommandAction implements ActionListener
    public void actionPerformed(ActionEvent evt)
    String command = evt.getActionCommand();
    // System.out.println("The value clear"+command);
    if (command.equals("Clear"))
              display.setText("");
              start = false;
    else
    if (start)
    if (command.equals("-"))
    display.setText(command);
    start = false;
    else
    lastCommand = command;
    else
    calculate(Double.parseDouble(display.getText()));
    lastCommand = command;
    start = true;
    Carries out the pending calculation.
    @param x the value to be accumulated with the prior result.
    public void calculate(double x)
    if (lastCommand.equals("+")) result += x;
    else if (lastCommand.equals("-")) result -= x;
    else if (lastCommand.equals("*")) result *= x;
    else if (lastCommand.equals("/")) result /= x;
    else if (lastCommand.equals("=")) result = x;
    display.setText("" + result);
    public void keyTyped(KeyEvent e) {
         //You should only rely on the key char if the event
    //is a key typed event.
         int id = e.getID();
         String keyString="";
         System.out.println("The value KeyEvent.KEY_TYPED"+KeyEvent.KEY_TYPED);
    if (id == KeyEvent.KEY_TYPED) {
    char c = e.getKeyChar();
    //System.out.println("The value c"+c);
    if(c=='*' || c=='/' || c=='-'||c=='+' || c=='=')
         start = true;
    else
         start = false;
         keyString = display.getText()+ c ;
         System.out.println("The value keyString"+keyString);
    else {
    calculate(Double.parseDouble(display.getText()));
    start = true;
    display.setText(keyString);
    public void keyPressed(KeyEvent e) {
         //You should only rely on the key char if the event
    //is a key typed event.
         String keyString;
    int id = e.getID();
    if (id == KeyEvent.KEY_TYPED) {
    char c = e.getKeyChar();
    keyString = "key character = '" + c + "'";
    } else {
    int keyCode = e.getKeyCode();
    keyString = "key code = " + keyCode
    + " ("
    + KeyEvent.getKeyText(keyCode)
    + ")";
    display.setText("keyPressed:::"+keyString);**/
    public void keyReleased(KeyEvent e) {
         //You should only rely on the key char if the event
    //is a key typed event.
         String keyString;
    int id = e.getID();
    if (id == KeyEvent.KEY_TYPED) {
    char c = e.getKeyChar();
    keyString = "key character = '" + c + "'";
    } else {
    int keyCode = e.getKeyCode();
    keyString = "key code = " + keyCode
    + " ("
    + KeyEvent.getKeyText(keyCode)
    + ")";
    display.setText("keyReleased:::"+keyString);**/
    }

    Please state why the question is urgent?
    You where given a suggestion 7 minutes after you posted the question, yet it has been over 2 hours and you have not yet responded indicating whether the suggest helped or not.
    So I gues its really not the urgent after all and therefore I will ignore the question.
    By the way, learn how to use the "Code Formatting Tags" when you post code, so the code you post is actually readable.

  • Calling1.4.1 signed applet from Javascript causes keyboard/focus problems

    Pretty sure there's a JRE bug here, but I'm posting to forums before I open one in case I'm missing something obvious :-)
    This issue may be specific to IE, I haven't tested elsewhere yet. Our web application is centered around a signed applet that is initialized with XML data via Javascript. We first noticed the problem when our users started upgrading from the 1.3.x plug-in to the 1.4.x plug-in. The major symptom was that shortcut keys stopped working. I debugged the problem off and on for about a month before I boiled it down to a very simple program that demonstrates the issue (included below). Basically, the program has a function that adds a JButton to a JPanel and registers a keyboard listener (using the new DefaultKeyboardFocusManager class) that prints a message to the console. This function is called by the applet's init() method, as well as by a public method that can be called from Javascript (called callMeFromJavascript()). I also included a very simple HTML file that provides a button that calls the callMeFromJavascript() method. You can test this out yourself: To recreate, compile the class below, JAR it up, sign the JAR, and put in the same dir with the HTML file. Load the HTML file in IE 5.0 or greater, and bring the console up in a window right next to it. Now click the button that says init--you should see the small box appear inside the button that indicates it has the focus. Now press some keys on your keyboard. You should see "KEY PRESSED!!!" appearing in the console. This is proper behavior. Now click the Init Applet from Javascript button. It has removed the button called init, and added one called "javascript". Press this button. Notice there is no focus occurring. Now press your keyboard. No keyboard events are registered.
    Where is gets interesting is that if you go back and make this an unsigned applet, and try it again, everything works fine. This bug only occurs if the applet is signed.
    Furthermore, if you try it in 1.3, signed or unsigned, it also works. So this is almost certainly a 1.4 bug.
    Anyone disagree? Better yet, anyone have a workaround? I've tried everything I could think of, including launching a thread from the init() method that sets up the components, and then just waits for the data to be set by Javascript. But it seems that ANY communication between the method called by Javascript and the code originating in init() corrupts something and we don't get keyboard events. This bug is killing my users who are very reliant on their shortcut keys for productivity, and we have a somewhat unique user interface that relies on Javascript for initialization. Any help or suggestions are appreciated.
    ================================================================
    Java Applet (Put it in a signed JAR called mainapplet.jar)
    ================================================================
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class MainApplet extends JApplet implements KeyEventDispatcher
        JPanel test;
        public void init()
            System.out.println("init called");
            setUp("init");
        public void callMeFromJavascript()
            System.out.println("callMeFromJavascript called");
            setUp("javascript");
        private void setUp(String label)
            getContentPane().removeAll();
            test = new JPanel();
            getContentPane().add( test );
            JButton button = new JButton(label);
            test.add( button );
            test.updateUI();
            DefaultKeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(this);
        public boolean dispatchKeyEvent(KeyEvent e)
            System.out.println("== KEY PRESSED!!! ==");
            return false;
    }================================================================
    HTML
    ================================================================
    <form>
    <APPLET code="MainApplet" archive="mainapplet.jar" align="baseline" id="blah"
         width="200" height="400">
         No Java 2 SDK, Standard Edition v 1.4.1 support for APPLET!!
    </APPLET>
    <p>
    <input type="button" onClick="document.blah.callMeFromJavascript();" value="Init Applet via Javascript">
    </form>

    I tried adding the requestFocus() line you suggested... Same behavior.
    A good thought, but as I mention in my description, the applet has no trouble gaining the focus initially (when init() is called). From what I have seen, it is only when the call stack has been touched by Javascript that I see problems. This is strange though: Your post gave me the idea of popping the whole panel into a JFrame... I tried it, and the keyboard/focus problem went away! It seems to happen only when the component hierarchy is descended from the JApplet's content pane. So that adds yet another variable: JRE 1.4 + Signed + Javascript + components descended from JApplet content pane.
    And yes, signed or unsigned DOES seem to make a difference. Don't ask me to explain why, but I have run this little applet through quite a few single variable tests (change one variable and see what happens). The same JAR that can't receive keyboard events when signed, works just fine unsigned. Trust me, I'm just as baffled as you are.

  • JApplet does not resize correctly

    Hello,
    I'm trying to practice with JLayeredPane in JApplet.
    The problem is that when i resize the applet JButton b3 is painted "as a background", and still works as a JButton.
    Why doesn't it resize correctly as the other JComponent do?
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class JLayeredPaneDemo extends JApplet {
         public void paint(Graphics g) {
              final JLabel l1 = new JLabel("LABEL 1",JLabel.CENTER);
              final JLabel l2 = new JLabel("LABEL 2",JLabel.CENTER);
              final JLabel l3 = new JLabel("LABEL 3",JLabel.CENTER);
              resize(400,300);
              l1.setOpaque(true);
              l1.setBackground(Color.blue);
              l1.setBorder(BorderFactory.createLineBorder(Color.black,2));
              l2.setOpaque(true);
              l2.setBackground(Color.green);
              l2.setBorder(BorderFactory.createLineBorder(Color.black,2));
              l3.setOpaque(true);
              l3.setBackground(Color.yellow);
              l3.setBorder(BorderFactory.createLineBorder(Color.black,2));
              l1.setBounds(0,0,100,100);
              l2.setBounds(30,30,100,100);
              l3.setBounds(60,60,100,100);
              getLayeredPane().add(l1,new Integer(1));
              getLayeredPane().add(l2,new Integer(2));
              getLayeredPane().add(l3,new Integer(3));
              JButton b1 = new JButton("LABEL 1 ON TOP");
              JButton b2 = new JButton("LABEL 2 ON TOP");
              JButton b3 = new JButton("LABEL 3 ON TOP");
              b1.setBounds(220,0,150,40);
              b2.setBounds(220,40,150,40);
              b3.setBounds(220,80,150,40);
              b1.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        if(getLayeredPane().getLayer(l2)>getLayeredPane().getLayer(l3))
                             getLayeredPane().setLayer(l1,new Integer(getLayeredPane().getLayer(l2)+1));
                        else
                             getLayeredPane().setLayer(l1,new Integer(getLayeredPane().getLayer(l3)+1));
              b2.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        if(getLayeredPane().getLayer(l1)>getLayeredPane().getLayer(l3))
                             getLayeredPane().setLayer(l2,new Integer(getLayeredPane().getLayer(l1)+1));
                        else
                             getLayeredPane().setLayer(l2,new Integer(getLayeredPane().getLayer(l3)+1));
              b3.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        if(getLayeredPane().getLayer(l1)>getLayeredPane().getLayer(l2))
                             getLayeredPane().setLayer(l3,new Integer(getLayeredPane().getLayer(l1)+1));
                        else
                             getLayeredPane().setLayer(l3,new Integer(getLayeredPane().getLayer(l2)+1));
              add(b1);
              add(b2);
              add(b3);
    }If i use the init() method instead of the paint(Graphics g) method JButton b3 is painted as large as possible since the beginning.
    thanx in advance :)

    Swing related questions should be posted in the Swing forum.
    If i use the init() method instead of the paint(Graphics g) methodWell, thats the proper way to write a Swing applet. The code for building the GUI should be in the init() method. You never need to override the paint() method of the JApplet.
    Components will not be automatically resized when the size of the applet changes. A layered pane does not use a layout manager, therefore it is up to you to manually change the size of each component. You can add a ComponentListener to the applet to be notified when the size changes.

  • Swing Calculator - Logical errors

    Hello,
    I have a couple of problems with the code below
    one of them is with the setLayout().
    Can anyone give a look to that code and tell me what's going wrong , or help me to make it work ??
    Thanks in advance!
    import java.awt.*;
    import java.awt.BorderLayout;
    import java.awt.FlowLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.Container;
    import javax.swing.JButton;
    import javax.swing.JCheckBox;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JTextArea;
    import javax.swing.*;
    public class Calculator extends JFrame implements ActionListener
        public static final int Width = 500;
        public static final int Height = 500;
        private JTextField Board;
        private JButton jbo0, jbo1, jbo2, jbo3, jbo4, jbo5, jbo6, jbo7, jbo8, jbo9,
                        jboAddition, jboSubtraction, jboMultiplication, jboDivision,
                        jboDot, jboLp, jboRp, jboClear, jboResult;
        public static void main(String args[])
        JFrame applet = new Calculator();
        JFrame frame = new JFrame();
        frame.add(frame);
        frame.setSize(Width,Height);
        frame.show();
    public static void main(String args[])
        JFrame outputFrame = new Calculator();
    //panel1.add(allyourstuff);
    //panel1.add(moreofyourstuff);
        outputFrame.setVisible(true);
        public Calculator()
            Container outputPane = this.getContentPane();
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            this.setSize(Width, Height);
            outputPane.setLayout(new GridLayout (3, 3));
            Panel panel1 = new Panel();
            this.setDefaultCloseOperation( EXIT_ON_CLOSE );
            Board = new JTextField();
            panel1.add(Board);
            outputPane.add(panel1);
            //panel1.add(jbo0);
            //Numbers
            setLayout(new FlowLayout());
            setFont(new Font("Helvetica", Font.PLAIN, 8));
            JButton jbo0 = new JButton("0");
            jbo0.addActionListener(this);
            panel1.add(jbo0);
            jbo1 = new JButton("1");
            panel1.add(jbo1);
            jbo1.addActionListener(this);
            jbo2 = new JButton("2");
            panel1.add(jbo2);
            jbo2.addActionListener(this);
            jbo3 = new JButton("3");
            panel1.add(jbo3);
            jbo3.addActionListener(this);
            jbo4 = new JButton("4");
            panel1.add(jbo4);
            jbo4.addActionListener(this);
            jbo5 = new JButton("5");
            panel1.add(jbo5);
            jbo5.addActionListener(this);
            jbo6 = new JButton("6");
            panel1.add(jbo6);
            jbo6.addActionListener(this);
            jbo7 = new JButton("7");
            panel1.add(jbo7);
            jbo7.addActionListener(this);
            jbo8 = new JButton("8");
            panel1.add(jbo8);
            jbo8.addActionListener(this);
            jbo9 = new JButton("9");
            panel1.add(jbo9);
            jbo9.addActionListener(this);
            //Math Operations
            jboAddition = new JButton("+");
            panel1.add(jboAddition);
            jboAddition.addActionListener(this);
            jboSubtraction = new JButton("-");
            panel1.add(jboSubtraction);
            jboSubtraction.addActionListener(this);
            jboMultiplication = new JButton("*");
            panel1.add(jboMultiplication);
            jboMultiplication.addActionListener(this);
            jboDivision = new JButton("/");
            panel1.add(jboDivision);
            jboDivision.addActionListener(this);
            //Result etc..
            jboDot = new JButton(".");
            panel1.add(jboDot);
            jboDot.addActionListener(this);
            jboLp = new JButton("(");
            panel1.add(jboLp);
            jboLp.addActionListener(this);
            jboRp = new JButton(")");
            panel1.add(jboRp);
            jboRp.addActionListener(this);
            jboClear = new JButton("C");
            panel1.add(jboClear);
            jboClear.addActionListener(this);
            jboResult = new JButton("=");
            panel1.add(jboResult);
            jboResult.addActionListener(this);
        public void actionPerformed(ActionEvent e)
            if (e.getSource() instanceof JButton)
                JButton buClicked = (JButton) e.getSource();
                if (buClicked == jboClear)
                    boardClear();
                else if(buClicked == jboResult)
                    Calculate();
            else
                Calculate();
        public void UserInput(JButton buClicked)
            String input;
            input = Board.getText();
            if (buClicked == jbo0)
                Board.setText(input + "0");
            if (buClicked == jbo1)
                Board.setText(input + "1");
            if (buClicked == jbo2)
                Board.setText(input + "2");
            if (buClicked == jbo3)
                Board.setText(input + "3");
            if (buClicked == jbo4)
                Board.setText(input + "4");
            if (buClicked == jbo5)
                Board.setText(input + "5");
            if (buClicked == jbo6)
                Board.setText(input + "6");
            if (buClicked == jbo7)
                Board.setText(input + "7");
            if (buClicked == jbo8)
                Board.setText(input + "8");
            if (buClicked == jbo9)
                Board.setText(input + "9");
            if (buClicked == jboAddition)
                Board.setText(input + "+");
            if (buClicked == jboSubtraction)
                Board.setText(input + "-");
            if (buClicked == jboMultiplication)
                Board.setText(input + "*");
            if (buClicked == jboDivision)
                Board.setText(input + "/");
            if (buClicked == jboDot)
                Board.setText(input + ".");
            if (buClicked == jboLp)
                Board.setText(input + "(");
            if (buClicked == jboRp)
                Board.setText(input + ")");
         private void boardClear()
            Board.setText("");
        public void Calculate()
            int counter;
            int numParenthesis = 0;
            int lenInput;
            String calc;
            String Answer = "";
            char NumOther;
            calc = Board.getText();
            lenInput = calc.length();
            for (counter = 0; counter < lenInput; counter++)
                NumOther = calc.charAt(counter);
                if (NumOther == ')')
                    numParenthesis--;
                if (NumOther == '(')
                    numParenthesis++;
                if ((NumOther < '(') || (NumOther > '9') || (NumOther == '.'))
                    Board.setText("Error");
                if (NumOther == '.' && (counter + 1 < calc.length()))
                    for (int k = counter + 1; (k < calc.length()) && ((Character.isDigit(calc.charAt(k))) || ((calc.charAt(k))) == '.'); k++)
                        if (calc.charAt(k) == '.')
                            Board.setText("Error");
            if (numParenthesis != 0)
                Board.setText("Error");
            else
                Answer = Calculate2(calc);
                Board.setText(Answer);
        private String CalculatorImp(String oper1, String oper2, char Oper)
            Double op1, op2;
            double ops1, ops2;
            double ans = 0;
            String result;
            op1 = new Double (oper1);
            op2 = new Double (oper2);
            ops1 = op1.doubleValue();
            ops2 = op2.doubleValue();
            if (Oper == '+')
                ans = ops1 + ops2;
            if (Oper == '-')
                ans = ops1 - ops2;
            if (Oper == '*')
                ans = ops1 * ops2 ;
            if (Oper == '/')
                ans = ops1/ops2;
            result = Double.toString(ans);
            return result;
        private String Calculate2(String process)
            String answer = process;
            String op1 = "";
            String op2 = "";
            char userinput;
            int index = 0;
            int indexL = 0;
            int indexR = 0;
            int numInput = answer.length();
            int numPar = 0;
            int matchPar = 0;
            int indexOp1 = 0;
            int indexOp2 = 0;
            if (answer  != "Error")
                for (index = 0; index < numInput; index++)
                    userinput = answer.charAt(index);
                    if (userinput  == '(')
                        if (matchPar == 0)
                            indexOp1 = index;
                        matchPar++;
                        numPar++;
                    if (userinput == ')')
                        matchPar--;
                        if (matchPar ==0)
                            indexOp2 = index;
                if (indexOp1 + 1 == indexOp2)
                    Board.setText("Error");
                if (answer == "Error"  && numPar > 0)
                    if (indexOp1 == 0)
                        if (indexOp2 == (numInput - 1))
                            if (indexOp1 != indexOp2)
                                answer = Calculate2(answer.substring(indexOp1 + 1, indexOp2));
                    else if (indexOp1 == 0 && indexOp2 > 0)
                        if ((Character.isDigit(answer.charAt(indexOp2 + 1))))
                            Board.setText("Error");
                        else
                            answer = Calculate2(answer.substring(indexOp1 + 1, indexOp2)) + answer.substring(indexOp2 + 1);
                            numPar--;
                            while (numPar != 0)
                                answer = Calculate2(answer);
                                numPar--;
                    else if ((indexOp1 > 0) && (indexOp2 > 0) && (indexOp2 != numInput - 1))
                        if (((Character.isDigit(answer.charAt(indexOp2 + 1 ))) ||  (Character.isDigit(answer.charAt(indexOp1 - 1 ))) ))
                            Board.setText("Error");
                        else
                            answer = answer.substring(0, indexOp1) + Calculate2(answer.substring(indexOp1 + 1, indexOp2)) + answer.substring(indexOp2 + 1);
                            numPar--;
                            while (numPar != 0)
                                answer = Calculate2(answer);
                                numPar--;
                    else if (indexOp2 == numInput - 1 && indexOp1 > 0)
                        if (((Character.isDigit(answer.charAt(indexOp1 - 1)))))
                            Board.setText("Error");
                        else
                            answer = answer.substring(0, indexOp1) + Calculate2(answer.substring(indexOp1 + 1, indexOp2));
                            numPar--;
                            while (numPar != 0)
                                answer = Calculate2(answer);
                                numPar--;
                if (numPar == 0)
                    if (answer != "Error")
                        if (!(Character.isDigit(answer.charAt(0))))
                            if (answer.charAt(0) != '-')
                                if (!(Character.isDigit(answer.charAt(answer.length() - 1))))
                                    Board.setText("Error");
                for (index = 0; index < answer.length() && (answer == "Error"); index++)
                    userinput = answer.charAt(index);
                    if (userinput == '*' || userinput == '/')
                        if (!(Character.isDigit(answer.charAt(index-1))) || (!(Character.isDigit(answer.charAt(index + 1)))))
                            if (answer.charAt(index + 1) != '-')
                                Board.setText("Error");
                        if (answer.charAt(index + 1) == '-')
                            if (!(Character.isDigit(answer.charAt(index + 2))))
                                Board.setText("Error");
                        if (answer == "Error")
                            indexL = index - 1;
                            if (indexL > 2)
                                if ((answer.charAt(indexL - 1)) == '-')
                                    if ((answer.charAt(indexL - 2)) == 'E')
                                        indexL = indexL -2;
                                while ((indexL  > 0) && ((Character.isDigit(answer.charAt(indexL - 2)) || ((answer.charAt(indexL - 1)) == '.') || ((answer.charAt(indexL - 1)) == 'E' ))))
                                    indexL--;
                                if (indexL == 1)
                                    if ((answer.charAt(indexL - 1)) == '-')
                                        indexL--;
                                if (indexL > 2)
                                    if (((answer.charAt(indexL - 1)) == '-') && !(Character.isDigit(answer.charAt(indexL - 2))))
                                            indexL--;
                                op2 = answer.substring(index + 1, indexR + 1);
                    for (index = 0; index < answer.length() && (answer != "Error"); index++)
                        if (index == 0)
                            index = 1;
                    if (index > 0)
                            if (answer.charAt(index + 1) == '-')
                                index = index + 2;
                    userinput = answer.charAt(index);
                    if ((userinput == '+') || (userinput == '-'))
                        if (!(Character.isDigit(answer.charAt(index - 1))))
                            Board.setText("Error");
                        if (!(Character.isDigit(answer.charAt(index + 1))))
                            Board.setText("Error");
                        if ((answer.charAt(index+1) == '-') && (!(Character.isDigit(answer.charAt(index+2)))))
                             Board.setText("Error");
                        if (answer != "Error")
                            indexL = 0;
                            op1 = answer.substring(indexL , index);
                            indexR = index + 1;
                            while((indexR < answer.length()-1) && ((Character.isDigit(answer.charAt(indexR + 1))) || ((answer.charAt(indexR + 1)) == '.') || ((answer.charAt(indexR + 1)) == 'E')))
                                indexR++;
                                if (indexR < answer.length() - 2)
                                        if ((answer.charAt(indexR + 1)) == '-')
                                            indexR++;
                            op2 = answer.substring(index + 1, indexR + 1);
                            answer = CalculatorImp(op1, op2, userinput ) + answer.substring(indexR + 1);
                            index = 0;
            return answer;
    }

    Your UserInput method doesn't seem to get called anywhere.
    You need to sort out the layout - try a vertical box containing the input and horizontal boxes for the button, or a simple grid. If using a GridLayout, the number of rows and column you give in the constructor should
    Move the actual calculation code out into a separate class - you then can test it more easily with a driver which feeds it lots of expressions, and your UI code isn't all mixed up with it.
    It's a convention to use lower case initial letters on variable and method names.
    Your code is very redundant - create one ActionListener which you attach to each your single character button to append the value of that button to the input box, rather than having all those tests, and extract that code into a single method.
    When you add a swing component to another, it keeps a reference to it so it can draw it. You don't need to, unless you want to do something else which it later on.
    Eg:import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class SwingCalculator extends JFrame {
      public static void main(String args[]) {
        new SwingCalculator().setVisible(true);
      final JTextField board;
      public SwingCalculator () {
        Container outputPane = this.getContentPane();
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setFont(new Font("Helvetica", Font.PLAIN, 18));
        setTitle("SwingCalculator");
        outputPane.setLayout(new BoxLayout(outputPane, BoxLayout.Y_AXIS));
        board = new JTextField();
        outputPane.add(board);
        final JPanel buttons = new JPanel();
        buttons.setLayout(new GridLayout (5, 4));
        outputPane.add(buttons);
        // Buttons which append to the board
        addButtons(buttons, "7", "8", "9", "+");
        addButtons(buttons, "4", "5", "6", "-");
        addButtons(buttons, "1", "2", "3", "*");
        addButtons(buttons, ".", "0", "E", "/");
        addButtons(buttons, "(", ")");
        // the C and = buttons have special action listeners
        final JButton cancel = new JButton("C");
        buttons.add(cancel);
        cancel.addActionListener(new ActionListener() {
          public void actionPerformed (ActionEvent event) {
            board.setText("");
        final JButton calculate = new JButton("=");
        buttons.add(calculate);
        // move the expression code to a separate class and call it here
        calculate.addActionListener(new ActionListener() {
          public void actionPerformed (ActionEvent event) {
            try {
              board.setText(ExpressionParser.evaluate(board.getText()));
            } catch (ExpressionParseException ex) {
              board.setText("ERROR");
        pack();
      // adds buttons which, when pressed, append their label to the board
      public void addButtons (JPanel panel, String... labels) {
        for (final String label:labels) {
          JButton button = new JButton(label);
          panel.add(button);
          button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
              board.setText(board.getText() + label);
    }

  • DrawString from ArraryList Problem

    First off, I am very to this forum, so if this is not the correct forum, please advise, (continue to have issues with this one).
    I'm a current Java1 student working on the final project for the year. Not looking to have answer provided but simply looking for a direction to move toward the issue I'm having.
    Project involves creating a digital signature, (a crude version of the approval pads you sign with electronic pen at Home Depot, Lowes, 7-11, you get the picture). The major difference is that we are signing the pad with our mouse just to show functionality.
    Problem is: When mouseReleased is invoked after signing one's first name and mousePressed is invoked at the start of the last name, a connector line is drawn from end of first name to beginning of last name. I am looking to have a new word started when mouseReleased is invoked.
    Below is the code pertinent to this part of the program, if more is needed let me know.
    Any help on this would be greatly appreciated.
    // Main OrderPanel Class
    class MainPanel extends JPanel
         //Constructor for main OrderPanel
         public MainPanel()
              sigPoints = new ArrayList<Point>();
              current = null;
              pressed = false;
              System.out.println(pressed);
              setLayout(new BorderLayout());
              northPanel = new JPanel();
              northPanel.setLayout(new GridLayout(2,1));
              logoLabel = new JLabel("Big Dog Hardware - Let's Build Something Today!", SwingConstants.CENTER);
              logoLabel.setFont(new Font("Arial", Font.BOLD, 16));
              logoLabel.setForeground(Color.BLUE);
              northPanel.add(logoLabel);
              approveAmount = (double) (Math.random() * 500);
              add(northPanel, BorderLayout.NORTH);
              southPanel = new JPanel();
              addButton("Approve");
              addButton("Clear");
              addButton("Close");
              add(southPanel, BorderLayout.SOUTH);
              //Topping Checkbox and Beverage checkbox create
              centerPanel = new JPanel();
              centerPanel.setLayout(new GridLayout(1,1));
              centerPanelComponent pad = new centerPanelComponent();
              centerPanel.add(pad);
              add(centerPanel, BorderLayout.CENTER);
          class centerPanelComponent extends JComponent implements MouseMotionListener
              public centerPanelComponent()
              addMouseListener(new MouseHandler());
              this.addMouseMotionListener(this);
              public void paintComponent(Graphics g)
                   Graphics2D graphic = (Graphics2D) g;
                   Rectangle2D signPad = new Rectangle2D.Double(47,50,400,75);
                   graphic.setPaint(Color.BLUE);
                   Font sigFont = new Font("Forte", Font.BOLD,26);
                   graphic.setFont(sigFont);
                   String X_Mark = "X";
                   graphic.drawString(X_Mark,21,123);
                   DecimalFormat dollar = new DecimalFormat("$0.00");
                   Font totalFont = new Font("Arial", Font.BOLD,12);
                   graphic.setFont(totalFont);
                   if (select != 1001)
                        String total = "Your Approval is Required for the Total Amount of: " + dollar.format(approveAmount);
                        graphic.drawString(total, 75, 30);
                   else
                        String total = "You Are Approved for the Total Amount of: " + dollar.format(approveAmount);
                        graphic.drawString(total, 100, 30);
                   graphic.draw(signPad);
                   if (sigPoints.size() > 1)
                        Point previousPoint = sigPoints.get(0);
                        for (int i = 1; i < sigPoints.size(); i++)
                             Point thisPoint = sigPoints.get(i);
                             graphic.drawLine(previousPoint.x, previousPoint.y, thisPoint.x, thisPoint.y);
                             previousPoint = thisPoint;
              public void mouseDragged(MouseEvent event)
                   Point a = event.getPoint();
                   sigPoints.add(a);
                   this.repaint();
              public void mouseMoved(MouseEvent event)
                   private class MouseHandler extends MouseAdapter
                        public void mousePressed(MouseEvent event)
                             if(event.getModifiersEx() == event.BUTTON1_DOWN_MASK)
                             pressed = true;
                             System.out.println(pressed);
                        public void mouseReleased(MouseEvent event)
                             if(event.getModifiersEx() != event.BUTTON1_DOWN_MASK)
                             pressed = false;
                             System.out.println(pressed);
         public void addButton(final String label)
              JButton button = new JButton(label);
              button.addActionListener(new ActionListener()
                        public void actionPerformed(ActionEvent event)
                             String selection = label;
                             if (selection == "Approve")
                                  if (sigPoints.size() < 1)
                                  JOptionPane.showMessageDialog(null, "You must sign the pad to authorize approval", "Approval Error", JOptionPane.PLAIN_MESSAGE);
                                  select = event.getID() +1;
                                  select = event.getID();
                                  repaint();
                             if (selection == "Clear")
                                  select = event.getID()+ 1;
                                  sigPoints.clear();
                                  repaint();
                             if (selection == "Close")
                                  select = event.getID() + 1;
                                  System.exit(0);
              southPanel.add(button);
         private ArrayList<Point> sigPoints;
         private Point current;
         private JLabel logoLabel;
         private JLabel approvalLabel;
         private JLabel approvedLabel;
         private double approveAmount;
         private JPanel northPanel;
         private JPanel southPanel;
         private JPanel centerPanel;
         private DecimalFormat dollar;
         private centerPanelComponent pad;
         private String total;
         private int select;
         private boolean pressed;
    }     

    Switch to a new array list. Or you have to have a state machine track that you are signing your last name. What is happening is that you are just adding a new point to the existing array, so you naturally draw a line from the last point to the next point--that is the logic you use all the way though to generate your signature. This seems to work for you, but you have a mouse release, you need to go to the next state, that is, to the last name, you do this with another ArrayList to hold the data for the last name. You'll have to amend your paint logic to take in:
    State: 0 -- clear
    State: 1 -- getting first name
    State 2 -- have first name and getting second name
    state 3 -- complete all is done.
    Unless you want to accept signatures that have multiple breaks like mine does... I have 5 sections on my signature. In that case you need to just keep on collecting new point set data until they click done.

  • Help on JComboBox

    Hi,
    I want to create a custom combobox. if i open the popup menu in the combo box, it should display a jtable in that rendering area of the combo box popup menu. i want to add any types of component in that jtable(Jbutton, label, combobox).
    Finally i want to add a new JButton in that jCombo popup area. the content of the button is "Connect". If the user click the connect button, then only the popup should be invisible.
    Any Idea?
    Can i use the ComboBoxRenderer to this?

    hi,
    i didn't had any sample program.. i did this just for your help.. this is just an idea that how it can go..
    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.Insets;
    import java.awt.Toolkit;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import javax.swing.Popup;
    import javax.swing.PopupFactory;
    * @author          : aniruddha<br>
    * @date          : Apr 11, 2007,  3:49:15 PM<br>
    * @source          : ADCCombo.java<br>
    * @project          : HelpForum<br>
    public class ADCCombo extends JPanel
         private JButton     m_btnBrowse     = null;
         private JLabel     m_lblMain     = null;
         private Popup     m_objPopup     = null;
         private boolean m_bisVisible = false;
         public ADCCombo()
              final PopupFactory factory = PopupFactory.getSharedInstance();
              setLayout(new BorderLayout());
              add(m_lblMain = new JLabel("OK"), BorderLayout.CENTER);
              add(m_btnBrowse = new JButton("..."), BorderLayout.EAST);
              m_btnBrowse.setMargin(new Insets(0, 0, 0, 0));
              final JTextArea txt = new JTextArea(3, 10);
              final Component l_cmp = new JScrollPane(txt);
              m_btnBrowse.setFocusable(false);
              m_btnBrowse.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent a_objEvent)
                        if(m_objPopup != null)
                             if(m_bisVisible)
                                  m_objPopup.hide();
                                  m_bisVisible = false;
                                  return;
                        m_objPopup = factory.getPopup(ADCCombo.this, l_cmp, l_objJFrame.getX() + 3, l_objJFrame.getY() + ADCCombo.this.getHeight() + ADCCombo.this.getY() + 25);
                        m_objPopup.show();
                        txt.requestFocus();
                        txt.setText(ADCCombo.this.toString());
                        m_bisVisible = true;
         static JFrame l_objJFrame = new JFrame("Custom Combo");
         public static void main(String[] args)
              l_objJFrame.add(new ADCCombo(), BorderLayout.NORTH);
              Dimension dimSize = Toolkit.getDefaultToolkit().getScreenSize();
              l_objJFrame.setSize((int) (dimSize.getWidth() / 10) * 4, (int) (dimSize.getHeight() / 10) * 4);
              l_objJFrame.setLocationRelativeTo(null);
              l_objJFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              l_objJFrame.setVisible(true);
    }this is another way...
    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.Insets;
    import java.awt.Toolkit;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JPopupMenu;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import javax.swing.Popup;
    import javax.swing.PopupFactory;
    * @author          : aniruddha<br>
    * @date          : Apr 11, 2007,  3:49:15 PM<br>
    * @source          : ADCCombo.java<br>
    * @project          : HelpForum<br>
    public class ADCCombo extends JPanel
         private JButton     m_btnBrowse     = null;
         private JLabel     m_lblMain     = null;
         private JPopupMenu     m_objPopup     = null;
         public ADCCombo()
              setLayout(new BorderLayout());
              add(m_lblMain = new JLabel("OK"), BorderLayout.CENTER);
              add(m_btnBrowse = new JButton("..."), BorderLayout.EAST);
              m_btnBrowse.setMargin(new Insets(0, 0, 0, 0));
              final JTextArea txt = new JTextArea(3, 10);
              final Component l_cmp = new JScrollPane(txt);
              m_objPopup = new JPopupMenu();
              m_objPopup.add(l_cmp);
              m_btnBrowse.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent a_objEvent)
                        m_objPopup.show(ADCCombo.this, getX(), getY() + getHeight());
         static JFrame l_objJFrame = new JFrame("Custom Combo");
         public static void main(String[] args)
              l_objJFrame.add(new ADCCombo(), BorderLayout.NORTH);
              Dimension dimSize = Toolkit.getDefaultToolkit().getScreenSize();
              l_objJFrame.setSize((int) (dimSize.getWidth() / 10) * 4, (int) (dimSize.getHeight() / 10) * 4);
              l_objJFrame.setLocationRelativeTo(null);
              l_objJFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              l_objJFrame.setVisible(true);
    }regards
    Aniruddha

  • How do i display an ArrayLists data in GUI?

    Hey
    Im trying to make a calendar and it works as it is suppose to with System.print.ln(), but now i want to get it you the GUI. How do i this?
    My best quess is to pass the ArrayList to the GUI and then loop through the ArrayList in the GUI. After this i dont know what i to do. I want to put the data from the ArrayList, which is all the days in a month (for example 1-31 or 1-30) into labels.
    Any suggentions to this?
    Here is the code that i have tried with:
    Makes the ArrayList:
    public void showCalendarMonth(int year, int month, int daysInMonth){
            calendarMonth = new ArrayList<String>();
            for(int i = 1 ; i <= daysInMonth; i++)
                if(bookingList.checkDate(year, month, i) == "B"){
                    calendarMonth.add("B"+i);
                }else{           
                    calendarMonth.add(i);
    public ArrayList<String> getCalendar(){
            return calendarMonth;
        }GUI:
    public void makeCalendar(int year, int month, int daysInMonth){
            ArrayList<String> calendarArray = calender.getCalendar();
            for(String day : calendarArray){
                final String label = day;
                JButton button = new JButton(label);
                panel.add(button);
        }This gives me the following error:
    Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String

    I think this will solve your problem.
    public void makeCalendar(int year, int month, int daysInMonth){
            ArrayList<String> calendarArray = calender.getCalendar();
            for(String day : calendarArray){
                final String label = (String)day;
                JButton button = new JButton(label);
                panel.add(button);
        }

Maybe you are looking for

  • Right way to change encoding settings

    Hi! When I encode footages I have to differet ways to change encoding settings - one is AME's settings panel. Second is Codec options. I'm confused - where must I change settings, must they be the same in both windows, or what's "primary" options win

  • How to insert data in a smarforms?

    Good morning to everybody! I've a smartform with a header, in this header there're some fields that I've to fill with some data of the table HRPY_WPBP, I don't know how to insert the data in the field, I've read through internet I need to put before

  • Polling SAP directories

    Hello, I am hoping someone will be able to help me with my query. I am trying to write an ABAP program which poll a SAP directory and then process the files within this directory. I am using FM SUBST_GET_FILE_LIST to get the files from the directory

  • Trying to not wait on a server socket

    Hi! I need my code to not sit and pause on an accept command for server sockets, but still continue listening for incoming connections. How do I do this? Thanks!

  • Information about my hyperlinks disappeared from my hyperlinks panel and I need to know how to restore it.

    I am using InDesign CS6 for Windows. Information about my hyperlinks disappeared from my hyperlinks panel and I need to know how to restore it. I clicked on the panel and the hyperlinks section disappeared. I can see cross-references, but not hyperli