Problem with overridding JButton paintComponent

I have written an extension of JButton that simply paints an octagon on the button:
package myPackage;
import javax.swing.JButton;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Polygon;
import javax.swing.JFrame;
import java.io.Serializable;
public class MyButton extends JButton implements Serializable {
public MyButton() {
super();
public void paintComponent(Graphics g) {
super.paintComponent(g);
int[] xPoints = new int[9];
int[] yPoints = new int[9];
int endX, beginX, endY, beginY;
super.paintComponent(g);
int w = getSize().width;
int h = getSize().height;
// get the smaller of the two
int min = (w > h ? h : w);
System.out.println(w + ", " + h + ", " + min + ", " + getLocation());
beginX = getLocation().x + (w - min) / 2;
endX = beginX + min;
beginY = getLocation().y + (h - min) / 2;
endY = beginY + min;
System.out.println(beginX + ", " + beginY + ", " + endX + ", " + endY);
// Set the proper points to draw a 8 sided polygon
// These formulas are based on where a point should be
// proportionally relitive to the starting point (x1,y1)
// and the ending point (x,y)
xPoints[0] = (endX - beginX) / 4 + beginX;
xPoints[1] = (endX - beginX) * 3 / 4 + beginX;
xPoints[2] = endX;
xPoints[3] = endX;
xPoints[4] = (endX - beginX) * 3 / 4 + beginX;
xPoints[5] = (endX - beginX) / 4 + beginX;
xPoints[6] = beginX;
xPoints[7] = beginX;
xPoints[8] = (endX - beginX) / 4 + beginX;
yPoints[0] = beginY;
yPoints[1] = beginY;
yPoints[2] = (endY - beginY) / 4 + beginY;
yPoints[3] = (endY - beginY) * 3 / 4 + beginY;
yPoints[4] = endY;
yPoints[5] = endY;
yPoints[6] = (endY - beginY) * 3 / 4 + beginY;
yPoints[7] = (endY - beginY) / 4 + beginY;
yPoints[8] = beginY;
Polygon p = new Polygon(xPoints, yPoints, 8);
g.setColor(Color.RED);
g.fillPolygon(p);
public static void main(String args[]) {
JFrame jf = new JFrame("Stop Button");
// change false to true to see it in a JPanel
if (false) {
JPanel jp = new JPanel();
jp.setLayout(new BorderLayout());
jp.add(new MyButton(), BorderLayout.NORTH);
jf.add(jp);
} else {
jf.add(new MyButton());
jf.setSize(new Dimension(100, 100));
jf.setVisible(true);
This works fine ... until I reference it from a larger program. I used Netbeans 6.1 GUI builder for a more complicated structure. When I run the larger app ... the button is blank. Here's the main part of the code that the builder generated:
javax.swing.GroupLayout topPanelLayout = new javax.swing.GroupLayout(topPanel);
topPanel.setLayout(topPanelLayout);
topPanelLayout.setHorizontalGroup(
topPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(topPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(topPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(topPanelLayout.createSequentialGroup()
.addComponent(stopButton, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)) <---------------------
.addComponent(tickerField))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(srButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(channelButton)
.addGap(14, 14, 14)
.addComponent(measurementPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
I'm using JDK 1.6, and don't have a lot of experience chasing down Swing problems. Could you please make some suggestions as to what I'm doing wrong?? The print statements show me that the paintComponent method is being reached when I move the mouse over the button, but nothing gets drawn!!!
Thanks in advance for any help you can provide.
Dwight

Here's some of your code,
if (false) {
      JPanel jp = new JPanel();
      jp.setLayout(new BorderLayout());
      jp.add(new MyButton(), BorderLayout.NORTH);
      jf.add(jp);
} else {
     jf.add(new MyButton());
jf.setSize(new Dimension(100, 100));In both cases your button is being added to a container using BorderLayout. When the container resizes so to does the button. That's why this works,
public MyButton() {
     super();
public void paintComponent(Graphics g) {
     int w = getSize().width;
     int h = getSize().height;
}Initially MyButton has zero size, but when the frame's size is set the BorderLayout will change the size of MyButton.
However, with a more complicated GUI and GroupLayout the button may not necessarily change size when the frame's size is set. It may remain at its preferred size - which is zero or close to it (since it has no text or icon). So now all of a sudden getWidth() and getHeight() return zero (or close to it). You need to set an appropriate preferred size
public MyButton() {
     super();
     setPreferredSize(...);  //<--- add a line like this
}

Similar Messages

  • JSF 1.1 - problem with overriding default messages with UTF8 ones

    Hi there,
    I'm stuck with JSF 1.1 for now (creating application that is to run on JBoss 4.0.x) and I've encountered a problem... My web application uses UTF8 encoding - so that's also encoding I need in my message bundle. I've created one - and here goes a problem. I need to put Polish special characters into a properties file of a bundle - so I do it with UTF escape notation:
    javax.faces.component.UIInput.REQUIRED=Warto\u009C\u00E6 dla pola {0} jest wymagana
    some.custom.message.CLOSED=zamkni\u0119taThe thing is - while custom messages are working properly, overriden javax.faces.component.UIInput.REQUIRED message is rendered on a page as four "strange" characters, suggesting that it was first interpreted as UTF, then parsed as some kind of an ASCII (ISO) encoding and then back to an UTF8 page...
    How to fix this?
    TIA,
    Wojtek

    IDE fooled me - it was smarter then I expected and properties editor was showing already decoded values, not raw content of file. It's working properly now

  • SwingUtilities.paintComponent - problems with painting childs of components

    Maybe this question was mention already but i cant find any answer...
    Thats what could be found in API about method paintComponent in SwingUtilities:
    Paints a component c on an arbitrary graphics g in the specified rectangle, specifying the rectangle's upper left corner and size. The component is reparented to a private container (whose parent becomes p) which prevents c.validate() and c.repaint() calls from propagating up the tree. The intermediate container has no other effect.
    The component should either descend from JComponent or be another kind of lightweight component. A lightweight component is one whose "lightweight" property (returned by the Component isLightweight method) is true. If the Component is not lightweight, bad things map happen: crashes, exceptions, painting problems...
    So this method perfectly works for simple Java components like JButton / JCheckbox e.t.c.
    But there are problems with painting JScrollBar / JScrollPane (only background of this component appears).
    I tried to understand why this happens and i think the answer is that it has child components that does not draw at all using SwingUtilities.paintComponent()
    (JScrollBar got at least 2 childs - 2 buttons on its both sides for scroll)
    Only parent component appears on graphics - and thats why i see only gray background of scrollbar
    So is there any way to draw something like panel with a few components on it if i have some Graphics2D to paint on and component itself?
    Simple example with JScrollPane:
    JScrollPane pane = new JScrollPane(new JLabel("TEST"));
    pane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    pane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    SwingUtilities.paintComponent(g2d, pane, new JPanel(), 0, 0, 200, 200);Edited by: mgarin on Aug 11, 2008 7:48 AM

    Well the thing you advised could work... but this wont be effective, because i call repaint of the area, where Components painted, very often..
    So it will lag like hell when i make 10-20 repaints in a second... (for e.g. when i drag anything i need mass repainting of the area)
    Isnt there any more optimal way to do painting of the sub-components?
    As i understand when any component (even complicated with childs) paints in swing - its paint method calls its child components paint() to show them... can this thing be reproduced to paint such components as JScrollPane?

  • Problem with setCursor for JButton in cell on JTable

    i have a problem with setCursor to JButton that is in a cell of the JTable}
    this is the code
    public class JButtonCellRenderer extends JButton implements TableCellRenderer {
    public JButtonCellRenderer() {
    setOpaque(true);
    public Component getTableCellRendererComponent(JTable table, Object value,
    boolean isSelected, boolean hasFocus,
    int row, int column) {
    if (isSelected) {
    setForeground(table.getSelectionForeground());
    setBackground(table.getSelectionBackground());
    else {
    setForeground(table.getForeground());
    setBackground(Color.WHITE);
    setBorder(null);
    if(table.getValueAt(row,column) == null){
    setText("");
    if(isSelected){
    setBackground(table.getSelectionBackground());
    }else{
    setBackground(Color.WHITE);
    }else{
    if(table.getValueAt(row,column) instanceof JButton){
    JButton _button = (JButton)table.getValueAt(row,column);
    if(_button.getText().trim().equals("")){
    setText("<html>"+ "<font size=\"3\" COLOR=\"#0000FF\"><u><b>Ver...</b></u></font>"+"");
    }else{
    setText("<html>"+ "<font size=\"3\" COLOR=\"#0000FF\"><u><b>" + _button.getText() + "</b></u></font>"+"");
    return this;
    }

    Not quite sure I understand the problem, but I guess you have tried to call setCursor on your renderer and found it didn't work? The reason, I think, is that the renderer only renders a JButton. The thing that ends up in the table is in fact only a "picture" of a JButton, and among other things it won't receive and interact with any events, such as MouseEvents (so it wouldn't know that the cursor should change).
    There are at least two alternatives for you: You can perhaps use a CellEditor instead of a CellRenderer. Or you can add a MouseListener to the table and then use the methods column/rowAtPoint to figure out if the cursor is over your JButton cell and change the cursor yourself if it is.

  • Problems with basic Java JPanel animation using paintcomponent

    okay so I am trying to animate a sprite moving across a background using a for loop within the paintComponent method of a JPanel extension
    public void paintComponent(Graphics g){
    Image simpleBG = new ImageIcon("Images/Backgrounds/Simple path.jpg").getImage();
    Image mMan = new ImageIcon("Images/Sprites/hMan.gif").getImage();
    if (!backgroundIsDrawn){
    g.drawImage(simpleBG, 0, 0, this);
    g.drawImage(mMan, xi, y, this);
    backgroundIsDrawn=true;
    else
    for (int i=xi; i<500; i++){
    g.drawImage(simpleBG, 0, 0, this);
    g.drawImage(mMan, i, y, this);
    try{
    Thread.sleep(10);
    } catch(Exception ex){System.out.println("damn");}
    The problem is that no matter what I set my thread to, it will not show the animation, it will just jump to the last location, even if the thread sleep is set high enough that it takes several minutes to calculate,, it still does not paint the intemediary steps.
    any solution, including using a different method of animation all together would be greatly appreciated. I am learning java on my own so i need all the help I can get.

    fysicsandpholds1014 wrote:
    even when I placed the thread sleep outside of the actual paintComponent in a for loop that called repaint(), it still did not work? Nope. Doing this will likely put the Event Dispatch Thread or EDT to sleep. Since this is the main thread that is responsible for Swing's painting and user interaction, you'll put your app to sleep with this. Again, use a Swing Timer
    and is there any easy animation method that doesnt require painting and repainting every time becasue it is very hard to change what I want to animate with a single paintComponent method? I don't get this.
    I find the internet tutorials either way too complicated or not nearly in depth enough. Maybe its just that I am new to programming but there doesn't seem to be a happy medium between dumbed down Swing tutorials and very complicated and sophisticated animation algorithmns.I can only advise that you practice, practice, practice. The more you use the tutorials, the easier they'll be to use.
    Here's another small demo or animation. It is not optimized (repaint is called on the whole JPanel), but demonstrates some points:
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.image.BufferedImage;
    import java.net.URL;
    import javax.imageio.ImageIO;
    import javax.swing.*;
    @SuppressWarnings("serial")
    public class AnimationDemo2 extends JPanel {
      // use a publicly available sprite for this example
      private static final String SPRITE_PATH = "http://upload.wikimedia.org/" +
                "wikipedia/commons/2/2e/FreeCol_flyingDutchman.png";
      private static final int SIDE = 600;
      private static final Dimension APP_SIZE = new Dimension(SIDE, SIDE);
      // timer delay: equivalent to the Thread.sleep time
      private static final int TIMER_DELAY = 20;
      // how far to move in x dimension with each loop of timer
      public static final int DELTA_X = 1;
      // holds our sprite image
      private BufferedImage img = null;
      // the images x & y locations
      private int imageX = 0;
      private int imageY = SIDE/2;
      public AnimationDemo2() {
        setPreferredSize(APP_SIZE);
        try {
          // first get our image
          URL url = new URL(SPRITE_PATH);
          img = ImageIO.read(url);
          imageY -= 3*img.getHeight()/4;
        } catch (Exception e) { // shame on me for combining exceptions :(
          e.printStackTrace();
          System.exit(1); // exit if fails
        // create and start the Swing Timer
        new Timer(TIMER_DELAY, new TimerListener()).start();
      // all paintComponent does is paint -- nothing else
      public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.setColor(Color.blue);
        int w = getWidth();
        int h = getHeight();
        g.fillRect(0, h/2, w, h);
        if (img != null) {
          g.drawImage(img, imageX, imageY, this);
      private class TimerListener implements ActionListener {
        // is called every TIMER_DELAY ms
        public void actionPerformed(ActionEvent e) {
          imageX += DELTA_X;
          if (imageX > getWidth()) {
            imageX = 0;
          // ask JVM to paint this JPanel
          AnimationDemo2.this.repaint();
      // code to place our JPanel into a JFrame and show it
      private static void createAndShowUI() {
        JFrame frame = new JFrame("Animation Demo");
        frame.getContentPane().add(new AnimationDemo2());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
      // call Swing code in a thread-safe manner
      public static void main(String[] args) {
        java.awt.EventQueue.invokeLater(new Runnable() {
          public void run() {
            createAndShowUI();
    }

  • Having problems with GUI

    Goodday all, I'm having a problem getting this GUI for a simulation game up and running. I've added four panels which each house components for instance buttons, text area etc. And I've created another panel to house the image that should be set for the background. I've heard that the best way to achieve this is to use getLayeredPane(), but I think that's the problem. The panel simDisplay holds the title for the simulation, simControls hold start and stop simulation buttons, simGrid holds a grid on which the simulation is played (still working on that) and simDisplayControls is a panel that holds a textArea and button to run the simulation again. The textArea is a display area for the status of the simulation (for instance which characters moved, how many are there remaining etc ). The simDisplay was placed NORTH, simGRID CENTER, simControls EAST, and simDisplayContols SOUTH. Before I added the getLayeredPane so that I can view the image as the background, each of these panels were in their respective positions within the layout...now that I have, only some components are visible. As soon as I comment out that line of code with getLayeredPane all the components show exactly how I want them to which is in the positions I specified above (NORTH, SOUTH etc). I'm wondering if the fact that I used the BoxLayout to position the components within their panels is conflicting with the layeredPane. I'm new to this so any help will be greatly appreciated. Thank You ;)
    import javax.swing.*;
    import java.awt.*;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Image;
    public class Simulation extends JFrame{
    //create new panels, image icons and buttons
    JLayeredPane panel = new JLayeredPane();
    JPanel panel2 = new JPanel();
    JPanel simDisplayControls = new JPanel();
    public JButton start = new JButton("Start Simulation");
    public JButton stop = new JButton("Stop Simulation");
    private JTextArea turnDisplay;
    public JButton next = new JButton("Next Time Step");
    JPanel simDisplay = new JPanel();
    JPanel simGrid = new JPanel ();
    JPanel simControls = new JPanel();
    //GUI main function
    public static void main(String[] args){
    Simulation example = new Simulation();
    //GUI constructor
    public Simulation() {
    BorderLayout b = new BorderLayout();
    setLayout(b);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    BorderLayout panelout = new BorderLayout( 0, 0 );
    panel.setLayout(panelout);
    //Set image as simulation background
    ImageIcon myIcon = new ImageIcon("background2.jpg");
    JLabel picLabel = new JLabel(myIcon);
    panel2.add(picLabel);
    picLabel.setBounds(0, 0, myIcon.getIconWidth(), myIcon.getIconHeight());
    getLayeredPane().add(picLabel, new Integer.MIN_VALUE);
    panel.setOpaque(false);
    //set content pane to main panel containing all other panels
    setContentPane(panel);
    simGrid.setLayout (new GridLayout (20, 20));
    // create text area to display status after each time step of the simulation
    turnDisplay = new JTextArea("Doodlebug Turn", 10, 40);
    JScrollPane scrollingDisplay = new JScrollPane(turnDisplay);
    simDisplayControls.add(scrollingDisplay);
    turnDisplay.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));
    //create horizontal box to house status display and "next time step" button
    Box simDisplayBox = Box.createHorizontalBox();
    simDisplayBox.add(Box.createHorizontalGlue());
    simDisplayBox.add(turnDisplay);
    simDisplayBox.add(Box.createHorizontalStrut(40));
    simDisplayBox.add(next);
    simDisplayBox.add(Box.createHorizontalStrut(30));
    //create vertical box to house "start" and "stop" simulation buttons
    Box simControlBox = Box.createVerticalBox();
    simControlBox.add(Box.createVerticalStrut(80));
    simControlBox.add(start);
    simControlBox.add(Box.createVerticalStrut(60));
    simControlBox.add(stop);
    simControlBox.add(Box.createVerticalGlue());
    //create label containing the title of the simulation
    JLabel title = new JLabel("Sim Title");
    //add title label and box containing simulation control buttons to their respective panels
    simDisplay.add(title);
    simControls.add(simControlBox);
    //add box containing status display and "next time step" button to its coresponding panel
    simDisplayControls.add(simDisplayBox);
    //add panels to the main panel
    panel.add(simDisplay, BorderLayout.NORTH);
    panel.add(simGrid, BorderLayout.CENTER);
    panel.add(simControls, BorderLayout.EAST);
    panel.add(simDisplayControls, BorderLayout.SOUTH);
    //set size of the frame
    setSize(800, 700);
    setVisible(true);// make the frame visible
    }

    Don't put the image on the layeredpane, and in fact don't create a class that subclasses JFrame. You're far better off subclassing a JPanel and drawing the image in the JPanel by overriding its paintComponent method, calling drawImage(...) in the same paintComponent method after checking that the image isn't null. Then adding all of your components to this JPanel. Be sure that the JPanels sitting on top of the main JPanel all have their opaque property set to false.
    Then when you're ready to show the app, create a JFrame on the fly, place your JPanel into the JFrame's contentPane, pack the JFrame, set it's location, and show it.
    for instance:
    import javax.imageio.ImageIO;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.image.BufferedImage;
    import java.io.IOException;
    import java.net.URL;
    public class Simulation extends JFrame
      //TODO: change this to point to your desired background image
      private static final String BACKGROUND =
        "http://upload.wikimedia.org/wikipedia/" +
        "commons/8/8e/Nebelostfriesland.jpg";
      JPanel panel = new JPanel()
        protected void paintComponent(Graphics g)
          super.paintComponent(g);
          myPaint(g);
      private BufferedImage image;
      private void myPaint(Graphics g)
        if (image != null)
          g.drawImage(image, 0, 0, panel.getWidth(), panel.getHeight(), panel);
      public Simulation()
        try
          // or if using a file on disk, can use a File here or an InputStream
          image = ImageIO.read(new URL(BACKGROUND));
        catch (IOException e)
          e.printStackTrace();
        panel2.setOpaque(false);
        //panel.setOpaque(false);
        simGrid.setOpaque(false); // etc...
    }Edited by: Encephalopathic on Dec 1, 2008 3:23 PM

  • Advance level drawing problem with Jframe and JPanel need optimize sol?

    Dear Experts,
    I m trying to create a GUI for puzzle game following some kind of "game GUI template", but i have problems in that,so i tried to implement that in various ways after looking on internet and discussions about drawing gui in swing, but i have problem with both of these, may be i m doing some silly mistake, which is still out of my consideration. please have a look at these two and recommend me one of them, which is running without problems (flickring and when you enlarge window the board draw copies (tiled) everywhere,
    Note: i don't want to inherit jpanel or Jframe
    here is my code : import java.awt.BorderLayout;
    public class GameMain extends JFrame {
         private static final long serialVersionUID = 1L;
         public int mX, mY;
         int localpoints = 0;
         protected static JTextField[][] squares;
         protected JLabel statusLabel = new JLabel("jugno");
         Label lbl_score = new Label("score");
         Label lbl_scorelocal = new Label("local score");
         protected static TTTService remoteTTTBoard;
         // Define constants for the game
         static final int CANVAS_WIDTH = 800; // width and height of the game screen
         static final int CANVAS_HEIGHT = 600;
         static final int UPDATE_RATE = 4; // number of game update per second
         static State state; // current state of the game
         private int mState;
         // Handle for the custom drawing panel
         private GameCanvas canvas;
         // Constructor to initialize the UI components and game objects
         public GameMain() {
              // Initialize the game objects
              gameInit();
              // UI components
              canvas = new GameCanvas();
              canvas.setPreferredSize(new Dimension(CANVAS_WIDTH, CANVAS_HEIGHT));
              this.setContentPane(canvas);
              this.setDefaultCloseOperation(EXIT_ON_CLOSE);
              this.pack();
              this.setTitle("MY GAME");
              this.setVisible(true);
         public void gameInit() {     
         // Shutdown the game, clean up code that runs only once.
         public void gameShutdown() {
         // To start and re-start the game.
         public void gameStart() {
         private void gameLoop() {
         public void keyPressed(KeyEvent e) {
         public void keyTyped(KeyEvent e) {
         public void gameKeyReleased(KeyEvent e) {
              PuzzleBoard bd = getBoard();
              for (int row = 0; row < 4; ++row) {
                   for (int col = 0; col < 4; ++col) {
                        if (e.getSource() == squares[row][col]) {
                             if (bd.isOpen(col, row)) {
                                  lbl_score.setText("Highest Score = "
                                            + Integer.toString(bd.getPoints()));
                                  setStatus1(bd);
                                  pickSquare1(col, row, squares[row][col].getText()
                                            .charAt(0));
         protected void pickSquare1(int col, int row, char c) {
              try {
                   remoteTTTBoard.pick(col, row, c);
              } catch (RemoteException e) {
                   System.out.println("Exception: " + e.getMessage());
                   e.printStackTrace();
                   System.exit(1);
         // method "called" by remote object to update the state of the game
         public void updateBoard(PuzzleBoard new_board) throws RemoteException {
              String s1;
              for (int row = 0; row < 4; ++row) {
                   for (int col = 0; col < 4; ++col) {
                        squares[row][col].setText(new_board.ownerStr(col, row));
              lbl_score.setText("Highest Score = "
                        + Integer.toString(new_board.getPoints()));
              setStatus1(new_board);
         protected void setStatus1(PuzzleBoard bd) {
              boolean locals = bd.getHave_winner();
              System.out.println("local win" + locals);
              if (locals == true) {
                   localpoints++;
                   System.out.println("in condition " + locals);
                   lbl_scorelocal.setText("Your Score = " + localpoints);
              lbl_score
                        .setText("Highest Score = " + Integer.toString(bd.getPoints()));
         protected PuzzleBoard getBoard() {
              PuzzleBoard res = null;
              try {
                   res = remoteTTTBoard.getState();
              } catch (RemoteException e) {
                   System.out.println("Exception: " + e.getMessage());
                   e.printStackTrace();
                   System.exit(1);
              return res;
         /** Custom drawing panel (designed as an inner class). */
         class GameCanvas extends JPanel implements KeyListener {
              /** Custom drawing codes */
              @Override
              public void paintComponent(Graphics g) {
                   // setOpaque(false);
                   super.paintComponent(g);
                   // main box; everything placed in this
                   // JPanel box = new JPanel();
                   setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
                   // add(statusLabel, BorderLayout.NORTH);
                   // set up the x's and o's
                   JPanel xs_and_os = new JPanel();
                   xs_and_os.setLayout(new GridLayout(5, 5, 0, 0));
                   squares = new JTextField[5][5];
                   for (int row = 0; row < 5; ++row) {
                        for (int col = 0; col < 5; ++col) {
                             squares[row][col] = new JTextField(1);
                             squares[row][col].addKeyListener(this);
                             if ((row == 0 && col == 1) || (row == 2 && col == 3)
                             || (row == 1 && col == 4) || (row == 4 && col == 4)
                                       || (row == 4 && col == 0))
                                  JPanel p = new JPanel(new BorderLayout());
                                  JLabel label;
                                  if (row == 0 && col == 1) {
                                       label = new JLabel("1");
                                       label.setHorizontalAlignment(JLabel.LEFT);
                                       label.setVerticalAlignment(JLabel.TOP);
                                  else if (row == 4 && col == 0) {// for two numbers or
                                       // two
                                       // blank box in on row
                                       label = new JLabel("2");
                                       label.setHorizontalAlignment(JLabel.LEFT);
                                       label.setVerticalAlignment(JLabel.TOP);
                                  else if (row == 1 && col == 4) {
                                       label = new JLabel("3");
                                       label.setHorizontalAlignment(JLabel.LEFT);
                                       label.setVerticalAlignment(JLabel.TOP);
                                  else if (row == 4) {
                                       label = new JLabel("4");
                                       label.setHorizontalAlignment(JLabel.LEFT);
                                       label.setVerticalAlignment(JLabel.TOP);
                                  else {
                                       label = new JLabel("5");
                                       label.setHorizontalAlignment(JLabel.LEFT);
                                       label.setVerticalAlignment(JLabel.TOP);
                                  label.setOpaque(true);
                                  label.setBackground(squares[row][col].getBackground());
                                  label.setPreferredSize(new Dimension(label
                                            .getPreferredSize().width, squares[row][col]
                                            .getPreferredSize().height));
                                  p.setBorder(squares[row][col].getBorder());
                                  squares[row][col].setBorder(null);
                                  p.add(label, BorderLayout.WEST);
                                  p.add(squares[row][col], BorderLayout.CENTER);
                                  xs_and_os.add(p);
                             } else if ((row == 2 && col == 1) || (row == 1 && col == 2)
                                       || (row == 3 && col == 3) || (row == 0 && col == 3)) {
                                  xs_and_os.add(squares[row][col]);
                                  // board[ row ][ col ].setEditable(false);
                                  // board[ row ][ col ].setText("");
                                  squares[row][col].setBackground(Color.RED);
                                  squares[row][col].addKeyListener(this);
                             } else {
                                  squares[row][col] = new JTextField(1);
                                  // squares[row][col].addActionListener(this);
                                  squares[row][col].addKeyListener(this);
                                  xs_and_os.add(squares[row][col]);
                   this.add(xs_and_os);
                   this.add(statusLabel);
                   this.add(lbl_score);
                   this.add(lbl_scorelocal);
              public void keyPressed(KeyEvent e) {
              public void keyReleased(KeyEvent e) {
                   gameKeyReleased(e);
              public void keyTyped(KeyEvent e) {
         // main
         public static void main(String[] args) {
              SwingUtilities.invokeLater(new Runnable() {
                   @Override
                   public void run() {
                        new GameMain();
      thanks a lot for your time , consideration and efforts.
    jibby
    Edited by: jibbylala on Sep 20, 2010 6:06 PM

    jibbylala wrote:
    thanks for mentioning as i wasn't able to write complete context here.Yep thanks camickr. I think that Darryl's succinct reply applies here as well.

  • Problems with JDesktopPane and JInternalFrame

    hello
    merry christmas .
    I have some strange problem with JDesktopPane .
    I have a frame with an splitpane and in right side of splitpane i have a JDesktopPane .
    I can easily add InternalFrames to this JDesktopPane but when there is two or more InternalFrame and when I have at least 2 internal frame(they are not minimized or in full screen mode or cover completely each other , just when overlap each other) my cpu usage go to 100% and as soon as i minimize one of them or go to full screen mode or drag out one of them problem resolves .
    I have not any extra code that cause this problem(i just overwrite the paint method in internal frames ) .
    Can you help me ?
    Thanks for your time

    Did you override paint() or paintComponent()? Generally you should override paintComponent() for Swing components.
    Regards,
    Tim

  • Problem with JPanel, JMenuBar

    Hi, I'm new here so I'm not even sure if I'm posting in the correct forum ^^
    I usually don't have problems when building a JFrame and adding items into it but now I'm confused.
    When the JFrame is "built", I get a NullPointerException from the Panel's paintComponent method when it's trying to draw an image (g.drawImage())
    This is the whole JPanel class
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class PanneauDe extends JPanel
      private static final String [] TAB_IMAGE = { "De1.GIF", "De2.GIF", "De3.GIF",
                                                   "De4.GIF", "De5.GIF", "De6.GIF" };
      private static final int [] TAB_FREQUENCE = {0,0,0,0,0,0};
      private static final int SIDE = 100;
      private De unDe;
      private ImageIcon imageDe;
      private boolean aFirstTime;
      private int aX, aY; 
      public PanneauDe()
        unDe = new De();
        aX = aY = 0;
        aFirstTime = true;  
        addMouseListener(new EcouteurSouris());   
      public String getStats()
        String statsMsg = "";
        for ( int iPos = 0; iPos < TAB_FREQUENCE.length; iPos ++ )
          statsMsg += "Face " + (iPos + 1) + " : " + TAB_FREQUENCE[iPos] + " fois\n\n";
        return statsMsg;
      public String getTotal()
        int total = 0;
        for ( int iPos = 0; iPos < TAB_FREQUENCE.length; iPos ++ )
          total += TAB_FREQUENCE[iPos];
        return "Le d� a �t� lanc� " + total + " fois";
      public void throwDice()
        unDe.throwAgain();
        TAB_FREQUENCE[unDe.getFace() - 1] ++;   
      public void paintComponent (Graphics g) 
        super.paintComponent(g);
        g.drawImage (imageDe.getImage(), aX, aY, null); // <---- THIS GENERATES THE NULLPOINTEREXCEPTION
      class EcouteurSouris extends MouseAdapter
        public void mouseClicked (MouseEvent pMouseEvent)
          aX = pMouseEvent.getX();
          aY = pMouseEvent.getY();
          throwDice();
          imageDe = new ImageIcon(TAB_IMAGE[unDe.getFace() - 1]);
          repaint();
    }When I click in the windows, a picture of a dice (different side, randomly generated by the method throwDice() ), when I click again the first image dissapear and another one appears... and I make statistics about the results.
    I tried ...
      public void paintComponent (Graphics g) 
        super.paintComponent(g);
        //g.drawImage (imageDe.getImage(), aX, aY, null);
      class EcouteurSouris extends MouseAdapter
        public void mouseClicked (MouseEvent pMouseEvent)
          aX = pMouseEvent.getX();
          aY = pMouseEvent.getY();
          throwDice();
          imageDe = new ImageIcon(TAB_IMAGE[unDe.getFace() - 1]);
          Graphics g = getGraphics();
          g.drawImage (imageDe.getImage(), aX, aY, null);
          g.dispose();
        }Everything works correctly, no more NullPointerException, but the images don't dissapear when I click again. They just stay there.
    I'm not completly familiar with the repaint/dispose/paintComponent but I really don't understand why i get this NullPointerException error :\
    If you see some weird words in the code, it's because i'm canadian-frenchy! :)
    Full program is here

    The real question is why are you trying to override the paintComponent() method. Just add the image to a JLabel and add the label to a panel.
    However, the problem is that the paintComponent() method is invoked when the frame is shown and since you don't create the image until you do a mouseClick, the image in null.

  • Problem with JFrame code

    Can anyone say the problem with the attached code. When I run the program, only, maximize, minimize and close options are viewable and nothing else.
    import java.awt.Color;
    import java.awt.Container;
    import java.awt.Dimension;
    import java.awt.FlowLayout;
    import java.awt.Graphics;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.Image;
    import java.awt.Insets;
    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    import javax.swing.border.LineBorder;
    * Created on Mar 24, 2008
    * @author Anand
    public class JBackGroundImageDemo extends JFrame
        Container con = null;
        JPanel panelBgImg;
        public JBackGroundImageDemo()
            setTitle("JBackGroundImageDemo");
            con = getContentPane();
            con.setLayout(null);
            ImageIcon imh = new ImageIcon("aditi.jpg");
            setSize(imh.getIconWidth(), imh.getIconHeight());
            panelBgImg = new JPanel()
                public void paintComponent(Graphics g)
                    Image img = new ImageIcon("aditi.jpg").getImage();
                    Dimension size = new Dimension(img.getWidth(null), img.getHeight(null));
                    setPreferredSize(size);
                    setMinimumSize(size);
                    setMaximumSize(size);
                    setSize(size);
                    setLayout(null);
                    g.drawImage(img, 0, 0, null);
            con.add(panelBgImg);
            panelBgImg.setBounds(0, 0, imh.getIconWidth(), imh.getIconHeight());
            GridBagLayout layout = new GridBagLayout();
            JPanel panelContent = new JPanel(layout);
            GridBagConstraints gc = new GridBagConstraints();
            gc.insets = new Insets(3, 3, 3, 3);
            gc.gridx = 1;
            gc.gridy = 1;
            JLabel label = new JLabel("UserName: ", JLabel.LEFT);                       
            panelContent.add(label, gc);
            gc.gridx = 2;
            gc.gridy = 1;
            JTextField txtName = new JTextField(10);
            panelContent.add(txtName, gc);
            gc.insets = new Insets(3, 3, 3, 3);
            gc.gridx = 1;
            gc.gridy = 2;
            gc.gridwidth = 2;
            JButton btn = new JButton("Login");
            panelContent.add(btn, gc);
            panelContent.setBackground(Color.GRAY);
            panelContent.setBorder(new LineBorder(Color.WHITE));
            panelBgImg.add(panelContent);
            panelBgImg.setLayout(new FlowLayout(FlowLayout.CENTER, 150, 200));
            setResizable(false);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        public static void main(String[] args)
            new JBackGroundImageDemo().setVisible(true);
         Please help.
    Regards,
    Anees

    Here's you a little code example, it works, so take a look at it.
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Image;
    import java.awt.MediaTracker;
    import java.awt.Toolkit;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    public class Junk{
      public Junk(){
      public void makeFrame(){
        JFrame j = new JFrame("Junk");
        Toolkit t = Toolkit.getDefaultToolkit();
        MediaTracker mt = new MediaTracker(j);
        Image img = t.getImage("junk.jpg");
        mt.addImage(img, 0);
        try{
          mt.waitForID(0);
        }catch(InterruptedException e){
          System.out.println("Hey, we were too impatient!");
        myPanel p = new myPanel(img);
        p.setPreferredSize(new Dimension(img.getWidth(null), img.getHeight(null)));
        j.add(p);
        j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        j.pack();
        j.setVisible(true);
      public static void main(String[] args){
        new Junk().makeFrame();
      class myPanel extends JPanel{
        Image img;
        myPanel(Image img){
          this.img = img;
        public void paintComponent(Graphics g){
          g.drawImage(img, 0, 0, this);
    }BTW: your image should be in your project folder.

  • Problem with ScrollPane and JFrame Size

    Hi,
    The code is workin but after change the size of frame it works CORRECTLY.Please help me why this frame is small an scrollpane doesn't show at the beginning.
    Here is the code:
    import java.awt.*;
    public class canvasExp extends Canvas
         private static final long serialVersionUID = 1L;
         ImageLoader map=new ImageLoader();
        Image img = map.GetImg();
        int h, w;               // the height and width of this canvas
         public void update(Graphics g)
            paint(g);
        public void paint(Graphics g)
                if(img != null)
                     h = getSize().height;
                     System.out.println("h:"+h);
                      w = getSize().width;
                      System.out.println("w:"+w);
                      g.drawRect(0,0, w-1, h-1);     // Draw border
                  //  System.out.println("Size= "+this.getSize());
                     g.drawImage(img, 0,0,this.getWidth(),this.getHeight(), this);
                    int width = img.getWidth(this);
                    //System.out.println("W: "+width);
                    int height = img.getHeight(this);
                    //System.out.println("H: "+height);
                    if(width != -1 && width != getWidth())
                        setSize(width, getHeight());
                    if(height != -1 && height != getHeight())
                        setSize(getWidth(), height);
    }I create frame here...
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.JFrame;
    public class frame extends JFrame implements MouseMotionListener,MouseListener
         private static final long serialVersionUID = 1L;
        private ScrollPane scrollPane;
        private int dragStartX;
        private int dragStartY;
        private int lastX;
        private int lastY;
        int cordX;
        int cordY;
        canvasExp canvas;
        public frame()
            super("test");
            canvas = new canvasExp();
            canvas.addMouseListener(this);
            canvas.addMouseMotionListener(this);
            scrollPane = new ScrollPane();
            scrollPane.setEnabled(true);
            scrollPane.add(canvas);
            add(scrollPane);
            setSize(300,300);
            pack();
            setVisible(true);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        public void mousePressed(MouseEvent e)
            dragStartX = e.getX();
            dragStartY = e.getY();
            lastX = getX();
            lastY = getY();
        public void mouseReleased(MouseEvent mouseevent)
        public void mouseClicked(MouseEvent e)
            cordX = e.getX();
            cordY = e.getY();
            System.out.println((new StringBuilder()).append(cordX).append(",").append(cordY).toString());
        public void mouseEntered(MouseEvent mouseevent)
        public void mouseExited(MouseEvent mouseevent)
        public void mouseMoved(MouseEvent mouseevent)
        public void mouseDragged(MouseEvent e)
            if(e.getX() != lastX || e.getY() != lastY)
                Point p = scrollPane.getScrollPosition();
                p.translate(dragStartX - e.getX(), dragStartY - e.getY());
                scrollPane.setScrollPosition(p);
    }...and call here
    public class main {
         public main(){}
         public static void main (String args[])
             frame f = new frame();
    }There is something I couldn't see here.By the way ImageLoader is workin I get the image.
    Thank you for your help,please answer me....

    I'm not going to even attempt to resolve the problem posted. There are other problems with your code that should take priority.
    -- class names by convention start with a capital letter.
    -- don't use the name of a common class from the standard API for your custom class, not even with a difference of case. It'll come back to bite you.
    -- don't mix awt and Swing components in the same GUI. Change your class that extends Canvas to extend JPanel instead, and override paintComponent(...) instead of paint(...).
    -- launch your GUI on the EDT by wrapping it in a SwingUtilities.invokeLater or EventQueue.invokeLater.
    -- calling setSize(...) followed by pack() is meaningless. Use one or the other.
    -- That's not the correct way to display a component in a scroll pane.
    Ah, well, and the problem is that when you call pack(), it retrieves the preferredSize of the components in the JFrame, and you haven't set a preferredSize for the scroll pane.
    Please, for your own good, take a break from whatever it is you're working on and go through The Java&#8482; Tutorials: [Creating a GUI with JFC/Swing|http://java.sun.com/docs/books/tutorial/uiswing/TOC.html]
    db

  • Problem with Background image and JFrame

    Hi there!
    I've the following problem:
    I created a JFrame with an integrated JPanel. In this JFrame I display a background image. Therefore I've used my own contentPane:
    public class MContentPane extends JComponent{
    private Image backgroundImage = null;
    public MContentPane() {
    super();
    * Returns the background image
    * @return Background image
    public Image getBackgroundImage() {
    return backgroundImage;
    * Sets the background image
    * @param backgroundImage Background image
    public void setBackgroundImage(Image backgroundImage) {
    this.backgroundImage = backgroundImage;
    * Overrides the painting to display a background image
    protected void paintComponent(Graphics g) {
    if (isOpaque()) {
    g.setColor(getBackground());
    g.fillRect(0, 0, getWidth(), getHeight());
    if (backgroundImage != null) {
    g.drawImage(backgroundImage,0,0,this);
    super.paintComponent(g);
    Now the background image displays correct. But as soon as I click on some combobox that is placed within the integrated JPanel I see fractals of the opened combobox on the background. When I minimize
    the Frame they disappear. Sometimes though I get also some fractals when resizing the JFrame.
    It seems there is some problem with the redrawing of the background e.g. it doesn't get redrawn as often as it should be!?
    Could anyone give me some hint, on how to achieve a clear background after clicking some combobox?
    Thx in advance

    I still prefer using a border to draw a background image:
    import java.awt.*;
    import java.awt.image.*;
    import javax.swing.border.*;
    public class CentredBackgroundBorder implements Border {
        private final BufferedImage image;
        public CentredBackgroundBorder(BufferedImage image) {
            this.image = image;
        public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
            int x0 = x + (width-image.getWidth())/2;
            int y0 = y + (height-image.getHeight())/2;
            g. drawImage(image, x0, y0, null);
        public Insets getBorderInsets(Component c) {
            return new Insets(0,0,0,0);
        public boolean isBorderOpaque() {
            return true;
    }And here is a demo where I load the background image asynchronously, so that I can launch the GUI before the image is done loading. Warning: you may find the image disturbing...
    import java.awt.*;
    import java.io.*;
    import java.net.URL;
    import javax.imageio.*;
    import javax.swing.*;
    import javax.swing.border.*;
    public class BackgroundBorderExample {
        public static void main(String[] args) throws IOException {
            JFrame.setDefaultLookAndFeelDecorated(true);
            JFrame f = new JFrame("BackgroundBorderExample");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            JTextArea area = new JTextArea(24,80);
            area.setForeground(Color.WHITE);
            area.setOpaque(false);
            area.read(new FileReader(new File("BackgroundBorderExample.java")), null);
            final JScrollPane sp = new JScrollPane(area);
            sp.setBackground(Color.BLACK);
            sp.getViewport().setOpaque(false);
            f.getContentPane().add(sp);
            f.setSize(600,400);
            f.setLocationRelativeTo(null);
            f.setVisible(true);
            String url = "http://today.java.net/jag/bio/JagHeadshot.jpg";
            final Border bkgrnd = new CentredBackgroundBorder(ImageIO.read(new URL(url)));
            Runnable r = new Runnable() {
                public void run() {
                    sp.setViewportBorder(bkgrnd);
                    sp.repaint();
            SwingUtilities.invokeLater(r);
    }

  • Problem with Listeners/ requestFocus()

    Hello,
    I am new to Java (started learning two months back), There is a problem with the requestFocus() in the focusListener. The program does not return the focus to the object indicated in the requestFocus but it shows multiple cusors!!
    The faculity at the institute where I am learning could not rectify the error.
    Is the error because of the myMethod() which I am using. I had made this method to prove to my professor that we can reduce the code drastically while using the gridbaglayout.
    The code which I had written is as under:
    // file name ShopperApplet.java
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class ShopperApplet extends JApplet implements ActionListener, FocusListener,Runnable
         //static JPanel sP;
         //static JPanel oP;
         JTabbedPane tabbedPane = new JTabbedPane();
         JPanel sP;
         JPanel oP;
         JPanel pwd = new JPanel();
         // Layout Decleration of oP
         GridBagLayout ordL = new GridBagLayout();
         GridBagConstraints ordC = new GridBagConstraints();
         // Layout Decleration of sP
         FlowLayout flow = new FlowLayout();
         // Variables of sP
              JTextField textShopperId;
              JPasswordField textPassword;
              JTextField textFirstName ;
              JTextField textLastName ;
              JTextField textEmailId ;
              JTextField textAddress ;
              JComboBox comboCity ;
              JTextField textState ;
              JTextField textCountryId ;
              JTextField textZipCode ;
              JTextField textPhone ;
              JTextField textCreditCardNo ;
              JRadioButton rbVisa;
              JRadioButton rbMaster;
              JRadioButton rbAmEx;
              ButtonGroup BGccType;
              //JComboBox comboCreditCardType;
              //JTextField textExperyDate;
              JComboBox cmbDt;
              JComboBox cmbMth;
              JComboBox cmbYear;
              JButton btnSubmit;
              JButton btnReset;          
         // Variables of oP
              // Variable Decleration od oP
              JTextField txtOrderNo;
              JTextField txtToyId;
              JTextField txtQty;
              JRadioButton rbYes;     
              JRadioButton rbNo;
              ButtonGroup bgGiftWrap;
              JComboBox cmbWrapperId;
              JTextField txtMsg;
              JTextField txtToyCost;
              JButton btnOSubmit;
              JButton btnOReset;     
         // Variables of pwd
              JTextField txtShopperId;
              JPasswordField txtPassword;
              JButton btnPSubmit;
              JButton btnPReset;     
              JButton btnPNew;
              JButton btnPLogoff;
              JLabel lblN, lblN1;     
              Thread t,t1;
         Font TNR = new Font("Times New Roman",1,15);
         Font arial = new Font("Arial",2,15);
         public void sPDet()
              //Variable Decleration of sP
              textShopperId = new JTextField(6);
              textPassword = new JPasswordField(4);
              textPassword.addFocusListener(this);
              //textPassword = new JTextField(4);
              textPassword.setEchoChar('*');
              textFirstName = new JTextField(20);
              textLastName = new JTextField(20);
              textEmailId = new JTextField(25);
              textAddress = new JTextField(20);
              String cityList[] = {"New Delhi", "Mumbai", "Calcutta", "Hyderabad"};
              comboCity = new JComboBox(cityList);
              comboCity.setEditable(true);
              textState = new JTextField(30);
              textCountryId = new JTextField(25);
              textZipCode = new JTextField(6);
              textPhone = new JTextField(25);
              textCreditCardNo = new JTextField(25);
              String cardTypes[] = {"Visa", "Master Card", "American Express"};
              //comboCreditCardType = new JComboBox(cardTypes);
              rbVisa = new JRadioButton("Visa");
              rbMaster = new JRadioButton("Master Card");
              rbAmEx = new JRadioButton("American Express");
              BGccType = new ButtonGroup();
              BGccType.add(rbVisa);
              BGccType.add(rbMaster);
              BGccType.add(rbAmEx);
              String stDt[] = {"1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26","27","28","29","30","31"};
              String stMth[] = {"January","February","March","April","May","June","July","August","September","October","November","December"};
              String stYear[] = {"2001","2002","2003","2004","2005","2006","2007","2008","2009","2010"};
              cmbDt = new JComboBox(stDt);
              cmbMth = new JComboBox(stMth);
              cmbYear = new JComboBox(stYear);
              //textExperyDate = new JTextField(10);
              btnSubmit = new JButton("Submit");
              btnReset = new JButton("Reset");
              // Adding Layout Controls
              sP.setLayout(ordL);
              sP.setBackground(Color.green);
              myLayout(textShopperId,3,1,sP,"FM","Shopper Id");
              myLayout(textPassword,3,2,sP,"FM","Password");
              myLayout(textFirstName,3,3,sP,"FM","First Name") ;
              myLayout(textLastName,3,4,sP,"FM","Last Name") ;
              myLayout(textEmailId,3,5,sP,"FM","E-Mail Id") ;
              myLayout(textAddress,3,6,sP,"FM", "Address") ;
              myLayout(comboCity,3,7,sP,"FM","City") ;
              myLayout(textState,3,8,sP,"FM","State") ;
              myLayout(textCountryId,3,9,sP,"FM","Country") ;
              myLayout(textZipCode,3,10,sP,"FM","Zip Code") ;
              myLayout(textPhone,3,11,sP,"FM","Phone") ;
              myLayout(textCreditCardNo,3,12,sP,"FM","Credit Card No.") ;
              //myLayout(rbVisa,3,13,sP);
              JPanel newPanel = new JPanel();
              newPanel.add(rbVisa);
              newPanel.add(rbMaster);
              newPanel.add(rbAmEx);
              myLayout(newPanel,3,13,sP,"FM","Credit Card Type");
              //myLayout(rbMaster,4,13);
              //myLayout(rbAmEx,5,13);
              JPanel newPanel1 = new JPanel();
              newPanel1.add(cmbDt);
              newPanel1.add(cmbMth);
              newPanel1.add(cmbYear);
              myLayout(newPanel1,3,14,sP,"FM","Expiry Date");
              //myLayout(textExperyDate,3,14,sP,"FM");
              myLayout(btnSubmit,1,17,sP,"AL","Submit");
              myLayout(btnReset,3,17,sP,"AL","Reset");          
         public void oPDet()
              txtOrderNo = new JTextField(10);
              txtToyId = new JTextField(10);
              txtQty = new JTextField(10);
              rbYes = new JRadioButton("Yes");
              rbNo = new JRadioButton("No");
              bgGiftWrap = new ButtonGroup();
              bgGiftWrap.add(rbYes);
              bgGiftWrap.add(rbNo);
              String wrapperTypes[] = {"Blue Stripes", "Red Checks", "Green Crosses","Yellow Circles", "Red & Purple Stripes"};
              cmbWrapperId = new JComboBox(wrapperTypes);
              txtMsg = new JTextField(10);
              txtToyCost = new JTextField(10);
              btnOSubmit = new JButton("Submit");
              btnOReset = new JButton("Reset");
              // Adding Controls to oP
              oP.setLayout(ordL);
              oP.setBackground(Color.yellow);
              myLayout(txtOrderNo,3,1,oP,"FM","Order No.");
              myLayout(txtToyId,3,2,oP,"FM","Toy Id");
              myLayout(txtQty,3,3,oP,"FM","Quantity");
              myLayout(rbYes,3,4,oP,"M");
              myLayout(rbNo,4,4,oP,"M");
              myLayout(cmbWrapperId,3,5,oP,"M","Wrapper Id");
              myLayout(txtMsg,3,6,oP,"FM","Message");
              myLayout(txtToyCost,3,7,oP,"FM","Toy Cost");
              myLayout(btnOSubmit,1,8,oP,"AL","Submit");
              myLayout(btnOReset,3,8,oP,"AL","Reset");          
         public void pwdDet()
              pwd.setLayout(ordL);
              pwd.setBackground(Color.green);
              t = new Thread(this);
              t.start();
              t1 = new Thread(this);
              t1.start();
              lblN = new JLabel("");
              lblN1 = new JLabel("");
              txtShopperId = new JTextField(10);
              txtPassword = new JPasswordField(10);
              btnPSubmit = new JButton("Submit") ;
              btnPReset = new JButton("Reset");     
              btnPNew = new JButton("New Member");
              btnPLogoff = new JButton("Log Off");
              pwd.setLayout(ordL);
              pwd.setBackground(Color.yellow);
              myLayout(lblN,3,7,pwd);
              myLayout(lblN1,3,8,pwd);
              myLayout(txtShopperId,3,1,pwd,"FM","Shopper Id.");
              myLayout(txtPassword,3,2,pwd,"FM","Password");
              myLayout(btnPSubmit,2,4,pwd,"AL","Submit");
              myLayout(btnPReset,3,4,pwd,"AL","Reset");          
              myLayout(btnPNew,2,5,pwd,"AL","New");
              myLayout(btnPLogoff,3,5,pwd,"AL","Log Off");
         public void run()
              int ctr =0;
              String ili[] = {"India","is","a","Great","Country"};
              int ctr1 = 0;
              String iib[] = {"India","is","the","Best"};
              Thread myThread = Thread.currentThread();
              if (myThread == t)
                   while (t != null)
                        lblN.setText(ili[ctr]);
                        ctr++;
                        if (ctr >=5) ctr=0;
                        try
                             t.sleep(500);
                        catch(InterruptedException e)
                             showStatus("India is a great Country has been interrupter");
              else
                   while (t1 != null)
                        lblN1.setText(iib[ctr1]);
                        ctr1++;
                        if (ctr1 >=4) ctr1=0;
                        try
                             t1.sleep(1000);
                        catch(InterruptedException e)
                             showStatus("India is the best has been interrupter");
         public void myLayout(JComponent aObj, int x, int y, JPanel aPanel,String aListener,String toolTip)
              ordC.anchor=GridBagConstraints.NORTHWEST;
              JLabel aLabel = new JLabel(toolTip);
              ordC.gridx = x-1;
              ordC.gridy = y;
              ordL.setConstraints(aLabel,ordC);
              aPanel.add(aLabel);
              aObj.setToolTipText("Enter "+toolTip+" here");
              aObj.setForeground(Color.red);
              aObj.setBackground(Color.green);
              if (aListener.indexOf("F")     != -1)
                   aObj.addFocusListener(this);
              //if (aListener.indexOf("M")     != -1)
                   //aObj.addMouseListener(this);
              aObj.setFont(TNR);
              ordC.gridx = x;
              ordC.gridy = y;
              ordL.setConstraints(aObj,ordC);
              aPanel.add(aObj);
         public void myLayout(JComponent aObj, int x, int y, JPanel aPanel,String aListener)
              ordC.anchor=GridBagConstraints.NORTHWEST;
              aObj.setForeground(Color.red);
              aObj.setBackground(Color.green);
              if (aListener.indexOf("F")     != -1)
                   aObj.addFocusListener(this);
              //if (aListener.indexOf("M")     != -1)
                   //aObj.addMouseListener(this);
              aObj.setFont(TNR);
              ordC.gridx = x;
              ordC.gridy = y;
              ordL.setConstraints(aObj,ordC);
              aPanel.add(aObj);
         public void myLayout(JButton aObj, int x, int y, JPanel aPanel,String aListener, String toolTip)
              aObj.setToolTipText(toolTip);
              ordC.anchor=GridBagConstraints.NORTHWEST;
              aObj.setForeground(Color.red);
              if (aListener.indexOf("F")     != -1)
                   aObj.addFocusListener(this);
              //if (aListener.indexOf("M")     != -1)
                   //aObj.addMouseListener(this);
              if (aListener.indexOf("A")     != -1)
                   aObj.addActionListener(this);
              aObj.setFont(TNR);
              ordC.gridx = x;
              ordC.gridy = y;
              ordL.setConstraints(aObj,ordC);
              aPanel.add(aObj);
         public void myLayout(JTextField aObj, int x, int y, JPanel aPanel,String aListener,String toolTip)
              ordC.anchor=GridBagConstraints.NORTHWEST;
              //aObj = new JTextField(10);
              JLabel aLabel = new JLabel(toolTip);
              ordC.gridx = x-1;
              ordC.gridy = y;
              ordL.setConstraints(aLabel,ordC);
              aPanel.add(aLabel);
              aObj.setToolTipText("Enter "+toolTip+" here");
              aObj.setForeground(Color.red);
              if (aListener.indexOf("F")     != -1)
                   aObj.addFocusListener(this);
              //if (aListener.indexOf("M")     != -1)
              //     aObj.addMouseListener(this);
              if (aListener.indexOf("A")     != -1)
                   aObj.addActionListener(this);
              aObj.setFont(TNR);
              ordC.gridx = x;
              ordC.gridy = y;
              ordL.setConstraints(aObj,ordC);
              aPanel.add(aObj);
         public void myLayout(JLabel aObj, int x, int y, JPanel aPanel)
              ordC.anchor=GridBagConstraints.SOUTH;
              aObj.setForeground(Color.blue);
              aObj.setFont(TNR);
              ordC.gridx = x;
              ordC.gridy = y;
              ordL.setConstraints(aObj,ordC);
              aPanel.add(aObj);
         public void init()
              getContentPane().add(tabbedPane);
              sP = new JPanel();
              sPDet();
              oP = new JPanel();
              oPDet();
              pwdDet();
              tabbedPane.addTab("Login",null,pwd,"Login");
              tabbedPane.addTab("Shopper",null,sP,"Shopper Details");
              tabbedPane.addTab("Order",null,oP,"Order Details");
              tabbedPane.setEnabledAt(2, false);
              tabbedPane.setEnabledAt(1, false);
         public void actionPerformed(ActionEvent e)
              Object obj = e.getSource();
              if (obj == btnSubmit)
                   if (validShopperId() == false) return;
                   if (validPassword() == false) return;
                   if (validFirstName() == false) return ;
                   if (validLastName() == false) return ;
                   if (validEmailId() == false) return;
                   if (validAddress() == false) return;
                   if (validState() == false) return;
                   if (validCountryId() == false) return;
                   if (validZipCode() == false) return;
                   if (validCreditCardNo() == false) return ;
                   resetShopper();
                   tabbedPane.setEnabledAt(1,false);
                   tabbedPane.setEnabledAt(2,false);
                   tabbedPane.setSelectedIndex(0);
                   // also can be written as tabbedPane.setSelectedComponent(pwd);
                   //tabbedPane.remove(sP);
              if (obj == btnReset)
                   resetShopper();
                   tabbedPane.setEnabledAt(2,false);
                   //textExperyDate.setText("");
              if (obj == btnOSubmit)
                   if (validOrderNo() == false) return;
                   if (validToyId() == false) return;
                   if (chkNullEntry(txtQty, "Quantity")) return ;
                   if (chkNullEntry(txtToyCost, "Toy Cost")) return ;
              if (obj == btnOReset)
                   resetOrder();
              if (obj == btnPSubmit)
                   if (validPShopperId() && validPPassword())
                        tabbedPane.setEnabledAt(2, true);
                        tabbedPane.setEnabledAt(1, false);
                        txtShopperId.setText("");
                        txtPassword.setText("");
                        resetPassword();
                        //tabbedPane.addTab("Order",null,oP,"Order Details");
              if (obj == btnPReset)
                   resetPassword();
                   tabbedPane.setEnabledAt(1, false);
                   tabbedPane.setEnabledAt(2, false);
              if (obj == btnPNew)
                   tabbedPane.setEnabledAt(1, true);
                   tabbedPane.setEnabledAt(2, false);
                   resetPassword();
                   tabbedPane.setSelectedComponent(sP);
                   //tabbedPane.addTab("Shopper",null,sP,"Shopper Details");          
              if (obj == btnPLogoff)
                   tabbedPane.setEnabledAt(2, false);
                   tabbedPane.setEnabledAt(1, false);
                   resetPassword();
         public void focusGained(FocusEvent fe)
              //Object aObj = fe.getSource();
              //showStatus("Current Object is "+aObj);
         public void resetPassword()
              txtShopperId.setText("");
              txtPassword.setText("");
         public void resetShopper()
                   textShopperId.setText("");
                   textPassword.setText("");
                   textFirstName.setText("") ;
                   textLastName.setText("") ;
                   textEmailId.setText("") ;
                   textAddress.setText("") ;
                   textState.setText("") ;
                   textCountryId.setText("") ;
                   textZipCode.setText("") ;
                   textPhone.setText("") ;
                   textCreditCardNo.setText("") ;
         public void resetOrder()
              txtOrderNo.setText("");
              txtToyId.setText("");
              txtQty.setText("") ;
              txtToyCost.setText("") ;
              txtMsg.setText("") ;
         public void focusLost(FocusEvent fe)
              try{
                   Object obj = fe.getSource();
                   if (obj == textShopperId &&     validShopperId() == false)
                        //textShopperId.requestFocus();
                        return;
                   if (obj == textPassword && validPassword() == false)
                        //textPassword.requestFocus();
                        return;
                   if (obj == textFirstName && validFirstName() == false)
                        //textFirstName.requestFocus();
                        return;
                   if (obj == textEmailId && validEmailId() == false)
                        //textEmailId.requestFocus();
                        return;
                   if (obj == txtOrderNo && validOrderNo() == false)
                        //txtOrderNo.requestFocus();
                        return;
                   if (obj == txtToyId && validToyId() == false);
                        //txtToyId.requestFocus();
                        return;
              catch(Exception e)
                   showStatus("error in LostFocus() Method");
         public boolean validShopperId()
              if (chkNullEntry(textShopperId,"Shopper Id")) return false;
              return true;
         public boolean validPassword()
              if (chkNullEntry(textPassword,"Password")) return false;
              return true;
         public boolean validFirstName()
              if (chkNullEntry(textFirstName,"First Name")) return false;
              return true;
         public boolean validLastName()
              if (chkNullEntry(textLastName,"Last Name")) return false;
              return true;
         public boolean validAddress()
              if (chkNullEntry(textAddress,"Address")) return false;
              return true;
         public boolean validState()
              if (chkNullEntry(textState,"State")) return false;
              return true;
         public boolean validCountryId()
              if (chkNullEntry(textCountryId,"Country")) return false;
              return true;
         public boolean validZipCode()
              if (chkNullEntry(textZipCode,"Postal Code")) return false;
              return true;
         public boolean validCreditCardNo()
              if (chkNullEntry(textCreditCardNo,"Credit Card No.")) return false;
              return true;
         public boolean validEmailId()
              if (chkNullEntry(textEmailId,"Email Address")) return false;
              String s1 = textEmailId.getText();
              int abc = s1.indexOf("@");
              if (abc == -1 || abc == 0 || abc == (s1.length()-1))
                   JOptionPane.showMessageDialog(sP,"Invalid Email Address","Error Message",JOptionPane.ERROR_MESSAGE);
                   //textEmailId.requestFocus();
                   return false;
              return true;
         public boolean validOrderNo()
              if (chkNullEntry(txtOrderNo,"Order No.")) return false;
              return true;
         public boolean validToyId()
              if (chkNullEntry(txtToyId,"Toy Id")) return false;
              return true;
         public boolean chkNullEntry(JTextField aObj,String sDef)
              String s1 = aObj.getText();
              if (s1.length() ==0)
                   try
                        JOptionPane.showMessageDialog(sP,sDef+" cannot be left blank","Error Message",JOptionPane.ERROR_MESSAGE);
                        //showStatus(sDef+" cannot be left blank");
                        // nbvvvv vcz     z111111eeeefgggggggggg aObj.requestFocus();
                   catch(Exception e)
                        showStatus("Error in chkNullEntry() method");
                   return true ;
              else
                   return false;
         public boolean validPShopperId()
              if (chkNullEntry(txtShopperId,"Shopper Id")) return false;
              return true;
         public boolean validPPassword()
              if (chkNullEntry(txtPassword,"Password")) return false;
              return true;
    // end of code.

    Would it not be acceptable to check that each field has a value when Submit is pressed. If a field is found with no data then display the error message and return the focus to the empty field. This would solve the multiple cursors problem as you would not need any focusLost handler code.
    If this is entirely out of the question then you will have to override some of the FocusManager methods to prevent the JVM from handling focus for you :
    FocusManager.setCurrentManager(new DefaultFocusManager() {
      // Override FocusManager methods here.
    });Ronny.

  • Problem with focus border and ListCellRenderer in custom listbox

    I have a bug in some code that I adapted from another posting on this board -- basically what I've done is I have a class that implements a custom "key/value" mapping listbox in which each list item/cell is actually a JPanel consisting of 3 JLabels: the first label is the "key", the second is a fixed "==>" mapping string, and the 3rd is the value to which "key" is mapped.
    The code works fine as long as the list cell doesn't have the focus. When it does, it draws a border rectangle to indicate focus, but if the listbox needs to scroll horizontally to display all the text, part of the text gets cut off (i.e. "sometex..." where "sometext" should be displayed).
    The ListCellRenderer creates a Gridlayout to lay out the 3 labels in the cell's JPanel.
    What can I do to remedy this situation? I'm not sure what I'd need to do in terms of setting the size of the panel so that all the text gets displayed OK within the listbox. Or if there's something else I can do to fix this. The code and a main() to run the code are provided below. To reproduce the problem, click the Add Left and Add Right buttons to add a "mapping" -- when it doesn't have focus, everything displays fine, but when you give it focus, note the text on the right label gets cut off.
    //======================================================================
    // Begin Source Listing
    //======================================================================
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.Collection;
    import java.util.Iterator;
    import java.util.Vector;
    import java.util.Enumeration;
    public class TwoColumnListbox extends JPanel
    private JList m_list;
    private JScrollPane m_Pane;
    public TwoColumnListbox(Collection c)
         DataMapListModel model = new DataMapListModel();
         if (c != null)
         Iterator it = c.iterator();
         while (it.hasNext())
         model.addElement(it.next());
         m_list = new JList(model);
         ListBoxRenderer renderer= new ListBoxRenderer();
              m_list.setCellRenderer(renderer);
              setLayout(new BorderLayout());
              m_list.setVisibleRowCount(4);
              m_Pane = new JScrollPane(m_list);
              add(m_Pane, BorderLayout.NORTH);
    public JList getList()
    return m_list;
    public JScrollPane getScrollPane()
    return m_Pane;
    public static void main(String s[])
              JFrame frame = new JFrame("TwoColumnListbox");
              frame.addWindowListener(new WindowAdapter() {
              public void windowClosing(WindowEvent e) {System.exit(0);}
    final DataMappings dm = new DataMappings();
    final TwoColumnListbox lb = new TwoColumnListbox(dm.getMappings());
              final DataMap map = new DataMap();
              JButton leftAddBtn = new JButton("Add Left");
              leftAddBtn.addActionListener(new ActionListener() {
              public void actionPerformed(ActionEvent e)
              map.setSource("JButton1");
              DefaultListModel model = new DefaultListModel();
              model.addElement(map);
              lb.getList().setModel(model);
              JButton leftRemoveBtn = new JButton("Remove Left");
              leftRemoveBtn.addActionListener(new ActionListener() {
              public void actionPerformed(ActionEvent e)
              map.setSource("");
              DefaultListModel model = new DefaultListModel();
              model.addElement(map);
              lb.getList().setModel(model);
              JButton rightAddBtn = new JButton("Add Right");
    rightAddBtn.addActionListener(new ActionListener() {
              public void actionPerformed(ActionEvent e)
              map.setDestination("/getQuote/symbol[]");
              DefaultListModel model = new DefaultListModel();
              model.addElement(map);
              lb.getList().setModel(model);
              JButton rightRemoveBtn = new JButton("Remove Right");
    rightRemoveBtn.addActionListener(new ActionListener() {
              public void actionPerformed(ActionEvent e)
              map.setDestination("");
              DefaultListModel model = new DefaultListModel();
              model.addElement(map);
              lb.getList().setModel(model);
              JPanel leftPanel = new JPanel(new BorderLayout());
              leftPanel.add(leftAddBtn, BorderLayout.NORTH);
              leftPanel.add(leftRemoveBtn, BorderLayout.SOUTH);
    JPanel rightPanel = new JPanel(new BorderLayout());
              rightPanel.add(rightAddBtn, BorderLayout.NORTH);
              rightPanel.add(rightRemoveBtn, BorderLayout.SOUTH);
    frame.getContentPane().add(leftPanel, BorderLayout.WEST);
              frame.getContentPane().add(lb,BorderLayout.CENTER);
    frame.getContentPane().add(rightPanel, BorderLayout.EAST);
              frame.pack();
              frame.setVisible(true);
         class ListBoxRenderer extends JPanel implements ListCellRenderer
              private JLabel left;
              private JLabel arrow;
              private JLabel right;
              private Color clrForeground = UIManager.getColor("List.foreground");
    private Color clrBackground = UIManager.getColor("List.background");
    private Color clrSelectionForeground = UIManager.getColor("List.selectionForeground");
    private Color clrSelectionBackground = UIManager.getColor("List.selection.Background");
              public ListBoxRenderer()
                   setLayout(new GridLayout(1, 2, 10, 0));
                   //setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));
                   left = new JLabel("");
                   left.setForeground(clrForeground);               
                   arrow = new JLabel("");
                   arrow.setHorizontalAlignment(SwingConstants.CENTER);
                   arrow.setForeground(clrForeground);
                   right = new JLabel("");
                   right.setHorizontalAlignment(SwingConstants.RIGHT);
                   right.setForeground(clrForeground);
                   add(left);
                   add(arrow);
                   add(right);
              public Component getListCellRendererComponent(JList list, Object value,
                        int index, boolean isSelected, boolean cellHasFocus)
                   if (isSelected)
                        setBackground(list.getSelectionBackground());
                        setForeground(list.getSelectionForeground());
                        left.setForeground(clrSelectionForeground);
                        arrow.setForeground(clrSelectionForeground);
                        right.setForeground(clrSelectionForeground);
                   else
                        setBackground(list.getBackground());
                        setForeground(list.getForeground());
                   left.setForeground(clrForeground);
                        arrow.setForeground(clrForeground);
                        right.setForeground(clrForeground);               
                   // draw focus rectangle if control has focus. Problem with focus
    // and cut off text!!
                   if (cellHasFocus)
                   // FIXME: for Windows LAF I'm not getting the correct thing here for some reason.
                   // Looks OK on Metal though.
                   setBorder(BorderFactory.createLineBorder(UIManager.getColor("focusCellHighlightBorder")));
                   else
                   setBorder(BorderFactory.createEmptyBorder());               
    DataMap map = (DataMap) value;
                   String displaySource = map.getSource();
                   String displayDest = map.getDestination();
                   left.setText(displaySource);
                   arrow.setText("=>to<=");
                   right.setText(displayDest);
                   return this;
    /** Interface for macro editor UI
    * @version 1.0
    class DataMappings
    private Collection mappings;
    public DataMappings()
    setMappings(new Vector(0));
    public DataMappings(Collection maps)
    setMappings(maps);
    /** gets mapping value of a specified source object
    * @param src -- the "key" or source object, what is mapped.
    * @return what the source object is mapped to
    * @version 1.0
    public Object getValue(String src)
    if (src != null)
    Iterator it = mappings.iterator();
    while (it.hasNext());
    DataMap thisMap = (DataMap) it.next();
    if (thisMap.getSource().equals(src))
    return thisMap.getDestination();
    return null;
    /** sets mapping value of a specified source object
    * @param src -- the "key" or source object, what is mapped.
    * @param what the source object is to be mapped to
    * @version 1.0
    public void setValue(String src, String dest)
    if (src != null)
    // see if the value is in there first.
    Iterator it = mappings.iterator();
    while (it.hasNext())
    DataMap thisMap = (DataMap) it.next();
    if (thisMap.getSource().equals(src))
    thisMap.setDestination(dest);
    return;
    // not in the collection, add it
    mappings.add(new DataMap(src, dest));
    /** gets collection of mappings
    * @return a collection of all mappings in this object.
    * @version 1.0
    public Collection getMappings()
    return mappings;
    /** sets collection of mappings
    * @param maps a collection of src to destination mappings.
    * @version 1.0
    public void setMappings(Collection maps)
    mappings = maps;
    /** adds a DataMap
    * @param map a DataMap to add to the mappings
    * @version 1.0
    public void add(DataMap map)
    if (map != null)
    mappings.add(map);
    class DataMap
    public DataMap() {}
    public DataMap(String source, String destination)
    m_source = source;
    m_destination = destination;
    public String getSource()
    return m_source;
    public void setSource(String s)
    m_source = s;
    public String getDestination()
    return m_destination;
    public void setDestination(String s)
    m_destination = s;
    protected String m_source = null;
    protected String m_destination = null;
    /** list model for datamaps that provides ways
    * to determine whether a source is already mapped or
    * a destination is already mapped.
    class DataMapListModel extends DefaultListModel
    public DataMapListModel()
    super();          
    /** determines whether a source is already mapped
    * @param src -- the source property of a datamapping
    * @return true if the source is in the list, false if not
    public boolean containsSource(Object src)
    Enumeration enum = elements();
    while (enum.hasMoreElements())
    DataMap dm = (DataMap) enum.nextElement();
    if (dm.getSource().equals(src))
    return true;
    return false;
    /** determines whether a destination is already mapped
    * @param dest -- the destination property of a datamapping
    * @return true if the destination is in the list, false if not
    public boolean containsDest(Object dest)
    Enumeration enum = elements();
    while (enum.hasMoreElements())
    DataMap dm = (DataMap) enum.nextElement();
    if (dm.getDestination().equals(dest))
    return true;
    return false;
    public DataMappings getDataMaps()
    DataMappings maps = new DataMappings();
    // add all the datamaps in the model
    Enumeration enum = elements();
    while (enum.hasMoreElements())
    DataMap dm = (DataMap) enum.nextElement();
    maps.add(dm);
    return maps;
    //======================================================================
    // End of Source Listing
    //======================================================================

    I did not read the program, but the chopping looks like a layout problem.
    I think it's heavy to use a panel + 3 components in a gridlayout for each cell. look at this sample where i draw the Cell myself,
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.util.*;
    public class Jlist3 extends JFrame 
         Vector      v  = new Vector();
         JList       jc = new JList(v);
         JScrollPane js = new JScrollPane(jc);
    public Jlist3()
         addWindowListener(new WindowAdapter()
        {     public void windowClosing(WindowEvent ev)
              {     dispose();
                   System.exit(0);}});
         for (int j=0; j < 70; j++)     v.add(""+j*1000+"a  d"+j);
           setBounds(1,1,400,310);
         getContentPane().add(js);
         js.setPreferredSize(new Dimension(230,259));
         jc.setSelectedIndex(1);
         jc.setCellRenderer(new MyCellRenderer());
         getContentPane().setLayout(new FlowLayout());
         setVisible(true);
    public class MyCellRenderer extends JLabel implements ListCellRenderer
         String  txt;
         int     idx;
         boolean sel;
    public Component getListCellRendererComponent(JList list,
                             Object  value,           // value to display
                             int     index,           // cell index
                             boolean isSelected,      // is the cell selected
                             boolean cellHasFocus)    // the list and the cell have the focus
         idx = index;
         txt = value.toString();
         sel = isSelected;
         setText(txt);
         return(this);
    public void paintComponent(Graphics g)
         if (idx%2 == 1) g.setColor(Color.white);
              else        g.setColor(Color.lightGray);
         if (sel)        g.setColor(Color.blue);
         g.fillRect(0,0,getWidth(),getHeight());
         StringTokenizer st = new StringTokenizer(txt.trim()," ");
         g.setColor(Color.black);
         if (st.hasMoreTokens())     g.drawString(st.nextToken(),1,14);
         g.setColor(Color.red);
         g.drawString("===>",70,14);
         g.setColor(Color.black);
         if (st.hasMoreTokens())     g.drawString(st.nextToken(),110,14);
    public static void main (String[] args) 
         new Jlist3();
    Noah
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.util.*;
    public class Jlist3 extends JFrame
         Vector v = new Vector();
         JList jc = new JList(v);
         JScrollPane js = new JScrollPane(jc);
    public Jlist3()
         addWindowListener(new WindowAdapter()
    {     public void windowClosing(WindowEvent ev)
              {     dispose();
                   System.exit(0);}});
         for (int j=0; j < 70; j++)     v.add(""+j*1000+"a d"+j);
         setBounds(1,1,400,310);
         getContentPane().add(js);
         js.setPreferredSize(new Dimension(230,259));
         jc.setSelectedIndex(1);
         jc.setCellRenderer(new MyCellRenderer());
         getContentPane().setLayout(new FlowLayout());
         setVisible(true);
    public class MyCellRenderer extends JLabel implements ListCellRenderer
         String txt;
         int idx;
         boolean sel;
    public Component getListCellRendererComponent(JList list,
                             Object value, // value to display
                             int index, // cell index
                             boolean isSelected, // is the cell selected
                             boolean cellHasFocus) // the list and the cell have the focus
         idx = index;
         txt = value.toString();
         sel = isSelected;
         setText(txt);
         return(this);
    public void paintComponent(Graphics g)
         if (idx%2 == 1) g.setColor(Color.white);
              else g.setColor(Color.lightGray);
         if (sel) g.setColor(Color.blue);
         g.fillRect(0,0,getWidth(),getHeight());
         StringTokenizer st = new StringTokenizer(txt.trim()," ");
         g.setColor(Color.black);
         if (st.hasMoreTokens())     g.drawString(st.nextToken(),1,14);
         g.setColor(Color.red);
         g.drawString("===>",70,14);
         g.setColor(Color.black);
         if (st.hasMoreTokens())     g.drawString(st.nextToken(),110,14);
    public static void main (String[] args)
         new Jlist3();
    }

  • Problem with a template method in JDialog

    Hi friends,
    I'm experiencing a problem with JDialog. I have a base abstract class ChooseLocationDialog<E> to let a client choose a location for database. This is an abstract class with two abstract methods:
    protected abstract E prepareLocation();
    protected abstract JPanel prepareForm();Method prepareForm is used in the constructor of ChooseLocationDialog to get a JPanel and add it to content pane.
    Method prepareLocation is used to prepare location of a database. I have to options - local file and networking.
    There are two subclasses ChooseRemoteLocationDialog and ChooseLocalFileDialog.
    When I start a local version, ChooseLocalFileDialog with one input field for local file, everything works fine and my local client version starts execution.
    The problem arises when I start a network version of my client. Dialog appears and I can enter host and port into the input fields. But when I click Select, I get NullPointerException. During debugging I noticed that the values I entered into these fields ("localhost" for host and "10999" for port) were not set for corresponding JTextFields and when my code executes getText() method for these input fields it returns empty strings. This happens only for one of these dialogs - for the ChooseRemoteLocationDialog.
    The code for ChooseLocationDialog class:
    public abstract class ChooseLocationDialog<E> extends JDialog {
         private E databaseLocation;
         private static final long serialVersionUID = -1630416811077468527L;
         public ChooseLocationDialog() {
              setTitle("Choose database location");
              setAlwaysOnTop(true);
              setModal(true);
              Container container = getContentPane();
              JPanel mainPanel = new JPanel();
              //retrieving a form of a concrete implementation
              JPanel formPanel = prepareForm();
              mainPanel.add(formPanel, BorderLayout.CENTER);
              JPanel buttonPanel = new JPanel(new GridLayout(1, 2));
              JButton okButton = new JButton(new SelectLocationAction());
              JButton cancelButton = new JButton(new CancelSelectAction());
              buttonPanel.add(okButton);
              buttonPanel.add(cancelButton);
              mainPanel.add(buttonPanel, BorderLayout.SOUTH);
              container.add(mainPanel);
              pack();
              Toolkit toolkit = Toolkit.getDefaultToolkit();
              Dimension screenSize = toolkit.getScreenSize();
              int x = (screenSize.width - getWidth()) / 2;
              int y = (screenSize.height - getHeight()) / 2;
              setLocation(x, y);
              addWindowListener(new WindowAdapter() {
                   @Override
                   public void windowClosing(WindowEvent e) {
                        super.windowClosing(e);
                        System.exit(0);
         public E getDatabaseLocation() {
                return databaseLocation;
         protected abstract E prepareLocation();
         protected abstract JPanel prepareForm();
          * Action for selecting location.
          * @author spyboost
         private class SelectLocationAction extends AbstractAction {
              private static final long serialVersionUID = 6242940810223013690L;
              public SelectLocationAction() {
                   putValue(Action.NAME, "Select");
              @Override
              public void actionPerformed(ActionEvent e) {
                   databaseLocation = prepareLocation();
                   setVisible(false);
         private class CancelSelectAction extends AbstractAction {
              private static final long serialVersionUID = -1025433106273231228L;
              public CancelSelectAction() {
                   putValue(Action.NAME, "Cancel");
              @Override
              public void actionPerformed(ActionEvent e) {
                   System.exit(0);
    }Code for ChooseLocalFileDialog
    public class ChooseLocalFileDialog extends ChooseLocationDialog<String> {
         private JTextField fileTextField;
         private static final long serialVersionUID = 2232230394481975840L;
         @Override
         protected JPanel prepareForm() {
              JPanel panel = new JPanel();
              panel.add(new JLabel("File"));
              fileTextField = new JTextField(15);
              panel.add(fileTextField);
              return panel;
         @Override
         protected String prepareLocation() {
              String location = fileTextField.getText();
              return location;
    }Code for ChooseRemoteLocationDialog
    public class ChooseRemoteLocationDialog extends
              ChooseLocationDialog<RemoteLocation> {
         private JTextField hostField;
         private JTextField portField;
         private static final long serialVersionUID = -2282249521568378092L;
         @Override
         protected JPanel prepareForm() {
              JPanel panel = new JPanel(new GridLayout(2, 2));
              panel.add(new JLabel("Host"));
              hostField = new JTextField(15);
              panel.add(hostField);
              panel.add(new JLabel("Port"));
              portField = new JTextField(15);
              panel.add(portField);
              return panel;
         @Override
         protected RemoteLocation prepareLocation() {
              String host = hostField.getText();
              int port = 0;
              try {
                   String portText = portField.getText();
                   port = Integer.getInteger(portText);
              } catch (NumberFormatException e) {
                   e.printStackTrace();
              RemoteLocation location = new RemoteLocation(host, port);
              return location;
    }Code for RemoteLocation:
    public class RemoteLocation {
         private String host;
         private int port;
         public RemoteLocation() {
              super();
         public RemoteLocation(String host, int port) {
              super();
              this.host = host;
              this.port = port;
         public String getHost() {
              return host;
         public void setHost(String host) {
              this.host = host;
         public int getPort() {
              return port;
         public void setPort(int port) {
              this.port = port;
    }Code snippet for dialog usage in local client implementation:
    final ChooseLocationDialog<String> dialog = new ChooseLocalFileDialog();
    dialog.setVisible(true);
    location = dialog.getDatabaseLocation();
    String filePath = location;Code snippet for dialog usage in network client implementation:
    final ChooseLocationDialog<RemoteLocation> dialog = new ChooseRemoteLocationDialog();
    dialog.setVisible(true);
    RemoteLocation location = dialog.getDatabaseLocation();Exception that I'm getting:
    Exception occurred during event dispatching:
    java.lang.NullPointerException
         at suncertify.client.gui.dialog.ChooseRemoteLocationDialog.prepareLocation(ChooseRemoteLocationDialog.java:42)
         at suncertify.client.gui.dialog.ChooseRemoteLocationDialog.prepareLocation(ChooseRemoteLocationDialog.java:1)
         at suncertify.client.gui.dialog.ChooseLocationDialog$SelectLocationAction.actionPerformed(ChooseLocationDialog.java:87)
         at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
         at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
         at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
         at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
         at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
         at java.awt.Component.processMouseEvent(Component.java:6134)
         at javax.swing.JComponent.processMouseEvent(JComponent.java:3265)
         at java.awt.Component.processEvent(Component.java:5899)
         at java.awt.Container.processEvent(Container.java:2023)
         at java.awt.Component.dispatchEventImpl(Component.java:4501)
         at java.awt.Container.dispatchEventImpl(Container.java:2081)
         at java.awt.Component.dispatchEvent(Component.java:4331)
         at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4301)
         at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3965)
         at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3895)
         at java.awt.Container.dispatchEventImpl(Container.java:2067)
         at java.awt.Window.dispatchEventImpl(Window.java:2458)
         at java.awt.Component.dispatchEvent(Component.java:4331)
         at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
         at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
         at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
         at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:178)
         at java.awt.Dialog$1.run(Dialog.java:1046)
         at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
         at java.awt.EventQueue.dispatchEvent(EventQueue.java:597)
         at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
         at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
         at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)java version "1.6.0"
    OpenJDK Runtime Environment (build 1.6.0-b09)
    OpenJDK Client VM (build 1.6.0-b09, mixed mode, sharing)
    OS: Ubuntu 8.04
    Appreciate any help.
    Thanks.
    Edited by: spyboost on Jul 24, 2008 5:38 PM

    What a silly error! I have to call Integer.parseInt instead of getInt. Integer.getInt tries to find a system property. A small misprint, but a huge amount of time to debug. I always use parseInt method and couldn't even notice that silly misprint. Sometimes it's useful to see the trees instead of whole forest :)
    It works perfectly. Sorry for disturbing.

Maybe you are looking for