Panels in AWT

Can't we use Panels in awt...
AWTTest(){
          BorderLayout bord=new BorderLayout();
          setLayout(bord);
          setBounds(40,40,600,400);
          Panel p=new Panel();
          p.setLayout(null);
                    Button btn1=new Button("OK");
                    btn1.setBounds(10,10,60,20);
                    p.add(btn1);
          Panel p1=new Panel();
          p1.setLayout(null);
                    Button btn2=new Button("OK");
                    btn2.setBounds(10,10,60,20);
                    p1.add(btn2);
          add("Center",p);
          add("South",p1);
setVisible(true);
Since it only apperas "Center"
Where is the South

you're using an obsolete version of add() when you add the Panels to the outer container, and the constants "Center" and "South" may be obsolete or meaningless to BorderLayout as well. Use BorderLayout.CENTER and BorderLayout.SOUTH.
Also, when you post code, wrap it in [code][/code] tags.

Similar Messages

  • Switching panels in AWT

    Hi, having a problem with switching 2 panels within a frame. Am using the following code within the frame file:
    removeAll();
    recPlay = new RecPlayPanel(tvacs);
    recPlay.start();
    add(recPlay);
    this.repaint();
    When this code is exectuted the first panel is removed but the second is not displayed, yet if you resize the frame it suddenly appears. Does anybody know why this happens. NOTE: this must be done using AWT components only as is to run on JEODE runtime. Thanks in advance, Alan

    You should probably call validate() since that'll set the size of the panel according to your layout policy.
    Hope this helps.

  • Tabs and Panels

    Hey again. I have a JTabbedPane, with buttons, and another, larger Panel to the right of it. I need to be able to change the main Panel when a button is clicked. Unfortunatly, when I add content to it, the change doesn't show up until I change tabs on my TabbedPane. Changing the background colour works instantly though. Any ideas?
    Thanks!

    Swing related questions should be posted in the Swing forum.
    The method revalidate() is undefined for the type Panel revalidate() is for Swing components.
    You shouldn't be mixing AWT components with Swing components. Panel is AWT. You should be using JPanel which is a Swing component.
    You could also consider using a CardLayout, which was designed for this purpose:
    http://java.sun.com/docs/books/tutorial/uiswing/layout/visual.html

  • Can not get data from mySql

    I prepared a GUI user connection application in NebBeans 5.5 accessing mySql database in the company server. The application run very well in desktop.
    However, when I post it to the company server web, it gets nothing from the database.
    Can any one give advice???
    Thank you in advance.
    The following is my application
    import java.util.Vector;
    import java.awt.event.*;
    import java.awt.*;
    import java.awt.event.*;
    public class UserConnection extends javax.swing.JFrame {
    //constants for database
    private final String userName = "labmanage";
    private final String password = "labmanage";
    private final String server = "jdbc:mysql://svr.corp.com/labmanage";
    private final String driver = "com.mysql.jdbc.Driver";
    private JDBCAdapter data = new JDBCAdapter(server, driver, userName, password);
    //variables
    private String user, pwd;
    private Vector<Vector<String>> userTable = new Vector<Vector<String>>();
    private Vector<String>colUserNames = new Vector<String>();
    * Creates new form UserConnection
    public UserConnection() {
    initComponents();
    /** This method is called from within the constructor to
    * initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is
    * always regenerated by the Form Editor.
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">
    private void initComponents() {
    userLabel = new javax.swing.JLabel();
    pwdLabel = new javax.swing.JLabel();
    userTextField = new javax.swing.JTextField();
    passwordField = new javax.swing.JPasswordField();
    submitButton = new javax.swing.JButton();
    statusLabel = new javax.swing.JLabel();
    jScrollPane1 = new javax.swing.JScrollPane();
    statusTextArea = new javax.swing.JTextArea();
    changePwdButton = new javax.swing.JButton();
    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    setTitle("User's Connection");
    setBackground(new java.awt.Color(153, 204, 255));
    setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
    setFont(new java.awt.Font("aakar", 1, 12));
    userLabel.setText("User Name:");
    pwdLabel.setText("Password:");
    submitButton.setText("Submit");
    submitButton.addMouseListener(new java.awt.event.MouseAdapter() {
    public void mouseClicked(java.awt.event.MouseEvent evt) {
    submitButtonMouseClicked(evt);
    submitButton.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    submitButtonActionPerformed(evt);
    submitButton.addKeyListener(new java.awt.event.KeyAdapter() {
    public void keyTyped(java.awt.event.KeyEvent evt) {
    submitButtonKeyTyped(evt);
    statusLabel.setText("Status:");
    statusTextArea.setColumns(20);
    statusTextArea.setEditable(false);
    statusTextArea.setLineWrap(true);
    statusTextArea.setRows(3);
    statusTextArea.setText("Initial assigned password is \"dime\".");
    statusTextArea.setWrapStyleWord(true);
    jScrollPane1.setViewportView(statusTextArea);
    changePwdButton.setText("Change password");
    changePwdButton.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    changePwdButtonActionPerformed(evt);
    org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
    layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    .add(layout.createSequentialGroup()
    .addContainerGap()
    .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    .add(userLabel)
    .add(pwdLabel)
    .add(statusLabel))
    .add(35, 35, 35)
    .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    .add(layout.createSequentialGroup()
    .add(submitButton)
    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
    .add(changePwdButton))
    .add(passwordField, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 230, Short.MAX_VALUE)
    .add(userTextField, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 230, Short.MAX_VALUE)
    .add(org.jdesktop.layout.GroupLayout.TRAILING, jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 230, Short.MAX_VALUE))
    .addContainerGap())
    layout.setVerticalGroup(
    layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    .add(layout.createSequentialGroup()
    .addContainerGap()
    .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
    .add(userLabel)
    .add(userTextField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
    .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
    .add(pwdLabel)
    .add(passwordField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
    .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    .add(statusLabel)
    .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
    .add(15, 15, 15)
    .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
    .add(submitButton)
    .add(changePwdButton))
    .addContainerGap(27, Short.MAX_VALUE))
    pack();
    }// </editor-fold>
    private void submitButtonKeyTyped(java.awt.event.KeyEvent evt) {                                     
    if(evt.getKeyCode() == KeyEvent.VK_ENTER) {
    submitButton.doClick();
    submitButton.requestFocus();
    changePwdButton.requestFocus();
    private void changePwdButtonActionPerformed(java.awt.event.ActionEvent evt) {                                               
    String command = evt.getActionCommand();
    if(command.equals("Change password")) {
    passwordField.setText("");
    //Get connection to the changing password panel
    java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
    new ChangePassword().setVisible(true);
    private void submitButtonActionPerformed(java.awt.event.ActionEvent evt) {                                            
    // TODO add your handling code here:
    String command = evt.getActionCommand();
    if(command.equals("Submit")) {
    user = getUser();
    pwd = getPwd();
    data = new JDBCAdapter(server, driver, userName, password);
    data.executeQuery("SELECT * FROM USERTABLE");
    colUserNames = data.getColumnNames();
    userTable = data.getDataTable();
    if(colUserNames.elementAt(0).equals("")) {
    statusTextArea.setText("Can not connect to database");
    boolean checkUser = false;
    int i = 0;
    while(!checkUser && i<userTable.size()) {
    if(user.equalsIgnoreCase((String) userTable.elementAt(i).elementAt(0))) {
    //Find the user in database
    checkUser = true;
    //Check user's password
    if(pwd.equals((String)userTable.elementAt(i).elementAt(1))) {
    //Check for initial default password. The user is requested
    //to change his password
    if(pwd.equals((String) "dime")) {
    statusTextArea.setText("You are requested to change your " +
    "initial assigned password. Click 'Change password' please.");
    else {
    //Set UserConnection Panel to invisible
    setVisible(false);
    dispose();
    //Get connection to the table
    if(userTable.elementAt(i).elementAt(2).equals("0")) {
    //Get connection to non-editable table
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    PVRackReportNonEdit rackReport = new PVRackReportNonEdit();
    rackReport.createAndShowDialog();
    else {
    if(userTable.elementAt(i).elementAt(2).equals("1")) {
    //Get connection to editable table
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    PVRackReport rackReport = new PVRackReport(user);
    rackReport.createAndShowDialog();
    //PVRackReport rackReport = new PVRackReport();
    else statusTextArea.setText("You do not get approval for viewing data. " +
    "Please contact the administrator for details.");
    else {
    passwordField.setText("");
    statusTextArea.setText("Please enter corrected password or" +
    "the administrator for details.");
    i++;
    if(!checkUser) {
    passwordField.setText("");
    statusTextArea.setText("Not find such user's name." +
    "contact the admistrator for details.");
    private void submitButtonMouseClicked(java.awt.event.MouseEvent evt) {                                         
    // TODO add your handling code here:
    * @param args the command line arguments
    public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
    new UserConnection().setVisible(true);
    public String getUser() {
    return userTextField.getText();
    public String getPwd() {
    return passwordField.getText();
    // Variables declaration - do not modify
    private javax.swing.JButton changePwdButton;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JPasswordField passwordField;
    private javax.swing.JLabel pwdLabel;
    private javax.swing.JLabel statusLabel;
    private javax.swing.JTextArea statusTextArea;
    private javax.swing.JButton submitButton;
    private javax.swing.JLabel userLabel;
    private javax.swing.JTextField userTextField;
    // End of variables declaration
    Here is my JDBCAdapter
    package rackdemo2;
    * This is an adaptor which transforms the JDBC interface
    * to the PVRackTableDialogue
    import java.util.Vector;
    import java.sql.*;
    import javax.swing.table.AbstractTableModel;
    import javax.swing.event.TableModelEvent;
    public class JDBCAdapter {
    Connection connection;
    Statement statement;
    ResultSet resultSet;
    Vector<String> columnNames = new Vector<String>();
    Vector<Vector<String>> rows = new Vector<Vector<String>>();
    ResultSetMetaData metaData;
    public JDBCAdapter(String url, String driverName,
    String user, String passwd) {
    try {
    Class.forName(driverName);
    connection = DriverManager.getConnection(url, user, passwd);
    statement = connection.createStatement();
    catch (ClassNotFoundException ex) {
    System.err.println("Cannot find the database driver classes.");
    System.err.println(ex);
    catch (SQLException ex) {
    System.err.println("Cannot connect to this database.");
    System.err.println(ex);
    public void executeQuery(String query) {
    if (connection == null || statement == null) {
    System.err.println("There is no database to execute the query.");
    return;
    try {
    resultSet = statement.executeQuery(query);
    metaData = resultSet.getMetaData();
    int numberOfColumns = metaData.getColumnCount();
    // Get the column names and cache them.
    // Then we can close the connection.
    for(int column = 0; column < numberOfColumns; column++) {
    columnNames.addElement(metaData.getColumnLabel(column+1));
    // Get all rows.
    while (resultSet.next()) {
    Vector<String> newRow = new Vector<String>();
    for (int i = 1; i <= columnNames.size(); i++) {
    String tempString = resultSet.getString(i);
    if(!tempString.equals("null")) {
    newRow.addElement(tempString);
    else {
    newRow.addElement("");
    rows.addElement(newRow);
    //Modify dataTable to add empty row to separate chassis
    if(numberOfColumns>1) {
    int nRow = rows.size();
    Vector<String> row = new Vector<String>();
    for(int i=0; i<numberOfColumns; i++){
    row.add("");
    if(nRow>0 || numberOfColumns>0) {
    //Adding blank row to separate chassis
    int i = 0;
    while(i<nRow) {
    if(!rows.elementAt(i).elementAt(0).equals("")) {
    if(i>0) {
    rows.add(i, row);
    i++;
    nRow = rows.size();
    i++;
    close();
    catch (SQLException ex) {
    System.err.println(ex);
    public void close() throws SQLException {
    resultSet.close();
    statement.close();
    connection.close();
    // MetaData
    public Vector<String> getColumnNames() {
    return columnNames;
    public Vector<Vector<String>> getDataTable() {
    return rows;
    public int getColumnCount() {
    return columnNames.size();
    // Data methods
    public int getRowCount() {
    return rows.size();
    }

    Thank you for your answer.
    I'm very new to mySql as server. When I was assigned
    to write the application, the administrator has set
    up mySql database in the company web server for my
    application. My program runs very when using my
    workplace desktop with java web start or with java
    web start in netbeans (all paths should be link to my
    desktop hard disk, i.e. users/application/). I can
    not run the application at home because I can not
    access to the company intranet server (for security
    purpose). The problem happens when I post the
    application in the company web page (I have to modify
    all paths in jnlp file to the company web address).
    The program then runs without exception except it
    seems that it gets no data from the database (for
    example, when I type my username, it returns that
    "There is no such user name. contact.." as what I
    code in the application for not correcting user name)
    It happens for not only using my company desktop but
    also for others.
    Please help me.
    Thank you in advance.And all this could have been answered yesterday, in your other thread, when I asked you "Is the DB configured to allow that user to connect to the DB from where that user is attempting to connect from?"
    Seeing as how you get that error, the obvious answer was, "No." At which point we could have continued.
    Configure the needed users into the DB, without forgetting to allow them access from the machines from which they are going to access from.
    Although, I agree with Rene, that you should set up a server of some sort, located on the same machine as the DB, for communicating with the DB.

  • Calling a class's method from another class

    Hi, i would like to know if it's possible to call a Class's method and get it's return from another Class. This first Class doesn't extend the second. I've got a Choice on this first class and depending on what is selected, i want to draw a image on the second class witch is a Panel extended. I put the control "if" on the paint() method of the second class witch is called from the first by the repaint() (first_class.repaint()) on itemStateChanged(). Thankx 4 your help. I'm stuck with this.This program is for my postgraduation final project and i'm very late....

    import java.awt.*;
    import java.sql.*;
    * This type was generated by a SmartGuide.
    class Test extends Frame {
         private java.awt.Panel ivjComboPane = null;
         private java.awt.Panel ivjContentsPane = null;
         IvjEventHandler ivjEventHandler = new IvjEventHandler();
         private Combobox ivjCombobox1 = null;
    class IvjEventHandler implements java.awt.event.WindowListener {
              public void windowActivated(java.awt.event.WindowEvent e) {};
              public void windowClosed(java.awt.event.WindowEvent e) {};
              public void windowClosing(java.awt.event.WindowEvent e) {
                   if (e.getSource() == Test.this)
                        connEtoC1(e);
              public void windowDeactivated(java.awt.event.WindowEvent e) {};
              public void windowDeiconified(java.awt.event.WindowEvent e) {};
              public void windowIconified(java.awt.event.WindowEvent e) {};
              public void windowOpened(java.awt.event.WindowEvent e) {};
         private Panel ivjPanel1 = null;
    * Combo constructor comment.
    public Test() {
         super();
         initialize();
    * Combo constructor comment.
    * @param title java.lang.String
    public Test(String title) {
         super(title);
    * Insert the method's description here.
    * Creation date: (11/16/2001 7:48:51 PM)
    * @param s java.lang.String
    public void conexao(String s) {
         try {
              Class.forName("oracle.jdbc.driver.OracleDriver");
              String url = "jdbc:oracle:thin:system/[email protected]:1521:puc";
              Connection db = DriverManager.getConnection(url);
              //String sql_str = "SELECT * FROM referencia";
              Statement sq_stmt = db.createStatement();
              ResultSet rs = sq_stmt.executeQuery(s);
              ivjCombobox1.addItem("");
              while (rs.next()) {
                   String dt = rs.getString(1);
                   ivjCombobox1.addItem(dt);
              db.close();
         } catch (SQLException e) {
              System.out.println("Erro sql" + e);
         } catch (ClassNotFoundException cnf) {
    * connEtoC1: (Combo.window.windowClosing(java.awt.event.WindowEvent) --> Combo.dispose()V)
    * @param arg1 java.awt.event.WindowEvent
    /* WARNING: THIS METHOD WILL BE REGENERATED. */
    private void connEtoC1(java.awt.event.WindowEvent arg1) {
         try {
              // user code begin {1}
              // user code end
              this.dispose();
              // user code begin {2}
              // user code end
         } catch (java.lang.Throwable ivjExc) {
              // user code begin {3}
              // user code end
              handleException(ivjExc);
    * Return the Combobox1 property value.
    * @return Combobox
    /* WARNING: THIS METHOD WILL BE REGENERATED. */
    private Combobox getCombobox1() {
         if (ivjCombobox1 == null) {
              try {
                   ivjCombobox1 = new Combobox();
                   ivjCombobox1.setName("Combobox1");
                   ivjCombobox1.setLocation(30, 30);
                   // user code begin {1}
                   this.conexao("select * from referencia");
                   // user code end
              } catch (java.lang.Throwable ivjExc) {
                   // user code begin {2}
                   // user code end
                   handleException(ivjExc);
         return ivjCombobox1;
    * Return the ComboPane property value.
    * @return java.awt.Panel
    /* WARNING: THIS METHOD WILL BE REGENERATED. */
    private java.awt.Panel getComboPane() {
         if (ivjComboPane == null) {
              try {
                   ivjComboPane = new java.awt.Panel();
                   ivjComboPane.setName("ComboPane");
                   ivjComboPane.setLayout(null);
                   getComboPane().add(getCombobox1(), getCombobox1().getName());
                   getComboPane().add(getPanel1(), getPanel1().getName());
                   // user code begin {1}
                   // user code end
              } catch (java.lang.Throwable ivjExc) {
                   // user code begin {2}
                   // user code end
                   handleException(ivjExc);
         return ivjComboPane;
    * Return the ContentsPane property value.
    * @return java.awt.Panel
    /* WARNING: THIS METHOD WILL BE REGENERATED. */
    private java.awt.Panel getContentsPane() {
         if (ivjContentsPane == null) {
              try {
                   ivjContentsPane = new java.awt.Panel();
                   ivjContentsPane.setName("ContentsPane");
                   ivjContentsPane.setLayout(new java.awt.BorderLayout());
                   getContentsPane().add(getComboPane(), "Center");
                   // user code begin {1}
                   // user code end
              } catch (java.lang.Throwable ivjExc) {
                   // user code begin {2}
                   // user code end
                   handleException(ivjExc);
         return ivjContentsPane;
    * Return the Panel1 property value.
    * @return Panel
    /* WARNING: THIS METHOD WILL BE REGENERATED. */
    private Panel getPanel1() {
         if (ivjPanel1 == null) {
              try {
                   ivjPanel1 = new Panel();
                   ivjPanel1.setName("Panel1");
                   ivjPanel1.setBackground(java.awt.SystemColor.scrollbar);
                   ivjPanel1.setBounds(24, 118, 244, 154);
                   // user code begin {1}
                   // user code end
              } catch (java.lang.Throwable ivjExc) {
                   // user code begin {2}
                   // user code end
                   handleException(ivjExc);
         return ivjPanel1;
    * Called whenever the part throws an exception.
    * @param exception java.lang.Throwable
    private void handleException(java.lang.Throwable exception) {
         /* Uncomment the following lines to print uncaught exceptions to stdout */
         // System.out.println("--------- UNCAUGHT EXCEPTION ---------");
         // exception.printStackTrace(System.out);
    * Initializes connections
    * @exception java.lang.Exception The exception description.
    /* WARNING: THIS METHOD WILL BE REGENERATED. */
    private void initConnections() throws java.lang.Exception {
         // user code begin {1}
         // user code end
         this.addWindowListener(ivjEventHandler);
    * Initialize the class.
    /* WARNING: THIS METHOD WILL BE REGENERATED. */
    private void initialize() {
         try {
              // user code begin {1}
              // user code end
              setName("Combo");
              setLayout(new java.awt.BorderLayout());
              setSize(460, 300);
              setTitle("Combo");
              add(getContentsPane(), "Center");
              initConnections();
         } catch (java.lang.Throwable ivjExc) {
              handleException(ivjExc);
         // user code begin {2}
         // user code end
    * Insert the method's description here.
    * Creation date: (11/17/2001 2:02:58 PM)
    * @return java.lang.String
    public String readCombo() {
         String dado = ivjCombobox1.getSelectedItem();
         return dado;
    * Starts the application.
    * @param args an array of command-line arguments
    public static void main(java.lang.String[] args) {
         try {
              /* Create the frame */
              Test aTest = new Test();
              /* Add a windowListener for the windowClosedEvent */
              aTest.addWindowListener(new java.awt.event.WindowAdapter() {
                   public void windowClosed(java.awt.event.WindowEvent e) {
                        System.exit(0);
              aTest.setVisible(true);
         } catch (Throwable exception) {
              System.err.println("Exception occurred in main() of Test");
              exception.printStackTrace(System.out);
    * Insert the type's description here.
    * Creation date: (11/17/2001 1:59:15 PM)
    * @author:
    class Combobox extends java.awt.Choice {
         public java.lang.String dado;
    * Combobox constructor comment.
    public Combobox() {
         super();
         initialize();
    * Called whenever the part throws an exception.
    * @param exception java.lang.Throwable
    private void handleException(java.lang.Throwable exception) {
         /* Uncomment the following lines to print uncaught exceptions to stdout */
         // System.out.println("--------- UNCAUGHT EXCEPTION ---------");
         // exception.printStackTrace(System.out);
    * Initialize the class.
    /* WARNING: THIS METHOD WILL BE REGENERATED. */
    private void initialize() {
         try {
              // user code begin {1}
              // user code end
              setName("Combobox");
              setSize(133, 23);
         } catch (java.lang.Throwable ivjExc) {
              handleException(ivjExc);
         // user code begin {2}
         // user code end
    * main entrypoint - starts the part when it is run as an application
    * @param args java.lang.String[]
    public static void main(java.lang.String[] args) {
         try {
              java.awt.Frame frame = new java.awt.Frame();
              Combobox aCombobox;
              aCombobox = new Combobox();
              frame.add("Center", aCombobox);
              frame.setSize(aCombobox.getSize());
              frame.addWindowListener(new java.awt.event.WindowAdapter() {
                   public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
              frame.setVisible(true);
         } catch (Throwable exception) {
              System.err.println("Exception occurred in main() of Combobox");
              exception.printStackTrace(System.out);
    * Insert the type's description here.
    * Creation date: (11/17/2001 2:16:11 PM)
    * @author:
    class Panel extends java.awt.Panel {
    * Panel constructor comment.
    public Panel() {
         super();
         initialize();
    * Panel constructor comment.
    * @param layout java.awt.LayoutManager
    public Panel(java.awt.LayoutManager layout) {
         super(layout);
    * Called whenever the part throws an exception.
    * @param exception java.lang.Throwable
    private void handleException(java.lang.Throwable exception) {
         /* Uncomment the following lines to print uncaught exceptions to stdout */
         // System.out.println("--------- UNCAUGHT EXCEPTION ---------");
         // exception.printStackTrace(System.out);
    * Initialize the class.
    /* WARNING: THIS METHOD WILL BE REGENERATED. */
    private void initialize() {
         try {
              // user code begin {1}
              // user code end
              setName("Panel");
              setLayout(null);
              setSize(260, 127);
         } catch (java.lang.Throwable ivjExc) {
              handleException(ivjExc);
         // user code begin {2}
         // user code end
    * main entrypoint - starts the part when it is run as an application
    * @param args java.lang.String[]
    public static void main(java.lang.String[] args) {
         try {
              java.awt.Frame frame = new java.awt.Frame();
              Panel aPanel;
              aPanel = new Panel();
              frame.add("Center", aPanel);
              frame.setSize(aPanel.getSize());
              frame.addWindowListener(new java.awt.event.WindowAdapter() {
                   public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
              frame.setVisible(true);
         } catch (Throwable exception) {
              System.err.println("Exception occurred in main() of java.awt.Panel");
              exception.printStackTrace(System.out);
    * Insert the method's description here.
    * Creation date: (11/17/2001 2:18:36 PM)
    public void paint(Graphics g) {
    /* Here's the error:
    C:\Test.java:389: non-static method readCombo() cannot be referenced from a static context
         System.out.println(Test.lerCombo());*/
         System.out.println(Test.readCombo());

  • TextPANE's Y_AXIS preferredSpan not set, but textAREA's is ?

    I can do
    area = new JTextArea();
    area.setText( "Some text" );
    view = area.getUI().getRootView( area );
    height = view.getPreferredSpan( View.Y_AXIS ) ;and height is set to 16.0. But if I do
    pane = new JTextPane();
    pane.setText( "Some text" );
    view = pane.getUI().getRootView( pane );
    height = view.getPreferredSpan( View.Y_AXIS );height is always 0.0. Why is this?
    Interestingly,
    width = view.getPreferredSpan( View.X_AXIS );does give me a value back , the same in both cases ( 54.0 in my case ).
    : jay

    Why is this?Check out this demo code:
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.text.*;
    public class UTextComponent
         **  Return the current column number at the Caret Position.
         public static int getColumnAtCaret(JTextComponent component)
              int caretPosition = component.getCaretPosition();
              Element root = component.getDocument().getDefaultRootElement();
              int line = root.getElementIndex( caretPosition );
              int lineStart = root.getElement( line ).getStartOffset();
              return caretPosition - lineStart + 1;
              int rowStart = 0;
              try
                   rowStart = Utilities.getRowStart(component, component.getCaretPosition());
              catch(BadLocationException ble) {}
              return component.getCaretPosition() - rowStart;
         **  Return the current line number at the Caret position.
         public static int getLineAtCaret(JTextComponent component)
              int caretPosition = component.getCaretPosition();
              Element root = component.getDocument().getDefaultRootElement();
              return root.getElementIndex( caretPosition ) + 1;
         **  Return the number of lines of text.
         public static int getLines(JTextComponent component)
              Element root = component.getDocument().getDefaultRootElement();
              return root.getElementCount();
         **  Position the caret at the start of a line.
         public static void gotoLine(JTextComponent component, int line)
              Element root = component.getDocument().getDefaultRootElement();
              line = Math.max(line, 1);
              line = Math.min(line, root.getElementCount());
              component.setCaretPosition( root.getElement( line - 1 ).getStartOffset() );
              //  The following will position the caret at the start of the first word
              try
                   component.setCaretPosition(
                        Utilities.getNextWord(component, component.getCaretPosition()));
              catch(Exception e) {System.out.println(e);}
         **  Return the number of lines of text, including wrapped lines.
         public static int getWrappedLines(JTextPane component)
              int lines = 0;
              View view = component.getUI().getRootView(component).getView(0);
              System.out.println("view: " + (int)view.getPreferredSpan(View.Y_AXIS) );
              int paragraphs = view.getViewCount();
              System.err.println("p: " + paragraphs);
              for (int i = 0; i < paragraphs; i++)
                   lines += view.getView(i).getViewCount();
              return lines;
         **  Return the number of lines of text, including wrapped lines.
         public static int getWrappedLines(JTextArea component)
              View view = component.getUI().getRootView(component).getView(0);
              int preferredHeight = (int)view.getPreferredSpan(View.Y_AXIS);
              int lineHeight = component.getFontMetrics( component.getFont() ).getHeight();
              return preferredHeight / lineHeight;
         public static void main(String[] args)
              final JTextPane textComponent = new JTextPane();
    //          final JTextArea textComponent = new JTextArea(5, 15);
    //          textComponent.setLineWrap( true );
    //          textComponent.setWrapStyleWord( true );
    //          textComponent.setText("1\n2\n3\n4\n5\n6\n7");
    //          textComponent.setEditable(false);
              textComponent.addCaretListener( new CaretListener()
                   public void caretUpdate(CaretEvent e)
                        System.out.print
                             "Column/Line : " +
                             UTextComponent.getColumnAtCaret( textComponent ) +
                             "/" +
                             UTextComponent.getLineAtCaret( textComponent ) +
                             ", Lines : " +
                             UTextComponent.getLines( textComponent ) +
                             ", Wrapped Lines : "
                        //  It looks like the View has not yet been updated.
                        //  Add request to end of queue
    //                    SwingUtilities.invokeLater( new Runnable()
    //                         public void run()
                                  System.out.println(
                                       UTextComponent.getWrappedLines( textComponent ) );
              JScrollPane scrollPane = new JScrollPane( textComponent );
              JPanel panel = new JPanel();
              panel.add( new JLabel( "Goto Line:" ) );
              final JTextField gotoField = new JTextField(4);
              panel.add( gotoField );
              gotoField.addActionListener( new java.awt.event.ActionListener()
                   public void actionPerformed(java.awt.event.ActionEvent e)
                        UTextComponent.gotoLine(textComponent,
                             Integer.parseInt( gotoField.getText()) );
                        gotoField.setText("");
                        textComponent.requestFocus();
              JFrame frame = new JFrame( "Text Component Utilities" );
              frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
              frame.getContentPane().add( scrollPane );
              frame.getContentPane().add(panel, java.awt.BorderLayout.SOUTH);
    //          frame.pack();
              frame.setSize(300, 300);
              frame.setVisible(true);
    }a) Run the code as is
    b) enter a single character, view = 16
    c) use enter key to add a new line, view = 16
    d) use enter key to add a new line, view = 32
    This is inconsistent behaviour. The view should change with each new line
    e) use backspace key until you are left with a single character, view = 0 ?
    f) use left arrow key, view = 16
    Again this is inconsistent
    Now remove the comments for the code that uses the SwingUtilities.invokeLater and repeat above tests. This view seems to update normally as far as I can see.
    So, I guess the answer to your question is that the view processing for JTextPane is more complicated than it is for JTextArea and some of this processing is added to the end of the event thread when the setText() method is used, so you are getting an old value.
    Also, notice how my two methods for getWrappedLines are different for the JTextArea and JTextpane. You would hope/expect that the view methods would return the same values but they didn't. In this case I would consider the JTextPane to be the correct code and the JTextArea inconsistent.

  • Cannot find class: Exception??

    Hi
    The compiler claims it cannot find class FileNotFoundException or any other exception in my Main. Any packages I import has no problem. My structure:
    java \ myMain \ Main.java
    java \ com \ myName \ packages //no, the space is just there as visual help:)
    Use javac -classpath java\ @compile.file
    ...where compile.file is a txt file giving the paths and filenames to all files I include.
    This is first time I use the -classpath parameter, but I believed java.lang always was included. What Am I doing wrong.
    regards
    JT

    You should review the tool documentation for the javac command and its use of classpath.
    Your problem appears to be due to the way you defined classpath, "-classpath java\". While you don't provide enough information to conclusively say what it should be, I'm guessing it should also include java\myMain\ - assuming that you're issuing the javac command from the parent of the \java\ directory, as your command example indicates.
    Here is a clip about its use of the classpath.
    "When compiling a source file, the compiler often needs information about a type whose definition did not appear in the source files given on the command line. The compiler needs type information for every class or interface used, extended, or implemented in the source file. This includes classes and interfaces not explicitly mentioned in the source file but which provide information through inheritance.
    For example, when you subclass java.applet.Applet, you are also using Applet's ancestor classes: java.awt.Panel, java.awt.Container, java.awt.Component, and java.lang.Object.
    When the compiler needs type information, it looks for a source file or class file which defines the type. The compiler searches for class files first in the bootstrap and extension classes, then in the user class path (which by default is the current directory). The user class path is defined by setting the CLASSPATH environment variable or by using the -classpath command line option. (For details, see Setting the Class Path).
    If you set the -sourcepath option, the compiler searches the indicated path for source files; otherwise the compiler searches the user class path for both class files and source files."

  • Event-Handling  Between 2 Classes

    Trying to learn where did I make a mistake!
    Here is a very simple sample code:
    2 classes (each has 1 (awt-style)Panel & 1 (awt-style) Button. By clicking on one of the buttons how do I change the Background (color) of the Panel in the other class?
    //***********Sample Code **********************
    import java.awt.*;
    import java.awt.event.*;
    //=====================================================
    public class App extends Frame
    Panel_1 ap1; //ap1 --> additional panel #1
    Panel_2 ap2;
    public App()
    setLayout(null);
    setBounds(100,100,300,200);
    setBackground(Color.yellow);
    //re: Panel_1
    //=============
    ap1=new Panel_1();
    add(ap1);
    //re: Panel_2
    //===========
    ap2=new Panel_2();
    add(ap2);
    public static void main(String[] args)
    App app=new App();
    app.setVisible(true);
    //==============================================================
    class Panel_1 extends Panel implements ActionListener
    Panel_2 p2;
    Button ap1b=new Button();
    Panel_1()
    setBounds(50,120,100,50);
    setBackground(Color.green);
    ap1b.setBackground(Color.red);
    ap1b.addActionListener(p2);
    add(ap1b);
    public void actionPerformed(ActionEvent ae)
    if (ae.getSource()==p2.ap2b)
    System.out.println("Test Panel 1");
    //=================================
    class Panel_2 extends Panel implements ActionListener
    Panel_1 p1;
    Button ap2b=new Button();
    Panel_2()
    setBounds(50,30,200,50);
    setBackground(Color.orange);
    ap2b.setBackground(Color.red);
    ap2b.addActionListener(p1);
    add(ap2b);
    public void actionPerformed(ActionEvent ae)
    if (ae.getSource()==p1.ap1b)
    System.out.println("Test Panel 2");
    }

    There are several ways to do this. Without going into all of them, let's narrow them down by thinking in terms of design. Why should the panels know anything about each other? Each panel is its own deal. The component which has both of the panels should be the one listening to the buttons.
    Really there is no reason to have separate classes for the panels, but if you must, then write a listener as an inner class of the frame class, then pass that listener to the constructor of each panel as you instantiate it. Then you can have the listener work with both panels directly.
    Drake

  • Need a little code help please

    I am writing a program that shows a house with some clouds moving a the top. I have all the class compiling correctly, when it runs the clouds and background are painted over the house. I think I am just missing something small here. Can someone help me please. Thanks.
    public class BallApp extends javax.swing.JFrame {
      public BallApp (String title) {
        super(title);
        this.setSize(600, 450);
        this.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);
        this.add(new BallPanel());
        this.setVisible(true);
        this.add(new LinePanel());
        this.setVisible(true);
      public static void main (String [ ] args) {
        BallApp app = new BallApp ("Chapter 7: BallApp");
    public class LinePanel extends javax.swing.JPanel
       private SmartLine _myLine, _myLine2, _myLine3;          //instance variables for lines
       private SmartLine _myLine4, _myLine5;
       public LinePanel()
         super();
         _myLine = new SmartLine(210, 290, 210, 365, java.awt.Color.BLACK);  //creates lines sets position/color
         _myLine2 = new SmartLine(290, 290, 290, 365, java.awt.Color.BLACK);
            _myLine3 = new SmartLine (210, 365, 290, 365, java.awt.Color.BLACK);
         _myLine4 = new SmartLine (200, 300, 250, 245, java.awt.Color.BLACK);     
         _myLine5 = new SmartLine (250, 245, 300, 300, java.awt.Color.BLACK);
         this.setBackground(java.awt.Color.BLUE);     //sets background color
       public void paintComponent (java.awt.Graphics aBrush)
         super.paintComponent(aBrush);          //method paints lines on to panel
         java.awt.Graphics2D betterBrush = (java.awt.Graphics2D) aBrush;
         _myLine.draw(betterBrush);
         _myLine2.draw(betterBrush);
         _myLine3.draw(betterBrush);
         _myLine4.draw(betterBrush);
         _myLine5.draw(betterBrush);
    } //end of class
    public class BallPanel extends javax.swing.JPanel implements Mover {
        private final int INIT_X = 75; // attributes
        private final int INIT_Y = 75;
        private final int INIT_X1 = 0;
        private final int INIT_Y1 = 0;
        private final int DIAMETER = 60;
        private final int INTERVAL = 100;
        private BouncingBall _ball, _ball2; // components
        private MoveTimer _timer;
        public BallPanel () {
         super();
         _ball = new BouncingBall (java.awt.Color.white, this); 
         _ball2 = new BouncingBall (java.awt.Color.white, this);
         _timer = new MoveTimer(INTERVAL, this);
         //this.setBackground(java.awt.Color.blue);
         _ball.setLocation(INIT_X, INIT_Y);
         _ball.setSize(DIAMETER, DIAMETER);
         _ball2.setLocation(INIT_X1, INIT_Y1);
         _ball2.setSize(DIAMETER, DIAMETER);
         _timer.start();
        public void move() {
         _ball.move();
         _ball2.move();
         this.repaint();
        public void paintComponent (java.awt.Graphics aBrush) {
         super.paintComponent(aBrush);
         java.awt.Graphics2D betterBrush =
             (java.awt.Graphics2D) aBrush;
         _ball.fill(betterBrush);
         _ball2.fill(betterBrush);
    }

    ok.
    public interface Mover {
        public void move();
    public class BouncingBall extends SmartEllipse implements Mover {
        private int _changeX, _changeY; // attributes
        private final int MOVE_LEN = 5;
        private javax.swing.JPanel _panel; // peer object (and container)
        private javax.swing.Timer _timer;
        private double nextY;
        public BouncingBall (java.awt.Color aColor,
                             javax.swing.JPanel aPanel){
         super(aColor);
         _changeX = MOVE_LEN;
         _changeY = MOVE_LEN;
         _panel = aPanel; nextY=75;
        public void move() {
         int nextX = (int)this.getX() + _changeX;
         if (nextX <= this.getMinBoundX()) {
             _changeX *= -1;
             nextX = this.getMinBoundX();
         else if (nextX >= this.getMaxBoundX()) {
             _changeX *= -1;
             nextX = this.getMaxBoundX();
         this.setLocation(nextX, nextY);
        public int getMinBoundX() {
         return (int) _panel.getX();
        public int getMaxBoundX() {
              return (int) (_panel.getX() + _panel.getWidth()
                    - this.getWidth());
    public class MoveTimer extends javax.swing.Timer {
        private Mover _mover; // peer object
       public MoveTimer (int anInterval, Mover aMover) {
          super(anInterval, null);
          _mover = aMover;
          this.addActionListener(new MoveListener());
       private class MoveListener implements java.awt.event.ActionListener {
         public void actionPerformed(java.awt.event.ActionEvent e){
            _mover.move();
    public class SmartLine extends java.awt.geom.Line2D.Double
       private java.awt.Color _lineColor;
       private final int STROKE_WIDTH = 2;          //makes width of line constant
       private double X1, Y1, X2, Y2;          //set as instance variables that are doubles
       public SmartLine (double X1, double Y1, double X2, double Y2, java.awt.Color aColor)
         _lineColor = aColor;          //constructor
         setLine(X1,Y1,X2,Y2);
         X1 = 0;                    //sets intial positions to 0
         Y1 = 0;
         X2 = 0;
         Y2 = 0;
       public void setLineColor (java.awt.Color aColor)
         _lineColor = aColor;          //method for setting the color of the lines
       public void setLocation (double X1, double X2, double Y1, double Y2)
         this.setLine (getP1(), getP2()); //method for setting location of lines             
       public void draw (java.awt.Graphics2D aBrush)
         java.awt.Color savedColor = aBrush.getColor();        //method draws the line with color set
         aBrush.setColor(_lineColor);
         java.awt.Stroke savedStroke = aBrush.getStroke();
         aBrush.setStroke(new java.awt.BasicStroke(STROKE_WIDTH));
         aBrush.draw(this);
         aBrush.setStroke(savedStroke);
         aBrush.setColor(savedColor);
    } //end of class

  • Drawing moving GIF images?

    Is it possible to draw moving gif images on a simple Frame applet?
    I made an image drawer class for my applet and i can draw simple 2d images.
    Here is the basis of my GameSprite class;
        public byte[] pixels;
        public int width;
        public int height;
        public GameSprite(String imageName, int requestIndex) {
         try {
                    // Removed code, it's zipInputStream, but it can be used just as ./image.jpg etc
         javax.swing.ImageIcon icon = new javax.swing.ImageIcon(fileBytes);
         width = icon.getIconWidth();
                     height = icon.getIconHeight();
                     pixels = fileBytes;
         } catch(Exception e) {
              e.printStackTrace();
        public void drawSprite(int x, int y) {
         try {
              Image image = Toolkit.getDefaultToolkit().createImage(pixels);
                                    //Removed code here
              graphics.drawImage(image, x, y + 7, width, height, observer);
         } catch(Exception e) {
              e.printStackTrace();
        }If i try to draw an animated gif image it dosn't move.
    Thanks for any help.

    In Java you need to override the paint method in AWT and paintComponenet method in SWING to do graphics/animation. If you go to an offscreen rendering, then you can paint to the graphics context of an image you use for a drawImage in your paint/paintComponent...
    If you where overriding a Panel in AWT you would override paint:
    public void paint(Graphics g){
      g.drawImage(im, 0, 0, this);
    }Then where you are maipulating your graphics you would do something like this:
    //code snippet
    Graphics g = im.getGraphics();
    //make what ever changes to im by manipulating the graphics context g
    repaint();

  • Moving GIF images

    Hi
    Earler I had Golive and could make moving GIF images in a timeline. Can ayone tell me how it works in Dreamweaver CS4?
    ...from the beginning..
    Sten, Boras, Sweden

    In Java you need to override the paint method in AWT and paintComponenet method in SWING to do graphics/animation. If you go to an offscreen rendering, then you can paint to the graphics context of an image you use for a drawImage in your paint/paintComponent...
    If you where overriding a Panel in AWT you would override paint:
    public void paint(Graphics g){
      g.drawImage(im, 0, 0, this);
    }Then where you are maipulating your graphics you would do something like this:
    //code snippet
    Graphics g = im.getGraphics();
    //make what ever changes to im by manipulating the graphics context g
    repaint();

  • Nature of ClassLoading, special circumstance(?)

    Let me start with some skeletal code:
    class MyCustom extends Thread{
    BufferedReader br; PrintWriter pw; Socket sock;
    public MyCustom(Socket s)
    /*set stuff here*/
    public MyCustom(Socket s, BufferedReader b, PrintWriter p)
    sock=s; br=b; pw=p;
    public void run(){*do something*/}
    public BufferedReader get_br(){return br;}
    public PrintWriter get_pw(){return pw;}
    public Socket get_sock(){return sock;}
    Given the above, let's say that a new version of MyCustom.class is to be downloaded, but the Socket should remain open.... I have a second class that does not change in this manner, so...
    class MyPlaceHolder extends Thread{
    Socket sock; BufferedReader br; PrintWriter pw;
    public MyPlaceHolder(Socket s, BufferedReader b, PrintWriter p)
    sock=s; br=b; pw=p;
    public void run()
    /*do some sending and receiving*/
    public Socket get_sock(){return sock;}
    public BufferedReader get_br(){return br;}
    public PrintWriter get_pw(){return pw;}
    Ok... Here is the scenario... When it is ready to update that MyCustom.class file, it does this:
    (given a MyCustom mc already existing):
    some_method(){
    MyPlaceHolder mph = new MyPlaceHolder(mc.get_sock(),mc.get_br(),mc.get_pw());
    new Thread(mph).start();
    mc = null;
    System.gc();
    /*download new .class file for MyCustom, replace old one, and then*/
    mc = new MyCustom(mph.get_sock(),mph.get_br(),mph.get_pw());
    new Thread(mc).start();
    Maybe I am convoluted in my stating of what I want to do... The crux of my question is this:
    1- When I go to create a new 'MyCustom', does it load dynamically, or does it cache the older object code for MyCustom.class?
    2- When does the class load...?
    In the following class:
    class Yoyo{
    TextField tf; TextArea ta; Panel p; Frame f; Vector v;
    public Yoyo()
    tf=new TextField(20); ta=new TextArea("",10,20); p=new Panel(); f=new Frame("Frame"); v=new Vector();
    When are the java.awt.TextField, java.awt.Panel, java.awt.TextArea, java.awt.Frame and java.util.Vector actually loaded? At the 'import' statement?
    OK... what about custom classes?
    Are they loaded at the declaration, or at the constructor?
    Thanks,
    Dave

    Well, no, not quite...close though.
    You can download the MyClass.class as many times as
    you want, but the class definition is only loaded into
    the primordial class loader the first time. Each and
    every time you want to change its definition, you have
    to supply a new ClassLoader and tell it to load the
    class; the JVM doesn't do that for you.
    All classes not already loaded into or available to
    the primordial class loader that are referenced by
    MyClass.class are then loaded by the same custom class
    loader automatically. For that reason, you should
    avoid loading MyClass.class with the primordial class
    loader. This since you can never get rid of it once
    it's loaded into the primordial class loader, and
    custom class loaders defer the search of classes to
    the primordial one before searching for new ones
    themselves.Thats true if your new class loader uses the findClass method (class loader delegation model) but if the loadClass method was derived then if you don;t call super.loadClass then the system class loader is never called for this class, so you can stop classes from getting loaded from the system class loader this way.
    With the java hotstop some classes are automatically loaded from the system class loader like [B, which is the class name for a byte[] (which does have a class of its own), even if you derive the loadClass method.
    The classic vm still calls the loadClass method for classes like this.
    >
    A bit convoluted, perhaps? :)
    It's not altogether easy, I admit.
    Here's an example:
    You have a class A that hasn't been loaded. A
    uses JPanel, JFrame, etc. You simply type new
    A(), and it's loaded by the primordial class
    loader.
    Then you create your own custom ClassLoader C,
    and tells it to define A. Now it won't, since A is
    already defined in the primordial class loader, and C
    asks the primordial class loader "do you know what
    this is, or can you find it"? Only if the answer is No
    to both those questions does C go about defining the
    class.
    You can go around that by not having C asking
    the primordial classloader first, but then you have to
    redefine every class, recursively, that A refers to,
    inside C...that, you don't want to do. Some are not
    even allowed, such as those beginning with "java.".
    You could delegate the java. classes with the super.loadClass method described earlier but
    There is a sneaky way of defining classes which start with java.
    by (using introspection and setting accessibility to true) call a function call define0 which is private to ClassLoader.
    Now... if you had told C to define A instead of using
    "new A()", then only those classes that don't already
    exist or can't be found by the primordial class loader
    would be loaded and defined by C. Meaning JPanel et al
    definitions would still come from the primordial class
    loader, since it can find them in its class path.
    if you told C to define A and still did "new A()" then the class would be
    loaded in C and the System class loader because C is higher in the class loader tree and would be asked..
    Using the class loader delegation model.
    D     E     a call to new A() in a class defined by both of these
    | |     class loaders would load the class in both only if C
    +========+     and the system class loader didn't have it loaded first.
    |
    C     a call to new A() in a class defined by this class loader would
    |      load the class in C only if the system class loader didn't have it      |     first
    |
    System a call to new A() in a class defined by the system class loader           would load A in the system class loader even if loaded in C           first.
    Back to the original problem,
    tomcat does this with its ServletLoader class, if the jar file which loaded the servlet changes then the ServletClassLoader is thrown away and a new classloader is created and the classes are reloaded, this is open so you can see the source for this at www.apache.org

  • Unable to resolve 'class' or 'interface' expected compile error

    Any help would be appreciated - I can't resolve the following compile errors:
    E:\j2sdk1.4.0\bin\RandomApp3\src\RandomApp3.java:85: 'class' or 'interface' expected private void initComponents() {
    E:\j2sdk1.4.0\bin\RandomApp3\src\RandomApp3.java:97: 'class' or 'interface' expected }
    E:\j2sdk1.4.0\bin\RandomApp3\src\RandomApp3.java:97: 'class' or 'interface' expected }
    3 errors
    here is the source:
    import javax.swing.JOptionPane;
    import java.applet.Applet;
    import java.awt.Graphics;
    import java.util.Random;
    public class RandomApp3 extends javax.swing.JApplet {
    public RandomApp3() {
    public static void main(String args[]) {
    /** Creates a new instance of RandomApp3 */
    public class RandInt {
    private Random randNum;
    //constructor for RandInt class
    public RandInt(int endInt) {
    int randNum;
    int range;
    int[] lottery = new int[5];
    for (int x = 0; x <=49; x++) {
    range = (int) (Math.floor(Math.random()*5 + 1));
    lottery[range]++;
    /** Initializes the applet RandomApp3 */
    public void initComponents() {
    try {
    java.awt.EventQueue.invokeAndWait(new Runnable() {
    public void run() {
    initComponents();
    } catch (Exception ex) {
    ex.printStackTrace();
    /** This method is called from within the init() method to
    * initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is
    * always regenerated by the Form Editor.
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">
    private void initComponents() {
    panell = new java.awt.Panel();
    getContentPane().add(panell, java.awt.BorderLayout.CENTER);
    // </editor-fold>
    // Variables declaration - do not modify
    private java.awt.Panel panel1;
    // End of variables declaration
    /** This method is called from within the init() method to
    * initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is
    * always regenerated by the Form Editor.
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">
    private void initComponents() {
    panel1 = new java.awt.Panel();
    getContentPane().add(panel1, java.awt.BorderLayout.CENTER);
    // </editor-fold>
    // Variables declaration - do not modify
    private java.awt.Panel panel1;
    // End of variables declaration
    }

    Re-posted with code tags. This may show that there is an extra } just before initComponents()
    public class RandomApp3 extends javax.swing.JApplet {
    public RandomApp3() {
    public static void main(String args[]) {
    /** Creates a new instance of RandomApp3 */
    public class RandInt {
    private Random randNum;
    //constructor for RandInt class
    public RandInt(int endInt) {
    int randNum;
    int range;
    int[] lottery = new int[5];
    for (int x = 0; x <=49; x++) {
    range = (int) (Math.floor(Math.random()*5 + 1));
    lottery[range]++;
    /** Initializes the applet RandomApp3 */
    public void initComponents() {
    try {
    java.awt.EventQueue.invokeAndWait(new Runnable() {
    public void run() {
    initComponents();
    } catch (Exception ex) {
    ex.printStackTrace();
    /** This method is called from within the init() method to
    * initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is
    * always regenerated by the Form Editor.
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">
    private void initComponents() {
    panell = new java.awt.Panel();
    getContentPane().add(panell, java.awt.BorderLayout.CENTER);
    // </editor-fold>
    // Variables declaration - do not modify
    private java.awt.Panel panel1;
    // End of variables declaration
    /** This method is called from within the init() method to
    * initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is
    * always regenerated by the Form Editor.
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">
    private void initComponents() {
    panel1 = new java.awt.Panel();
    getContentPane().add(panel1, java.awt.BorderLayout.CENTER);
    // </editor-fold>
    // Variables declaration - do not modify
    private java.awt.Panel panel1;
    // End of variables declaration
    }

  • JMenu hidden unde JPanel

    Hi,
    I write same simple application, and I have problem with a JMenu. When I make simple JMenu, and add it to this application, menu this will be hiden under JPanel and other controls...
    Here id code:
    Hi,
    I write same simple application, and I have problem with a JMenu. When I make simple JMenu, and add it to this application, menu this will be hiden under JPanel and other controls...
    Here id code:
    package pl.staniszczak.JFakturka.GUI;
    import java.awt.Component;
    import java.awt.Container;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.GridLayout;
    import java.awt.Panel;
    import javax.swing.JButton;
    import javax.swing.JComboBox;
    import javax.swing.JFormattedTextField;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    import javax.swing.JMenuItem;
    import javax.swing.JScrollPane;
    import javax.swing.JSpinner;
    import javax.swing.JTable;
    import javax.swing.JTextField;
    import pl.staniszczak.JFakturka.GUI.Actions.DrukujFaktureAction;
    import pl.staniszczak.JFakturka.GUI.Models.TowaryATModel;
    * @author Administrator
    public class MainFrame extends JFrame {
         private JTextField jtfNrFaktury;
         private JFormattedTextField jftfDataSprzedazy;
         private JFormattedTextField jftfDataFaktury;
         private JComboBox jcbPlatnosc;
         private JSpinner jsTerminPlatnosci;
         private JTextField jtfUwagi;
         private JTable jtTowary;
         private JButton jbDodajTowar;
         private JButton jbUsunTowar;
         public MainFrame() {
              setTitle("JFakturka 1.0");
              setResizable(false);
              setSize(450,400);
           * Menus
            JMenu menuFaktura = new JMenu("Faktura");
            JMenuItem drukuj = menuFaktura.add(new DrukujFaktureAction("Drukuj"));
            JMenuBar menuBar = new JMenuBar();
            setJMenuBar(menuBar);
            menuBar.add(menuFaktura);
             * Uk&#322;ad komponent�w
              //g&#322;�wny layout
              GridLayout gridLayout = new GridLayout(2,1);
              getContentPane().setLayout(gridLayout);
              //layout na kompionenty tekstowe
              Panel pnlText = new Panel();
              GridBagLayout gblLayout = new GridBagLayout();
            GridBagConstraints constraints = new GridBagConstraints();
            constraints.anchor = GridBagConstraints.WEST;
              pnlText.setLayout(gblLayout);
              add(pnlText);
            * Komponenty
              //Numer faktury
            JLabel jlblNrFaktury = new JLabel("Numer Faktury");
            buildConstraints(constraints, 0,0,1,1,100,100);
            gblLayout.setConstraints(jlblNrFaktury, constraints);
            pnlText.add(jlblNrFaktury);
            jtfNrFaktury = new JTextField(25);
            buildConstraints(constraints, 1,0,3,1,100,100);
            gblLayout.setConstraints(jtfNrFaktury, constraints);
            pnlText.add(jtfNrFaktury);
            //Data sprzeda&#380;y
            JLabel jlblDataSprzedazy = new JLabel("Data sprzeda&#380;y");
            buildConstraints(constraints, 0,2,1,1,100,100);
            gblLayout.setConstraints(jlblDataSprzedazy, constraints);
            pnlText.add(jlblDataSprzedazy);
            jftfDataSprzedazy = new JFormattedTextField();
            buildConstraints(constraints, 1,2,1,1,100,100);
            gblLayout.setConstraints(jftfDataSprzedazy, constraints);
            pnlText.add(jftfDataSprzedazy);
            //Data faktury
            JLabel jlblDataFaktury = new JLabel("Data faktury");
            buildConstraints(constraints, 2,2,1,1,100,100);
            gblLayout.setConstraints(jlblDataFaktury, constraints);
            pnlText.add(jlblDataFaktury);
            jftfDataFaktury = new JFormattedTextField();
            buildConstraints(constraints, 3,2,1,1,100,100);
            gblLayout.setConstraints(jftfDataFaktury, constraints);
            pnlText.add(jftfDataFaktury);
            //P&#322;atno&#347;&#263;
            JLabel jlblPlatnosc = new JLabel("P&#322;atno&#347;&#263;");
            buildConstraints(constraints, 0,3,1,1,100,100);
            gblLayout.setConstraints(jlblPlatnosc, constraints);
            pnlText.add(jlblPlatnosc);
            jcbPlatnosc = new JComboBox(new String[]{"Got�wka", "Przelew", "Inna"});
            buildConstraints(constraints, 1,3,1,1,100,100);
            gblLayout.setConstraints(jcbPlatnosc, constraints);
            pnlText.add(jcbPlatnosc);
            //Termin p&#322;atno&#347;ci
            JLabel jlblTerminPlatnosc = new JLabel("Termin");
            buildConstraints(constraints, 2,3,1,1,100,100);
            gblLayout.setConstraints(jlblTerminPlatnosc, constraints);
            pnlText.add(jlblTerminPlatnosc);
            jsTerminPlatnosci = new JSpinner();
            buildConstraints(constraints, 3,3,1,1,100,100);
            gblLayout.setConstraints(jsTerminPlatnosci, constraints);
            pnlText.add(jsTerminPlatnosci);
            //Uwagi
            JLabel jlblUwagi = new JLabel("Uwagi");
            buildConstraints(constraints, 0,4,1,1,100,100);
            gblLayout.setConstraints(jlblUwagi, constraints);
            pnlText.add(jlblUwagi);
            jtfUwagi = new JTextField(25);
            buildConstraints(constraints, 1,4,3,1,100,100);
            gblLayout.setConstraints(jtfUwagi, constraints);
            pnlText.add(jtfUwagi);
            //Dodaj towar
              jbDodajTowar = new JButton("Dodaj towar");
            buildConstraints(constraints, 0,5,4,1,100,100);
            gblLayout.setConstraints(jbDodajTowar, constraints);
            pnlText.add(jbDodajTowar);
            //Usu&#324; towar
              jbUsunTowar = new JButton("Usun towar");
            buildConstraints(constraints, 1,5,4,1,100,100);
            gblLayout.setConstraints(jbUsunTowar, constraints);
            pnlText.add(jbUsunTowar);
            //Towary
            TowaryATModel towaryModel = new TowaryATModel();
            jtTowary = new JTable(towaryModel);
            add(new JScrollPane(jtTowary));
         public void buildConstraints(GridBagConstraints gbc, int gx, int gy, int gw, int gh, int wx, int wy) {
              gbc.gridx = gx;
              gbc.gridy = gy;
              gbc.gridwidth = gw;
              gbc.gridheight = gh;
              gbc.weightx = wx;
              gbc.weighty = wy;
    }

    It's my bug - I use Panel from AWT. When I replace it by JPanel, it's start work:-)

  • Number line and position in the line

    Hi, is it possible to know the number of the line and the position of the cariet in a textarea?

    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.text.*;
    public class UTextComponent
         **  Return the current column number at the Caret Position.
         public static int getColumnAtCaret(JTextComponent component)
              int caretPosition = component.getCaretPosition();
              Element root = component.getDocument().getDefaultRootElement();
              int line = root.getElementIndex( caretPosition );
              int lineStart = root.getElement( line ).getStartOffset();
              return caretPosition - lineStart + 1;
         **  Return the current line number at the Caret position.
         public static int getLineAtCaret(JTextComponent component)
              int caretPosition = component.getCaretPosition();
              Element root = component.getDocument().getDefaultRootElement();
              return root.getElementIndex( caretPosition ) + 1;
         **  Return the number of lines of text.
         public static int getLines(JTextComponent component)
              Element root = component.getDocument().getDefaultRootElement();
              return root.getElementCount();
         **  Position the caret at the start of a line.
         public static void gotoLine(JTextComponent component, int line)
              Element root = component.getDocument().getDefaultRootElement();
              line = Math.max(line, 1);
              line = Math.min(line, root.getElementCount());
              component.setCaretPosition( root.getElement( line - 1 ).getStartOffset() );
              //  The following will position the caret at the start of the first word
              try
                   component.setCaretPosition(javax.swing.text.Utilities.getNextWord(component, component.getCaretPosition()));
              catch(Exception e) {System.out.println(e);}
         **  Return the number of lines of text, including wrapped lines.
         public static int getWrappedLines(JTextPane component)
              int lines = 0;
              View view = component.getUI().getRootView(component).getView(0);
              int paragraphs = view.getViewCount();
              for (int i = 0; i < paragraphs; i++)
                   lines += view.getView(i).getViewCount();
              return lines;
         public static void main(String[] args)
              final JTextPane textComponent = new JTextPane();
    //          final JTextArea textComponent = new JTextArea(5, 30);
    //          textComponent.setLineWrap( true );
              textComponent.addCaretListener( new CaretListener()
                   public void caretUpdate(CaretEvent e)
                        System.out.println
                             "Column/Line : " +
                             UTextComponent.getColumnAtCaret( textComponent ) +
                             "/" +
                             UTextComponent.getLineAtCaret( textComponent ) +
                             ", Lines : " +
                             UTextComponent.getLines( textComponent ) +
                             ", Wrapped Lines : " +
                             UTextComponent.getWrappedLines( textComponent )
                        SwingUtilities.invokeLater( new Runnable()
                             public void run()
                                  System.out.println( UTextComponent.getWrappedLines( textComponent ) );
              JScrollPane scrollPane = new JScrollPane( textComponent );
              JPanel panel = new JPanel();
              panel.add( new JLabel( "Goto Line:" ) );
              final JTextField gotoField = new JTextField(4);
              panel.add( gotoField );
              gotoField.addActionListener( new java.awt.event.ActionListener()
                   public void actionPerformed(java.awt.event.ActionEvent e)
                        UTextComponent.gotoLine(textComponent, Integer.parseInt( gotoField.getText()) );
                        gotoField.setText("");
                        textComponent.requestFocus();
              JFrame frame = new JFrame( "Text Component Utilities" );
              frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
              frame.getContentPane().add( scrollPane );
              frame.getContentPane().add(panel, java.awt.BorderLayout.SOUTH);
              frame.pack();
              frame.setVisible(true);
    }

Maybe you are looking for