MyClass extends JPanel implements ActionListener (is that possible?)

I have tried the above and it doesn't allow me to addActionListener(this) in the constructor, which I usually do with JButtons, so I don't know what to do? I can always do the mouseListener but the ActionListener is more of what I want... Is there a way around that or a suggestion you could offer?

I have tried the above and it doesn't allow me to
addActionListener(this) in the constructor, which I
usually do with JButtons, so I don't know what to do?
I can always do the mouseListener but the
ActionListener is more of what I want... Is there a
way around that or a suggestion you could offer?You're calling addActionListener(this); , right?
If so, what you're essentially doing is adding the object itself as its own ActionListener!
I'm not sure if this is illegal.. ??
And anyway, JPanel does not have the method addActionListener(someActionListener);It looks like this is the main problem.
is it?
regards :o)
lutha

Similar Messages

  • Closing a class that extends JPanel

    Hi, i have a class that extends JPanel(lets call it class A). In that class, if the user click the logout button, i want class A to close and display class B that extends JFrame. right now, i am able to call class B, but i cannot close class A.
    I uses remove() to close class A, but it doesnt work... could u tell me what to do??
    I put this code in class A...
    if (e.getSource() == logoutButton)     {
         remove(this);
         new Rest_Login1();
         String [] ar = null;
         Rest_Login1.main(ar);
    } Thx

    so i want to remove the CustomerPanel3 and display the Rest_Login1...
    some of my code look like this.
    thx
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class CustomerPanel3 extends JPanel implements ActionListener
    // some JButton, JLabel n etc
         public void actionPerformed (ActionEvent e)
              if (e.getSource() == logoutButton)     {
                   remove(this);
                   new Rest_Login1();
                   String [] ar = null;
                   Rest_Login1.main(ar);
    public class Rest_Login1 {
         public static void main(String args[])
              JFrame login1 = new JFrame("Login User Interface");
              JFrame.setDefaultLookAndFeelDecorated(true);
              RestaurantLogin userpan = new RestaurantLogin();
              login1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              login1.setSize(600, 250);
              login1.setLocation(230,192);
              login1.getContentPane().add(userpan);
              login1.setVisible(true);
    }

  • JEditorPane (or subclasses) and a class that extends JPanel

    hello to all,
    i'm realizing an application with Swing.
    i have realized a class that extends JPanel(called "PanelLayer") and, other to draw a ruler as Office 2003, it must contain an other subclass of JPanel (called "PanelLayer") that, in turn, will contain a JEditorPane.
    the problem is strange: i should continue in moviment the mouse to look well the JEditorPane (or subclasses)
    the URL is a image of the result that i get...
    URL : http://phantom89.helloweb.eu/img/img.jpg
    codes:
    public class Layer extends JPanel implements ComponentListener{
        private static final long serialVersionUID = 1L;
        private Rectangle2D.Double areaCentrale = new Rectangle2D.Double(100,100,850,1285);
        private double larghFoglio = 21.0*50;
        private double altFoglio = 29.7*50;
        private double zoom = 1.0;
        private JScrollPane sp = new JScrollPane(this);
        private Rectangle2D.Double posFoglio = new Rectangle2D.Double();
        private int lastX,lastY;
        private PanelLayer pl;
        private Point mouse = null;
        private JEditorPane text;
        public Layer(PanelLayer pl){
            this.setLayout(null);
            this.pl = pl;
            this.setPreferredSize(new Dimension((int)(40+larghFoglio*zoom), (int)(100+altFoglio*zoom)));
            areaCentrale = new Rectangle2D.Double(100*zoom,100*zoom,850*zoom,1285*zoom);
                sp.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
            sp.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
            //try{
                text = new JEditorPane();
                text.setBounds(50,50,200,200);
                this.add(text);
            //}catch(IOException e){}
            lastX = sp.getHorizontalScrollBar().getValue();
            lastY = sp.getVerticalScrollBar().getValue();
            this.addComponentListener(this);
            this.addMouseListener(this);
            this.addMouseMotionListener(this);
        public void paintComponent(Graphics g){
            if(posFoglio.height + posFoglio.width == 0){
                this.posFoglio = new Rectangle2D.Double((this.getWidth()-larghFoglio*zoom)/2,50,larghFoglio*zoom,altFoglio*zoom);       
            Graphics2D g2d = (Graphics2D)g;
            g2d.setPaint(Color.lightGray);
            g2d.fillRect(0,0,this.getWidth(),this.getHeight());
            g2d.translate((this.getWidth()-larghFoglio*zoom)/2,50);
            g2d.setPaint(Color.black);
            g2d.draw(new Rectangle2D.Double(0,0,larghFoglio*zoom,altFoglio*zoom));
            g2d.setPaint(Color.white);
            g2d.fill(new Rectangle2D.Double(1,1,larghFoglio*zoom-1,altFoglio*zoom-1));
            g2d.setPaint(Color.blue);
            g2d.draw(areaCentrale);
        public JScrollPane getJScrollPane(){
            return sp;
        public Rectangle2D.Double getDimFoglio(){       
            return this.posFoglio;
        public double getCmWidth(){
            return larghFoglio*zoom/50+((larghFoglio*zoom/50)%1 <= getIncr() ? 0 : getIncr());
        public double getCmHeight(){
            return altFoglio*zoom/50+((altFoglio*zoom/50)%1 <= getIncr() ? 0 : getIncr());
        public Point getPointMouse(){
            return mouse;
        public void refresh(){
            lastX = sp.getHorizontalScrollBar().getValue();
            posFoglio.x = (this.getWidth()-larghFoglio*zoom)/2-lastX;
        public double getIncr(){
            return zoom/2;
        public void mouseClicked(MouseEvent e) {}
        public void mouseEntered(MouseEvent e) {}
        public void mouseExited(MouseEvent e) {}
        public void mousePressed(MouseEvent e) {}
        public void mouseReleased(MouseEvent e) {}
        public void mouseDragged(MouseEvent e) {}
        public void mouseMoved(MouseEvent e) {
            mouse = e.getPoint();
            mouse.x -= sp.getHorizontalScrollBar().getValue();
            mouse.y -= sp.getVerticalScrollBar().getValue();
            pl.repaint();
        public void componentHidden(ComponentEvent e) {}
        public void componentMoved(ComponentEvent e) {
            lastX = sp.getHorizontalScrollBar().getValue();
            posFoglio.x = (this.getWidth()-larghFoglio*zoom)/2-lastX;
            lastY = sp.getVerticalScrollBar().getValue();
            posFoglio.y = 50-lastY;
            pl.repaint();
        public void componentResized(ComponentEvent e) {
            this.repaint();
            pl.repaint();
        public void componentShown(ComponentEvent e) {}
    public class PanelLayer extends JPanel implements MouseWheelListener,MouseInputListener{
        private static final long serialVersionUID = 1L;
        private Layer layer;
        private JScrollPane sp = null;
        private boolean visualizzaMouse = false;
        public PanelLayer(){
            this.setLayout(null);
            layer = new Layer(this);
            layer.addMouseListener(this);
            layer.addMouseMotionListener(this);
        public void paintComponent(Graphics g){
            if(layer.getDimFoglio().getWidth()+layer.getDimFoglio().getHeight() == 0){
                layer.setSize(50,50);
            if(sp == null){
                sp = layer.getJScrollPane();
                sp.addMouseWheelListener(this);
                sp.setBounds(30,30,this.getWidth()-30,this.getHeight()-30);
                this.add(sp);
            }else{
                layer.refresh();
            sp.setBounds(30,30,this.getWidth()-30,this.getHeight()-30);
            Graphics2D g2d = (Graphics2D)g;
            g2d.setPaint(new Color(153,255,153));
            g2d.fill(new Rectangle2D.Double(0,0,this.getWidth(),30));
            g2d.fill(new Rectangle2D.Double(0,0,30,this.getHeight()));
            g2d.setPaint(Color.black);
            g2d.drawLine(0,0,this.getWidth(),0);
            g2d.drawLine(0,30,this.getWidth(),30);
            g2d.drawLine(0,0,0,this.getHeight());
            g2d.drawLine(30,0,30,this.getHeight());
            for(double i=0,j=0;i<=layer.getCmWidth();i+=layer.getIncr(),j++){
                if(j%2==0){
                    g2d.drawLine((int)(layer.getDimFoglio().x+31+i*50), 15,(int)(layer.getDimFoglio().x+31+i*50), 30);
                    g2d.drawString(String.valueOf((int)(j/2)), (float)(layer.getDimFoglio().x+31+i*50), 13);               
                }else{
                    g2d.drawLine((int)(layer.getDimFoglio().x+31+i*50), 22,(int)(layer.getDimFoglio().x+31+i*50), 30);
            for(double i=0,j=0;i<=layer.getCmHeight();i+=layer.getIncr(),j++){
                if(j%2==0){
                    g2d.drawLine(15, (int)(layer.getDimFoglio().y+31+i*50),30,(int)(layer.getDimFoglio().y+31+i*50));
                    g2d.drawString(String.valueOf((int)(j/2)),5,(float)(layer.getDimFoglio().y+31+i*50));
                }else{
                    g2d.drawLine(22, (int)(layer.getDimFoglio().y+31+i*50),30,(int)(layer.getDimFoglio().y+31+i*50));
            if((layer.getPointMouse() != null)&&(visualizzaMouse)){
                g2d.drawLine(layer.getPointMouse().x+30,0,layer.getPointMouse().x+30,30);
                g2d.drawLine(0,layer.getPointMouse().y+30,30,layer.getPointMouse().y+30);
            g2d.setPaint(new Color(153,255,153));
            g2d.fillRect(1,1,29,29);
            int largh = layer.getJScrollPane().getVerticalScrollBar().getWidth();
            g2d.fillRect(this.getWidth()-largh, 1, largh, 29);
            g2d.fillRect(1, this.getHeight()-largh, 29, largh);
        public void mouseWheelMoved(MouseWheelEvent e) {
            JScrollBar vsb = layer.getJScrollPane().getVerticalScrollBar();
            vsb.setValue(vsb.getValue()+20*e.getWheelRotation());
        public void refresh(){
            if((layer != null)&&(sp != null)){
                layer.setSize(this.getWidth()-30,this.getHeight()-30);
                sp.setViewportView(layer);
                this.repaint();
        public void mouseClicked(MouseEvent e) {}
        public void mouseEntered(MouseEvent e) {
            visualizzaMouse = true;
            repaint();
        public void mouseExited(MouseEvent e) {
            visualizzaMouse = false;
            repaint();
        public void mousePressed(MouseEvent e) {}
        public void mouseReleased(MouseEvent e) {}
        public void mouseDragged(MouseEvent e) {}
        public void mouseMoved(MouseEvent e) {}
    }(my english isn't very good)

    Don't really understand what the posted code does and I can't execute the code so I don't have much to offer.
    But I did notice that you don't invoke super.paintComponent(...) which means you may have garbage being painted on the panels.
    If you need further help then you need to create a "Short, Self Contained, Compilable and Executable, Example Program (SSCCE)", that demonstrates the incorrect behaviour.
    http://homepage1.nifty.com/algafield/sscce.html

  • Use extends and implements or not?

    What is considered a better way of implementing classes? with the use of extends and/or implements or not?
    ex:
    public class TabPanel extends JPanel implements ActionListeneror have it return the needed Type
    ex:
    public class TabPanel implements ActionListener
    public JPanel TabPanel()
    JPanel jp = new JPanel();
    jp.add(new JLabel("Test"));
    return jp;
    }

    To extend or not to extend, that is a question. Defenitely, you must subclass when you need to override some method. You want to subclass to reuse the customized class. You want to implement an interface when you need a class implementing it.
    Regarding your example:
    public class TabPanel implements ActionListener {
         public JPanel TabPanel() {
              JPanel jp = new JPanel();
              jp.add(new JLabel("Test"));
              return jp;
    }Are you sure it will work? IMO, you do not have to specify result type and must not return anything in the constructors. Why to bother with TabPanel class? If you like to hide the scope, use {} braces in the code.
    JPanel panel = new JPanel();
    jp.add(new JLabel("Test"));
    public class NonAnanymousListener implements ActionListener {

  • Implementing ActionListener & MouseListener

    Hello all!!
    I was just wondering, is it possible to implement both an ActionListener and a MouseListener into one class? ex:
    public class NAME extends JFrame implements ActionListener implements MouseListener
    //etc
    I have a program that relies heavily on MouseListener that I want to add a JMenu to, but I need ActionListener to do that... so, is it possible and I only have the wrong code? Or do I have to work around that somehow?
    Thank you so much for your help!
    Blessings,
    Sarah

    public class Name extends JFrame implements ActionListener, MouseListener

  • Extends JPanel

    Hi.
    I have a Class ATable that extends Panel. It is working good and draw the table.
    But, I need to convert this class to make it extends JPanel not Panel but it is not draw the table unless I change the frame size.
    So what is the problem please?
    this is my Class :
    =========================================================
    import java.awt.*;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import javax.swing.*;
    public class ATable extends JPanel
    implements TableDataModelListener, ColumnModelListener
    public static int OUTSIDE_TABLE = -1;
    TableCellRenderer tableCellRenderer;//interface for ---> Cell getTableCell(ATable atable, Object obj, int i, int j)
    TableDataModel tableDataModel; //interface
    ColumnModel columnModel; //class
    int cellOffsetY[];
    int rowHeight;
    int rowPadding;
    Point tableOffset;
    Point textOffset;
    Color gridLinesColor;
    Color tableBackground;
    ATableHeader tableHeader;
    static class _cls1 extends WindowAdapter
    public void windowClosing(WindowEvent e)
    System.exit(0);
    _cls1()
    public ATable()
    rowPadding = -1;
    tableCellRenderer = new DefaultTableCellRenderer();
    tableDataModel = new DefaultTableDataModel();
    columnModel = new ColumnModel();
    initColumnModel();
    setLayout(new BorderLayout());
    tableHeader = new ATableHeader(this, columnModel, new DefaultHeaderCellRenderer());
    add("North", tableHeader);
    initATable();
    public ATable(TableDataModel tableDataModel, ColumnModel columnModel, TableCellRenderer tableCellRenderer, TableCellRenderer headerCellRenderer)
    rowPadding = -1;
    this.tableCellRenderer = tableCellRenderer;
    this.tableDataModel = tableDataModel;
    this.columnModel = columnModel;
    setLayout(new BorderLayout());
    tableHeader = new ATableHeader(this, columnModel, headerCellRenderer);
    add("North", tableHeader);
    initATable();
    void initColumnModel()
    for(int i = 0; i < tableDataModel.getColumnsCount(); i++)
    TableColumn tableColumn = new TableColumn("Header " + i, i, 70);
    columnModel.addColumn(tableColumn);
    void calTextOffset()
    FontMetrics fm = getFontMetrics(getFont());
    textOffset.x = fm.charWidth('0');
    textOffset.y = fm.getAscent();
    void adjustColumnHeight()
    FontMetrics fm = getFontMetrics(getFont());
    rowHeight = fm.getAscent() + fm.getDescent() + 1;
    tableOffset.y = tableHeader.getPreferredSize().height + rowPadding;
    void initATable()
    gridLinesColor = new Color(50, 50, 50);
    tableBackground =new Color(155, 175, 202);
    textOffset = new Point();
    tableOffset = new Point();
    int fontSize = 12;
    Font font = new Font("Dialog", 0, fontSize);
    setFont(font);
    calTextOffset();
    adjustColumnHeight();
    calBeanDimensions();
    calCellsOffsetY();
    columnModel.addColumnModelListener(this);
    void calCellsOffsetY()
    if(cellOffsetY == null || cellOffsetY.length != tableDataModel.getRowsCount())
    cellOffsetY = new int[tableDataModel.getRowsCount()];
    int y = tableOffset.y;
    for(int i = 0; i < cellOffsetY.length; i++)
    cellOffsetY[i] = y;
    y += rowHeight + rowPadding;
    public void setFontAndAdjustDim(Font font)
    tableHeader.setFontAndAdjustDim(font);
    setFont(font);
    calTextOffset();
    adjustColumnHeight();
    calBeanDimensions();
    FontMetrics fm = getFontMetrics(getFont());
    int colWidth[] = new int[columnModel.getColumnsCount()];
    for(int i = 0; i < columnModel.getColumnsCount(); i++)
    TableColumn tableColumn = columnModel.getColumn(i);
    int dataModelIndex = tableColumn.getDataModelIndex();
    int max = fm.stringWidth(tableColumn.getHeaderValue());
    for(int j = 0; j < tableDataModel.getRowsCount(); j++)
    int current = fm.stringWidth(tableDataModel.getValueAt(j, dataModelIndex).toString());
    if(current > max)
    max = current;
    colWidth[i] = max + textOffset.x + textOffset.x;
    columnModel.setColumnsWidth(colWidth);
    calCellsOffsetY();
    doLayout();
    public void setFont(Font font)
    super.setFont(font);
    calTextOffset();
    void drawCell(Graphics g, int row, int col)
    TableColumn tableColumn = columnModel.getColumn(col);
    int x = tableColumn.getX();
    int width = tableColumn.getWidth();
    int y = cellOffsetY[row];
    int dataModelIndex = tableColumn.getDataModelIndex();
    Object value = tableDataModel.getValueAt(row, dataModelIndex);
    Cell cell = tableCellRenderer.getTableCell(this, value, row, col);
    drawCell(g, cell, x, y, width);
    void drawCell(Graphics g, Cell cell, int x, int y, int width)
    g.setClip(x, y, width, rowHeight);
    Color oldColor = g.getColor();
    g.setColor(gridLinesColor);
    g.drawRect(x, y, width - 1, rowHeight - 1);
    g.setColor(cell.getBGColor());
    g.fillRect(x + 1, y + 1, width - 2, rowHeight - 2);
    g.setColor(cell.getTextColor());
    g.setClip(x + 1, y + 1, width - 2, rowHeight - 2);
    g.drawString(cell.getValue(), x + textOffset.x, y + textOffset.y);
    if(cell.getHighlight() != null)
    g.setColor(cell.getHighlight());
    g.drawRect(x + 1, y + 1, width - 3, rowHeight - 3);
    g.setColor(oldColor);
    public int convertColumnIndexToModel(int columnIndex)
    TableColumn tableColumn = columnModel.getColumn(columnIndex);
    return tableColumn.getDataModelIndex();
    public int convertColumnIndexToView(int modelColumnIndex)
    int size = columnModel.getColumnsCount();
    for(int i = 0; i < size; i++)
    TableColumn tableColumn = columnModel.getColumn(i);
    if(tableColumn.getDataModelIndex() == modelColumnIndex)
    return i;
    return -1;
    public void hideColumn(int columnIndex)
    columnModel.removeColumn(columnIndex);
    public void addColumn(TableColumn tableColumn)
    columnModel.addColumn(tableColumn);
    public void moveColumn(int columnIndex, int newColumnIndex)
    columnModel.moveColumn(columnIndex, newColumnIndex);
    public int getColumnIndexFromPixel(int x)
    TableColumn tableColumn = columnModel.getColumn(columnModel.getColumnsCount() - 1);
    int edgeX = (tableColumn.getX() + tableColumn.getWidth()) - 1;
    if(x > edgeX || x < textOffset.x)
    return OUTSIDE_TABLE;
    for(int i = columnModel.getColumnsCount() - 1; i >= 0; i--)
    if(x > columnModel.getColumn(i).getX())
    return i;
    return OUTSIDE_TABLE;
    public int getRowFromPixel(int y)
    int edgeY = ((cellOffsetY.length == 0 ? 0 : cellOffsetY[cellOffsetY.length - 1]) + rowHeight) - 1;
    if(y > edgeY || y < tableOffset.y)
    return OUTSIDE_TABLE;
    for(int i = cellOffsetY.length - 1; i >= 0; i--)
    if(y > cellOffsetY)
    return i;
    return -1;
    public Dimension getPreferredSize()
    int width=0;
    int height=0;
    TableColumn tableColumn = columnModel.getColumn(columnModel.getColumnsCount() - 1);
    try
    height = cellOffsetY[cellOffsetY.length - 1] + rowHeight;
    width = tableColumn.getX() + tableColumn.getWidth();
    catch(Exception exp)
    height = 0;
    width = 0;
    return new Dimension(width, height);
    public Dimension getMinimumSize()
    TableColumn tableColumn = columnModel.getColumn(columnModel.getColumnsCount() - 1);
    int height = cellOffsetY[cellOffsetY.length - 1] + rowHeight;
    int width = tableColumn.getX() + tableColumn.getWidth();
    return new Dimension(width, height);
    public void updateAll()
    int rowsCount = tableDataModel.getRowsCount();
    update(0, tableDataModel.getRowsCount() - 1, 0, columnModel.getColumnsCount() - 1);
    public void update(int firstRowIndex, int lastRowIndex, int firstColIndex, int lastColIndex)
    if(firstRowIndex > lastRowIndex || firstColIndex > lastColIndex)
    return;
    try
    TableColumn firstColumn = columnModel.getColumn(firstColIndex);
    TableColumn lastColumn = columnModel.getColumn(lastColIndex);
    int width = (lastColumn.getX() + lastColumn.getWidth()) - firstColumn.getX();
    int height = (cellOffsetY[lastRowIndex] + rowHeight) - cellOffsetY[firstRowIndex];
    Image offScreen = createImage(width, height);
    Graphics og = offScreen.getGraphics();
    og.translate(-1 * firstColumn.getX(), -1 * cellOffsetY[firstRowIndex]);
    for(int i = firstRowIndex; i <= lastRowIndex; i++)
    for(int j = firstColIndex; j <= lastColIndex; j++)
    drawCell(og, i, j);
    getGraphics().drawImage(offScreen, firstColumn.getX(), cellOffsetY[firstRowIndex], null);
    catch(ArrayIndexOutOfBoundsException e)
    calCellsOffsetY();
    repaint();
    System.out.println(e);
    e.printStackTrace();
    public void paint(Graphics g)
    tableHeader.repaint();
    updateAll();
    public void setGridLinesColor(Color gridLinesColor)
    this.gridLinesColor = gridLinesColor;
    tableHeader.setGridLinesColor(gridLinesColor);
    repaint();
    public void setTableBackground(Color tableBackground)
    this.tableBackground = tableBackground;
    repaint();
    public void tableDataModelChanged(TableDataModelEvent e)
    if(e.getType() == TableDataModelEvent.UPDATE)
    update(e.getFirstRow(), e.getLastRow(), 0, columnModel.getColumnsCount() - 1);
    else
    if(e.getType() == TableDataModelEvent.INSERT)
    calCellsOffsetY();
    update(e.getFirstRow(), e.getLastRow(), 0, columnModel.getColumnsCount() - 1);
    } else
    calCellsOffsetY();
    repaint();
    void calBeanDimensions()
    public void cellDataChanged(int row, int col)
    col = convertColumnIndexToView(col);
    if(col < 0)
    return;
    } else
    TableColumn column = columnModel.getColumn(col);
    int width = column.getWidth();
    int height = rowHeight;
    Image offScreen = createImage(width, height);
    Graphics og = offScreen.getGraphics();
    og.translate(-1 * column.getX(), -1 * cellOffsetY[row]);
    drawCell(og, row, col);
    getGraphics().drawImage(offScreen, column.getX(), cellOffsetY[row], null);
    return;
    public void columnAdded(ColumnModelEvent e)
    calBeanDimensions();
    repaint();
    public void columnMoved(ColumnModelEvent e)
    repaint();
    public void columnRemoved(ColumnModelEvent e)
    calBeanDimensions();
    repaint();
    public void columnWidthChanged(ColumnModelEvent e)
    calBeanDimensions();
    repaint();
    public ATableHeader getHeader()
    return tableHeader;
    public ColumnModel getColumnModel()
    return columnModel;
    public static void main(String args[])
    throws Exception
    ATable aTable = new ATable();
    Frame f = new Frame();
    f.addWindowListener(new _cls1());
    f.add(aTable);
    Dimension dim = aTable.getPreferredSize();
    f.setVisible(true);
    f.pack();

    thank you for reply.
    I removed the setFont function and the class works good and showing the table.
    But when I put this table in JFrame not in Frame the table disappeared. I mean if I changed the Main class to the following :
    ================================================
    public static void main(String args[])
    throws Exception
    ATable aTable = new ATable();
    JFrame f = new JFrame();
    f.addWindowListener(new _cls1());
    f.getContentPane.add(aTable);
    Dimension dim = aTable.getPreferredSize();
    f.setVisible(true);
    f.pack();

  • Extending JPanel

    i made a class that extends JPanel and i overrided the paintComponent method so i could create my own graphics. I tried adding my component to a JScrollPane but it didn't work. How could i create a ScrollPane for my component.

    did you override getPreferredSize() on the panel subclass to return a size? or call setPreferredSize() early on (in the constructor or somewhere) on the panel subclass?
    the best way to deal with scrolling panels, however, is to use something like this handy class as the base class... It handles drag-scrolling and lets you set the scroll unit size to whatever. When you want to change the size, call setPreferredSize() and it'll notify the scrollpane of the change. (Generally, you want to leave the ScrollableTracksViewportWidth/Height as false, BTW.)
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    * <code>ScrollablePanel</code> is a <code>JPanel</code> subclass which
    * supports scrolling via the <code>Scrollable</code> interface. 
    public class ScrollablePanel extends JPanel implements Scrollable, MouseMotionListener {
          * The scroll unit size. 
         private int unitSize = 5;
          * Flag to indicate if a viewport should always force the width of this
          * <code>Scrollable</code> to match the width of the viewport.
         private boolean scrollableTracksViewportWidth = false;
          * Flag to indicate if a viewport should always force the height of this
          * <code>Scrollable</code> to match the height of the viewport.
         private boolean scrollableTracksViewportHeight = false;
          * Creates a new <code>ScrollablePanel</code>. 
         public ScrollablePanel() {
              super();
              setAutoscrolls(true); // enable synthetic drag events
              addMouseMotionListener(this); // handle mouse drags
          * Handles mouse moved events.  Does nothing. 
          * @param  e  the mouse event
         public void mouseMoved(MouseEvent e) {
          * Handles mouse dragged events.  Tracks dragging for autoscrolling. 
          * @param  e  the mouse event
         public void mouseDragged(MouseEvent e) {
              scrollRectToVisible(new Rectangle(e.getX(), e.getY(), 1, 1));
          * Sets the preferred size of the panel.  This also calls
          * <code>revalidate()</code> to notify the viewport parent
          * of the change. 
          * @param  size  the preferred size of the panel
         public void setPreferredSize(Dimension size) {
              super.setPreferredSize(size);
              revalidate();
              repaint();
          * Returns the preferred size of the viewport for a view component. 
          * @return  the preferred size of the viewport
         public Dimension getPreferredScrollableViewportSize() {
              return getPreferredSize();
          * Components that display logical rows or columns should compute the
          * scroll increment that will completely expose one new row or column,
          * depending on the value of orientation.
          * @param  visibleRect  the visible area
          * @param  orientation  the orientation
          * @param  direction    the scroll direction
          * @return  the unit increment
         public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction) {
              int currentPosition = 0;
              if(orientation == SwingConstants.HORIZONTAL) {
                   currentPosition = visibleRect.x;
              } else {
                   currentPosition = visibleRect.y;
              // return the number of pixels between currentPosition and the
              // nearest unit size increment in the indicated direction.
              if(direction < 0) {
                   int newPosition = currentPosition - (currentPosition / unitSize) * unitSize;
                   return (newPosition == 0) ? unitSize : newPosition;
              } else {
                   return ((currentPosition / unitSize) + 1) * unitSize - currentPosition;
          * Components that display logical rows or columns should compute the
          * scroll increment that will completely expose one block of rows or
          * columns, depending on the value of orientation.
          * @param  visibleRect  the visible area
          * @param  orientation  the orientation
          * @param  direction    the scroll direction
          * @return  the block increment
         public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction) {
              if(orientation == SwingConstants.HORIZONTAL) {
                   return visibleRect.width - unitSize;
              } else {
                   return visibleRect.height - unitSize;
          * Return true if a viewport should always force the width of this
          * <code>Scrollable</code> to match the width of the viewport.
          * @return  the tracks viewport width mode
         public boolean getScrollableTracksViewportWidth() {
              return this.scrollableTracksViewportWidth;
          * Sets if a viewport should always force the width of this
          * <code>Scrollable</code> to match the width of the viewport.
          * @param  b  true if the tracks viewport width mode
         public void setScrollableTracksViewportWidth(boolean b) {
              this.scrollableTracksViewportWidth = b;
          * Return true if a viewport should always force the height of this
          * <code>Scrollable</code> to match the height of the viewport.
          * @return  the tracks viewport height mode
         public boolean getScrollableTracksViewportHeight() {
              return this.scrollableTracksViewportHeight;
          * Sets if a viewport should always force the height of this
          * <code>Scrollable</code> to match the height of the viewport.
          * @param  b  true if the tracks viewport height mode
         public void setScrollableTracksViewportHeight(boolean b) {
              this.scrollableTracksViewportHeight = b;
          * Gets the scroll unit size. 
          * @return  the scroll unit size
         public int getUnitSize() {
              return this.unitSize;
          * Sets the scroll unit size. 
          * @param  us  the scroll unit size
         public void setUnitSize(int us) {
              unitSize = us;
    }

  • Extending JPanel to contain a JRootPane - problems with scroll panes

    I am trying to write a JPanel subclass that contains a JRootPane, similar to the way that JFrame contains a JRootPane. The reason that I am doing this is that I would like to be able to intercept mouse events using the JGlassPane facility, but adding the glasspane to the JFrame is problematic since it then intercepts mouse events over all components in the JFrame, including the menu bar. It seems simpler to me to have the JRootPane owned by a JPanel, to give me better control over intercepting events. I've got an implementation working with the JFrame case, but have had to handle many small "gotchas", and at least one more exists. I'm hoping to simplify things by moving away from this way of doing things.
    I wrote a straightforward RootPanePanel class that extends JPanel and implements RootPaneContainer, delegating all of the add methods to the JRootPane's content pane. Here's the constructor for RootPanePanel:
    public RootPanePanel (LayoutManager layout) {
            rootPane = new JRootPane ();
            rootPane.setOpaque(true);
            rootPane.getContentPane().setLayout(layout);
            super.add (rootPane);
    }RootPanePanel also delegates calls like getContentPane/setContentPane to the JRootPane.
    To test my implementation, I wrote a main method that looks like the following:
    public static void main (String[] args) {
      SwingUtilities.invokeLater(new Runnable () {
        public void run () {
          try {
            JEditorPane editorPane = new JEditorPane ("http://www.archives.gov/exhibits/charters/print_friendly.html?page=declaration_transcript_content.html&title=NARA%20%7C%20The%20Declaration%20of%20Independence%3A%20A%20Transcription");
            JScrollPane scrollPane = new JScrollPane (editorPane);
            JFrame frame = new JFrame ("Test RootPanePanel");
            RootPanePanel panel = new RootPanePanel ();                    
            panel.add(scrollPane);
            frame.add(panel, BorderLayout.CENTER);
            scrollPane.setPreferredSize(new Dimension(800, 600));
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize (640, 480);
            frame.pack ();
            frame.setVisible(true);
          } catch (Exception e) {
            e.printStackTrace();
      });Note that I'm not actually using JEditorPane in my application, but it is the simplest component that displays the problem I'm encountering.
    When this code runs, it is fine, as long as the JFrame is big enough to display the scrollbars for the JScrollPane. If the JFrame is made small enough, the scrollbars are not displayed.
    If I instead add the JScrollPane to the JFrame directly, it behaves as you would expect.
    Is this a problem of mixing heavyweight and lightweight components? It doesn't seem like it should be; in both cases the JScrollPane is handling the same client component, the JEditorPane.
    Any suggestions/ideas are welcome!

    Here's the full RootPanePanel class in case people want to try it out
    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.awt.Container;
    import java.awt.Dimension;
    import java.awt.HeadlessException;
    import java.awt.LayoutManager;
    import java.io.IOException;
    import javax.swing.JEditorPane;
    import javax.swing.JFrame;
    import javax.swing.JLayeredPane;
    import javax.swing.JPanel;
    import javax.swing.JRootPane;
    import javax.swing.JScrollPane;
    import javax.swing.RootPaneContainer;
    import javax.swing.SwingUtilities;
    public class RootPanePanel extends JPanel implements RootPaneContainer {
         private JRootPane rootPane;
         public RootPanePanel () {
              this (new BorderLayout());
         public RootPanePanel (LayoutManager layout) {
              rootPane = new JRootPane ();
              rootPane.setOpaque(true);
              rootPane.getContentPane().setLayout(layout);
              super.add (rootPane);
         public Container getContentPane() {
              return rootPane.getContentPane();
         public Component getGlassPane() {
              return rootPane.getGlassPane();
         public JLayeredPane getLayeredPane() {
              return rootPane.getLayeredPane();
         public void setContentPane(Container arg0) {
              rootPane.setContentPane(arg0);
         public void setGlassPane(Component arg0) {
              rootPane.setGlassPane(arg0);
         public void setLayeredPane(JLayeredPane arg0) {
              rootPane.setLayeredPane(arg0);
         @Override
         protected void addImpl(Component comp, Object constraints, int index)
              if (comp == rootPane) {
                   super.addImpl(comp, constraints, index);
              else {
                   getContentPane().add(comp, constraints, index);
         @Override
         public Component add(Component comp, int index) {
              return rootPane.getContentPane().add(comp, index);
         @Override
         public void add(Component comp, Object constraints, int index) {
              rootPane.getContentPane().add(comp, constraints, index);
         @Override
         public void add(Component comp, Object constraints) {
              rootPane.getContentPane().add(comp, constraints);
         @Override
         public Component add(Component comp) {
              return rootPane.getContentPane().add(comp);
         @Override
         public Component add(String name, Component comp) {
              return rootPane.getContentPane().add(name, comp);
         public static void main (String[] args) {
              SwingUtilities.invokeLater(new Runnable () {
                   public void run () {
                        try {
                             JEditorPane editorPane = new JEditorPane ("http://www.archives.gov/exhibits/charters/print_friendly.html?page=declaration_transcript_content.html&title=NARA%20%7C%20The%20Declaration%20of%20Independence%3A%20A%20Transcription");
                             JScrollPane scrollPane = new JScrollPane (editorPane);
                             JFrame frame = new JFrame ("Test RootPanePanel");
                             RootPanePanel panel = new RootPanePanel ();                    
                             panel.add(scrollPane);
                             frame.add(panel, BorderLayout.CENTER);
                             scrollPane.setPreferredSize(new Dimension(800, 600));                                                                                                                                                 
                             frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                             frame.setSize (640, 480);
                             frame.pack ();
                             frame.setVisible(true);                                                                                                    
                        } catch (HeadlessException e) {
                             // TODO Auto-generated catch block
                             e.printStackTrace();
                        } catch (IOException e) {
                             // TODO Auto-generated catch block
                             e.printStackTrace();
         public JRootPane getRootPane() {
              return rootPane;
    }

  • Extends JFrame or extends JPanel ?

    Hi!
    I'd like to do a full screen animation but I don't know which Swing component to subclass to be able to paint the animation. Which is better:
    extends JFrame implements Runnable
    or
    extends JPanel implements Runnable
    Regards

    Do you mean full-screen exclusive mode: http://java.sun.com/docs/books/tutorial/extra/fullscreen/index.html
    In that case, you usually subclass java.awt.Window if you are doing active rendering, since Swing features
    like double buffering just get in the way.

  • Problem extending JPanel

    Hi,
    What is the best format to have a class with a JFrame and a number of JPanels, one of which needs to be painted on using Graphics.
    class Demo extends JPanel{
    public JFrame frame;
    public JPanel panel1;
    public JPanel panel2;
    public JPanel panel3;
       Demo(){
          // initialise JFrame
          frame = new JFrame();
          // initialise a few JPanels
          panel1 = new JPanel();
          panel2 = new JPanel();
          panel3 = new JPanel();
          // refer to the JPanel I'm painting on
          frame.getContentPane(this);   // Is this correct?
         public void paint(Graphics g)     {
              g.drawString("Click below", 50, 50);               
                  // now this method should paint over one of the JPanels only, the one I'm extending..
    }Any thought appreciated.

    Thanks for the pointers Haynese ,
    I understand what I should be doing.
    I have another issue with this now, maybe its constructed badly...
    I can get the graphics objects on the JPanel to display but not the JButton or label I add. If I click in the region of the button and hit it, it appears. Any ideas?
    public class GraphEditor extends JPanel implements MouseListener
    public JButton button;
    public JLabel label5;
         public GraphEditor(){
              //  JPanel Button, displays if clicked on.
              button = new JButton("JPanel Button, displays if clicked on...");
              this.add(button);
                                             //  This should display but never does
              label5 = new JLabel("This should display but never does");
              add(label5);
              setSize(50,50);
              setVisible(true);
         public void paint(Graphics g)     {
                                            // This displays fine
              g.drawString("This displays fine", 5, 5);               
    }and:
    public class SystemWindow extends JFrame {     
    public JButton button;
    public JPanel topPanel;
    public JPanel bottomPanel;
    public JPanel mainPanel;
    public JLabel topPanelLabel;
    public JLabel bottomPanelLabel;
    public JButton getPathButton;
    private GraphEditor mainMap = new GraphEditor(this);
         SystemWindow(){     
             topPanel = new JPanel();
              bottomPanel = new JPanel();
              mainPanel = new JPanel();
              // 10 is horizontal
                                               // 01 is vertical
              getContentPane().setLayout(new GridLayout(0,1));
              getContentPane().add(mainPanel);
              mainPanel.add(topPanel);
              mainPanel.add(bottomPanel);
              topPanelLabel = new JLabel("Top Panel");
              topPanel.add(topPanelLabel);
              bottomPanelLabel = new JLabel("Bottom Panel");
              bottomPanel.add(bottomPanelLabel);
              button = new JButton("Save");
              //button.addActionListener(this);
              bottomPanel.add(button);
              getPathButton = new JButton("Get");
              //getPathButton.addActionListener(this);
              bottomPanel.add(getPathButton);
              getContentPane().add(mainMap);
              setTitle("App Title");          
              setSize(500,300);          
              setLocation(100,100);     
              mainPanel.setVisible(true);
              topPanel.setVisible(true);
             bottomPanel.setVisible(true);
             setVisible(true);
         }          Any suggestions welcome.

  • Can any one change this Applet into a class that extends Jpanel.....

    Hi,
    I need this applet as a class that extends JPanel, I will be very very thankful to you if any one kindly change this Applet code into a class that extends JApplet.
    I will be very thankful to you if some one can reserve few minutes & do this favor early.
    Thanks a lot for any help.
         My Pong Code
    import java.applet.*;
    import java.awt.*;
    import java.io.*;
    import java.awt.event.*;
    public class Class1 extends Applet implements Runnable
    {     private final int APPLET_WIDTH = 900;
         private final int APPLET_HEIGHT = 600;
         private int px = 15;
         private final int py = 560;
         private final int ph = 10;
         private final int pw = 75;
         private int old_px = px;
         private int bx = 450;
         private int by = 15;
         private final int bh = 20;
         private final int bw = 20;
         private int move_x = 2;
         private int move_y = 2;
         private boolean done = false;
         Thread t;
         private final int delay = 25;
         public void init()
         {     setBackground(Color.black);
              setSize(APPLET_WIDTH, APPLET_HEIGHT);
              requestFocus();
              addKeyListener(new DirectionKeyListener());
             (t = new Thread(this)).start();
         public void run()      {
        try      {     while((t == Thread.currentThread()) && (done == false))           {     
                   if ((bx < 15) || (bx > APPLET_WIDTH-30))                     move_x = -move_x;                                if ((by < 15) ||                    ((by > APPLET_HEIGHT-60)&&                     ((px<=bx)&&(bx<=px+pw))))
                        move_y = -move_y;
                   if (by > APPLET_HEIGHT)
                        done = true;
                                   bx = bx + move_x;
                   by = by + move_y;                                                repaint();
                   t.sleep(delay);
         catch(Exception e)      {}
         }//end run
         /*public void move_paddle(int amount)
              old_px = px;
              //if (amount > 0)
                //if (px <= APPLET_WIDTH-15)
                   px = px + amount;
              //else if (amount < 0)
               // if (px >= 15)
                   px = px + amount;
         public void paint(Graphics page)
              //     page.setColor(Color.black);
              //     page.drawRect(old_px, py, pw, ph);
                   page.setColor(Color.blue);
                   page.drawRect(px, py, pw, ph);
                   page.setColor(Color.white);
                   page.drawOval(bx, by, bw, bh);
                   if ((done == true) && (by > APPLET_HEIGHT))
                        page.drawString("LOSER!!!", APPLET_WIDTH/2, APPLET_HEIGHT/2);
                   else if (done == true)
                        page.drawString("Game Over, Man!", APPLET_WIDTH/2-10, APPLET_HEIGHT/2);
         private class DirectionKeyListener implements KeyListener               
              public void keyPressed (KeyEvent event)
                   switch (event.getKeyCode())
                   case KeyEvent.VK_LEFT:
                        old_px = px;
                        if (px >=15)
                             px -=10;
                        break;
                   case KeyEvent.VK_RIGHT:
                        old_px = px;
                        if (px+pw <= APPLET_WIDTH-15)
                             px += 10;
                        break;
                   case KeyEvent.VK_Q:
                        done = true;
                   default:
                   }  //end switch
                   repaint();
              }//end keyPressed
              public void keyTyped (KeyEvent event)
              public void keyReleased (KeyEvent event)
         }  //end class 
    }

    thank you sir for your advice.
    Its not like that I without any attempt, just past code here & asked for its conversion. I spent about 5 hours on it, can say spoil whole day but to no avail. You then just guide me, give some hint so that I do it. I will most probably wanted to do it by myself but asked for help when was just disappointed.
    I try to put all init() in default constructor of identical copy of this applet that extends JPanel. Problem.....ball tend to fell but pad not moving. Also out out was not getting ant color input. That was like my best effort.....other tried that I found by search like just do nothing only extend panel OR frame in spite of applet, start applet from within main of another class.... these are few I remember what I tried.
    I will be very very thankful to you if you can help/guide me how can I do it. Behavior of the Applet is like a normal PONG game with on pad controlled by arrow keys, & one ball colliding with walls of boundary & falling down.
    Thanks a lot again for your attention & time.

  • When loading my photoshop cs4 extended in informs me The installer database is corrupt please contact adobe customer services. Is that possible?

    When loading my photoshop cs4 extended in informs me The installer database is corrupt please contact adobe customer services. Is that possible?

    Run the cleaner tool and reinstall from scratch, making sure you have proper file permissions and user privileges and turning off potential disturbances liek virus scanners etc..
    Mylenium

  • Xml Serializing a class that extends JPanel

    Alright I am getting an Exception saying java.
    java.lang.reflect.InvocationTargetException
    Continuing ...
    java.lang.Exception: XMLEncoder: discarding statement XMLEncoder.writeObject(JpanelScreen);
    Continuing ...
    is anyone familiar with this... It ocurrs when I try to Serialize my class object that extends JPanel...

    any examples of how to do this?
    try {
    java.beans.XMLEncoder out = new java.beans.XMLEncoder( new BufferedOutputStream( new java.io.FileOutputStream(getFilename())));
    out.writeObject(Screen);
    out.close();
    }catch (Exception exc) {System.err.println(exc.getMessage());}

  • What is wrong wiith:  JFrame that also implements ActionListener

    I got this as a reaction for a question
    Having a JFrame that also implements ActionListener
    is already a code smell, IMOCan someone explain me this.

    If you've got one ActionListener for the frame
    it's fine.This how I make the buttons for each button I make a new KnopHandler
    So this is not good
    This is the way I read in my book a couple of years ago at school.
            importdatafile.setBounds(520,230,195,25);
         importdatafile.addActionListener( new importdatafileKnopHandler() );
         importdata.setBounds(520,260,195,25);
         importdata.addActionListener( new importdataKnopHandler() );
            copy.setBounds(520,310,195,25);
         copy.addActionListener( new copyKnopHandler() );
            insertrow.setBounds(520,340,195,25);
         insertrow.addActionListener( new insertrowKnopHandler() );
             delete.setBounds(520,370,195,25);
         delete.addActionListener( new deleteKnopHandler() );
            senddata.setBounds(520,420,195,25);
         senddata.addActionListener( new senddataKnopHandler() );
         senddatafile.setBounds(520,450,195,25);
         senddatafile.addActionListener( new senddatafileKnopHandler() );
    class printtKnopHandler implements ActionListener
         public void actionPerformed(ActionEvent e)
         printt = true;
         GUI();
    class insertrowKnopHandler implements ActionListener
         public void actionPerformed(ActionEvent e)
         insertroww = true;
         GUI();
    class senddataKnopHandler implements ActionListener
         public void actionPerformed(ActionEvent e)
         sendverbdata = true;
         GUI();
    class senddatafileKnopHandler implements ActionListener
         public void actionPerformed(ActionEvent e)
         sendverbfile = true;
         GUI();
         }

  • Record while holding down a JButton - is that possible?

    I'm gonna make a program that records while the user is pressing and holding down the Record button. Is that possible? How can I do it?
    I have started with this code where I am using a mouseListener for the button and not an actionListener, that´s because I think a mouseListener is better if I want to implement a function that makes it possible to hold down the button while recording. Am I right? How can I write such a method?
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.io.*;
    import java.net.*;
    import javax.sound.sampled.*;
    class Recorder extends JFrame
         private JButton recordButt = new JButton("Record");
         private Socket sock = new Socket();
         private AudioFormat audioFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, 44100.0F, 16, 2, 4, 44100.0F, false);
         private AudioFileFormat fileFormat = new AudioFileFormat(AudioFileFormat.Type.WAVE, audioFormat, 16);
         private AudioInputStream ais;
         private TargetDataLine tdl;
         private File file = new File("sound.wav");
         Recorder()
              super("Recorder");
              setLayout(new BorderLayout());
              JPanel north = new JPanel();
              add(north, BorderLayout.NORTH);
              north.add(recordButt);
              recordButt.addMouseListener(new RecordButt());
              setDefaultCloseOperation(EXIT_ON_CLOSE);
              pack();
              setVisible(true);
         class RecordButt extends MouseAdapter
              Record r = new Record();
              public void mousePressed(MouseEvent e)
                   r.start();
              public void mouseReleased(MouseEvent ee)
                   r.interrupt();
         class Record extends Thread
              public void start()
                   DataLine.Info info = new DataLine.Info(TargetDataLine.class, audioFormat);
                   try
                        tdl = (TargetDataLine)AudioSystem.getLine(info);
                        tdl.open(audioFormat);
                   catch(LineUnavailableException err) { System.out.println(err.getMessage()); }
                   ais = new AudioInputStream(tdl);
                   try
                         AudioSystem.write(ais, AudioFileFormat.Type.AU, file);
                   catch(IOException e) {}
                   tdl.stop();
                   tdl.close();
         public static void main(String[] args)
              new Recorder();
    }

    Thanks!
    I have modified the above code and I have marked the changes with the comment "marked" and now it looks like:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.io.*;
    import java.net.*;
    import javax.sound.sampled.*;
    class Recorder extends JFrame
         private JButton recordButt = new JButton("Record");
         private Socket sock = new Socket();
         private AudioFormat audioFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, 44100.0F, 16, 2, 4, 44100.0F, false);
         private AudioFileFormat fileFormat = new AudioFileFormat(AudioFileFormat.Type.WAVE, audioFormat, 16);
         private AudioInputStream ais;
         private TargetDataLine tdl;
         private File file = new File("sound.wav");
            boolean record = false;  // changed
         Recorder()
              super("Recorder");
              setLayout(new BorderLayout());
              JPanel north = new JPanel();
              add(north, BorderLayout.NORTH);
              north.add(recordButt);
              recordButt.addMouseListener(new RecordButt());
              setDefaultCloseOperation(EXIT_ON_CLOSE);
              pack();
              setVisible(true);
         class RecordButt extends MouseAdapter
              Record r = new Record();
              public void mousePressed(MouseEvent e)
                          record = true;   // changed
                   r.start();
              public void mouseReleased(MouseEvent ee)
                   record = false;   // changed
         class Record extends Thread
              public void start()
                   DataLine.Info info = new DataLine.Info(TargetDataLine.class, audioFormat);
                   try
                        tdl = (TargetDataLine)AudioSystem.getLine(info);
                        tdl.open(audioFormat);
                   catch(LineUnavailableException err) { System.out.println(err.getMessage()); }
                   ais = new AudioInputStream(tdl);
                   try
                                  while(record)   // changed
                               AudioSystem.write(ais, AudioFileFormat.Type.AU, file);
                   catch(IOException e) {}
                   tdl.stop();
                   tdl.close();
         public static void main(String[] args)
              new Recorder();
    }But the Record button seems to hang while beeing pressed. Why?

Maybe you are looking for

  • I have trying to have my contacts and calendar info transferred to my new 4s from my 3g

    Please help.  I have been trying to transfer my contacts and calendar info from my old phone 3GS which I had already updated to iCloud-to my new iPhone 4s.   I have one apple I'd for I tunes and now 2 apple is for me.com.  Thanks

  • Can't Paste

    I can't paste anything into dreamweaver. when I restarted I got an error that said the following: The following Jave Script error(s) occurred: At line 56 of file "C:\Program Files\Macromedia\Dreamweaver8\Configuration\shared\common\Scripts\dwscriptsE

  • Script Alert SyntaxError: Expected: }:1

    While trying to run the Adobe Watermark Palette, I receive the syntax error as stated in the subject of this posting. I removed the Watermark Palette using Adobe Extension Manager and reinstalled it. I receive the same error. I've  double and triple

  • Opening different file types

    Forms [32 Bit] Version 10.1.2.3.0 (Production) Hi How can you open different file types saved in the database as BLOBs using Webutil? I am capturing the filename and extension as well. The file types are: Excel Spreadsheets, MS Word, PDF, Mail Attach

  • Mini ipod menu and play buttons are not working

    My ipod menu button has not worked now for a few months. I can't get back to my main playlist and choose certain things, I just have to listen to the all the songs. Now the play button is not working either, its working to turn on-play-pause, but not