Menubar in Swings

Hi,
I have a JMenuBar in My application which consists of 16 JMenus.
I need to get the 10 Menus in the first Line and remaining Menus at next Line As I need to pass My single Jmenubar Object to some othermethod.
kindly suggest Regarding this..
Regarding,
Das

If you want the menu items to wrap you should be able to just set the layout to FlowLayout.

Similar Messages

  • Create a popup window in Swing

    Hi, I want to create a popup window that contains some buttons and text fields when the user selects a menuItem from the menuBar using Swing. What would be the best way to do this?

    How to Use Menus:
    http://java.sun.com/docs/books/tutorial/uiswing/components/menu.html
    In your actionPerformed code you would create and display a JDialog.

  • Menubar in JSF

    Hello together!
    I am looking for something like a menubar in Swing.
    Something like a toolbar.
    Is there a way to build that with JSF??
    I would appreciate any hint. (Links, ...)
    Thanks.

    http://myfaces.apache.org/tomahawk/index.html
    Implemented with javascript
    Have a look to JSCook Menu
    My warnings:
    - you will have to fight to implement it!
    - There are some defaults, you can find some in this forum.
    - Main default is that it overrules JSF navigation principle because
    for what I know of you cannot activate a backing bean to check
    criteria and choose another jsp page
    Good luck
    :-)

  • What is equivalent of JInternalFrame in JavaFX 2.0?

    what is equivalent of JInternalFrame in JavaFX 2.0?
    Actually I want to use pure javaFX 2.0 to view report created in iReport 5.0.0.
    I have used java.swing code, and now I want to use pure javaFX 2.0.
    My code in swing is as follows
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    package reports;
    import java.awt.BorderLayout;
    import java.awt.Container;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    import java.util.HashMap;
    import net.sf.jasperreports.engine.JRException;
    import net.sf.jasperreports.engine.JasperFillManager;
    import net.sf.jasperreports.engine.JasperPrint;
    import net.sf.jasperreports.view.JRViewer;
    * @author TANVIR AHMED
    public class ReportsViewer extends javax.swing.JInternalFrame {
    * Creates new form MyiReportViewer
    private ReportsViewer()
    super("Report Viewer",true,true,true,true);
    initComponents();
    setBounds(10,10,600,500);
    setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    public ReportsViewer(String fileName)
    this(fileName,null);
    public ReportsViewer(String fileName,HashMap parameter)
    this();
    try
    /* load the required JDBC driver and create the connection
    here JDBC Type Four Driver for MySQL is used*/
    //Class.forName("com.mysql.jdbc.Driver");
    Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE", "invoice", "item");
    //Connection con=DriverManager.getConnection("jdbc:mysql://localhost/inventory","root","karim");
    /*(Here the parameter file should be in .jasper extension
    i.e., the compiled report)*/
    JasperPrint print = JasperFillManager.fillReport(
    fileName, parameter, con);
    JRViewer viewer=new JRViewer(print);
    Container c=getContentPane();
    c.setLayout(new BorderLayout());
    c.add(viewer);
    catch(SQLException sqle)
    sqle.printStackTrace();
    catch(JRException jre)
    jre.printStackTrace();
    * 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.
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {
    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGap(0, 394, Short.MAX_VALUE)
    layout.setVerticalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGap(0, 290, Short.MAX_VALUE)
    pack();
    }// </editor-fold>
    // Variables declaration - do not modify
    // End of variables declaration
    and
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    package reports;
    import java.beans.PropertyVetoException;
    * @author TANVIR AHMED
    public class MainUI extends javax.swing.JFrame {
    * Creates new form MainUI
    public MainUI() {
    super("REPORTS");
    initComponents();
    setSize(java.awt.Toolkit.getDefaultToolkit().getScreenSize());
    setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {
    jMenuItem1 = new javax.swing.JMenuItem();
    desktopPane = new javax.swing.JDesktopPane();
    salesTaxInv = new javax.swing.JButton();
    jLabel1 = new javax.swing.JLabel();
    supplyRegister = new javax.swing.JButton();
    PartyLedger = new javax.swing.JButton();
    menuBar = new javax.swing.JMenuBar();
    jMenuItem1.setText("jMenuItem1");
    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    desktopPane.setBackground(new java.awt.Color(255, 204, 0));
    desktopPane.setBorder(new javax.swing.border.MatteBorder(null));
    desktopPane.setForeground(new java.awt.Color(255, 0, 102));
    desktopPane.setAutoscrolls(true);
    desktopPane.setFont(new java.awt.Font("Bookman Old Style", 0, 14)); // NOI18N
    desktopPane.setPreferredSize(new java.awt.Dimension(1024, 768));
    salesTaxInv.setBackground(new java.awt.Color(255, 255, 255));
    salesTaxInv.setFont(new java.awt.Font("Bookman Old Style", 1, 18)); // NOI18N
    salesTaxInv.setForeground(new java.awt.Color(204, 0, 0));
    salesTaxInv.setText("Sales Tax Invoice");
    salesTaxInv.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    salesTaxInvActionPerformed(evt);
    salesTaxInv.setBounds(20, 53, 200, 31);
    desktopPane.add(salesTaxInv, javax.swing.JLayeredPane.DEFAULT_LAYER);
    jLabel1.setFont(new java.awt.Font("Bookman Old Style", 0, 24)); // NOI18N
    jLabel1.setForeground(new java.awt.Color(50, 72, 255));
    jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
    jLabel1.setText("Invoice System Reports");
    jLabel1.setBounds(0, -1, 1024, 50);
    desktopPane.add(jLabel1, javax.swing.JLayeredPane.DEFAULT_LAYER);
    supplyRegister.setFont(new java.awt.Font("Bookman Old Style", 1, 18)); // NOI18N
    supplyRegister.setForeground(new java.awt.Color(204, 0, 0));
    supplyRegister.setText("Supply Register");
    supplyRegister.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    supplyRegisterActionPerformed(evt);
    supplyRegister.setBounds(20, 100, 200, 30);
    desktopPane.add(supplyRegister, javax.swing.JLayeredPane.DEFAULT_LAYER);
    PartyLedger.setFont(new java.awt.Font("Bookman Old Style", 1, 18)); // NOI18N
    PartyLedger.setForeground(new java.awt.Color(204, 0, 0));
    PartyLedger.setText("Party Ledger");
    PartyLedger.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    PartyLedgerActionPerformed(evt);
    PartyLedger.setBounds(20, 140, 200, 30);
    desktopPane.add(PartyLedger, javax.swing.JLayeredPane.DEFAULT_LAYER);
    setJMenuBar(menuBar);
    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addComponent(desktopPane, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
    layout.setVerticalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addComponent(desktopPane, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
    pack();
    }// </editor-fold>
    private void salesTaxInvActionPerformed(java.awt.event.ActionEvent evt) {                                           
    try
    ReportsViewer myiReportViewer = new ReportsViewer("reports/INV.jasper");
    myiReportViewer.setBounds(0, 0, desktopPane.getWidth(), desktopPane.getHeight());
    myiReportViewer.setVisible(true);
    desktopPane.add(myiReportViewer);
    myiReportViewer.setSelected(true);
    catch (PropertyVetoException pve)
    pve.printStackTrace();
    private void supplyRegisterActionPerformed(java.awt.event.ActionEvent evt) {                                              
    try
    ReportsViewer myiReportViewer = new ReportsViewer("reports/supplyRegister.jasper");
    myiReportViewer.setBounds(0, 0, desktopPane.getWidth(), desktopPane.getHeight());
    myiReportViewer.setVisible(true);
    desktopPane.add(myiReportViewer);
    myiReportViewer.setSelected(true);
    catch (PropertyVetoException pve)
    pve.printStackTrace();
    private void PartyLedgerActionPerformed(java.awt.event.ActionEvent evt) {                                           
    try
    ReportsViewer myiReportViewer = new ReportsViewer("reports/CustomerLedger.jasper");
    myiReportViewer.setBounds(0, 0, desktopPane.getWidth(), desktopPane.getHeight());
    myiReportViewer.setVisible(true);
    desktopPane.add(myiReportViewer);
    myiReportViewer.setSelected(true);
    catch (PropertyVetoException pve)
    pve.printStackTrace();
    * @param args the command line arguments
    public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
    new MainUI().setVisible(true);
    // Variables declaration - do not modify
    private javax.swing.JButton PartyLedger;
    private javax.swing.JDesktopPane desktopPane;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JMenuBar menuBar;
    private javax.swing.JButton salesTaxInv;
    private javax.swing.JButton supplyRegister;
    // End of variables declaration
    Best Regards

    Dear Sir,
    I am using the swing code and running the jasper report with the above code.
    Realy!
    I start the thread with this code
    @FXML
    private void mainUiButtonAction(ActionEvent event) {
    try{
    new MainUI().setVisible(true);
    catch(Exception ex){                 
    }

  • Subclass of JPanel invisible in a subclass of JFrame

    I am very, very new to Java GUI, so bear with me:).
    I create a subclass of JFrame and add a menu bar it. That is ok. Then I create a subclass of JPanel and added it to the contentPane of the subclass of the JFrame. But when I run the code, it is not visible, only the frame and the menu bar can be seen. I tried it differently, creating a class for the entire GUI that then creates an instance of JFrame and adds the instance of the said subclass of JPanel and it works fine. I do not see what is the difference. Also, when debugging the first version, I put the break point inside the painComponent of the JPanel subclass and it seems that the program never enters it. Can somebody please tell me why? Is the subclass of JPanel not properly added to the subclass of JFrame?
    Here is the code:
    * PlanITED.java
    * Created on 30 de Maio de 2008, 17:53
    * @author Branka
    package PlanITEDLibraries;
    public class PlanITED extends javax.swing.JFrame {
    /** Creates new form PlanITED */
    public PlanITED() {
    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.
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
    menuBar = new javax.swing.JMenuBar();
    fileMenu = new javax.swing.JMenu();
    loadMapItem = new javax.swing.JMenuItem();
    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    setTitle("PlanITED");
    fileMenu.setText("File");
    fileMenu.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    fileMenuActionPerformed(evt);
    loadMapItem.setText("Load map");
    loadMapItem.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    loadMapItemActionPerformed(evt);
    fileMenu.add(loadMapItem);
    menuBar.add(fileMenu);
    setJMenuBar(menuBar);
    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGap(0, 400, Short.MAX_VALUE)
    layout.setVerticalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGap(0, 279, Short.MAX_VALUE)
    pack();
    }// </editor-fold>//GEN-END:initComponents
    private void fileMenuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fileMenuActionPerformed
    // TODO add your handling code here:
    }//GEN-LAST:event_fileMenuActionPerformed
    private void loadMapItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_loadMapItemActionPerformed
    // TODO add your handling code here:
    }//GEN-LAST:event_loadMapItemActionPerformed
    * @param args the command line arguments
    public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
    PlanITED oPlanITED = new PlanITED();
    oPlanITED.getContentPane().add(new DrawingArea());
    oPlanITED.setVisible(true);
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenu fileMenu;
    private javax.swing.JMenuItem loadMapItem;
    private javax.swing.JMenuBar menuBar;
    // End of variables declaration//GEN-END:variables
    And the code for the class DrawingArea:
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    package PlanITEDLibraries;
    import javax.swing.*;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Color;
    * @author Branka
    public class DrawingArea extends JPanel {
    @Override
    public Dimension getPreferredSize() {
    return new Dimension(500,500);
    @Override
    public void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.drawString("This is my custom Panel!",10,20);
    g.setColor(Color.RED);
    g.fillRect(0, 0, 500, 500);
    Thanks!

    Don't forget to use the [Code Formatting Tags|http://forum.java.sun.com/help.jspa?sec=formatting], so the posted code retains its original formatting.
    Is the subclass of JPanel not properly added to the subclass of JFrame?That would be my guess. I have no idea how GroupLayout works but you didn't set any constraints when you added the panel to the content pane so I would guess that is the problem.
    Don't use the IDE to create your code. Learn how to create GUIs yourself and then you will understand the code. Spend your time learning Java, not learning the IDE.

  • Port Programming Using Netbeans

    Hello everybody,
    I am working on Serial port communication, and I have used Netbeans for GUI designing.
    I am able access the port, but failed to set Event for the same.
    I am getting error like............
    D:\NetBeansProjects\MySerialPort\src\readserialport\MyComport.java:20: readserialport.MyComport is not abstract and does not override abstract method serialEvent(javax.comm.SerialPortEvent) in javax.comm.SerialPortEventListener
    Please help me to resolve this problem...............
    My code:
    * MyComport.java
    * Created on March 18, 2008, 5:43 PM
    package readserialport;
    import java.awt.*;
    import java.io.*;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.comm.*;
    import java.util.*;
    * @author pbagde
    class MyComport extends javax.swing.JFrame
    implements SerialPortEventListener{
    /** How long to wait for the open to finish up. **/
    public static final int TIMEOUTSECONDS = 30;
    /** The chosen Port Identifier **/
    CommPortIdentifier thePortID;
    /** The chosen Port itself **/
    CommPort thePort;
    /** A mapping from names to CommPortIdentifiers. **/
    protected HashMap map = new HashMap();
    /** The name of the choice the user made. **/
    protected String selectedPortName;
    /** The CommPortIdentifier the user chose. **/
    //SerialEvent Mytest;
    //PortChooser MyPort = new PortChooser(null);
    SerialPortEventListener SEvent;
    InputStream inputStream;
    OutputStream outputStream;
    protected CommPortIdentifier selectedPortIdentifier;
    /** Creates new form MyComport */
    public MyComport(){
    initComponents();
    InitializeComponentValues();
    public void InitializeComponentValues(){
    // get list of ports available on this particular computer,
    // by calling static method in CommPortIdentifier.
    Enumeration pList = CommPortIdentifier.getPortIdentifiers();
    // Process the list, putting serial and parallel into ComboBoxes
    while (pList.hasMoreElements()) {
    CommPortIdentifier cpi = (CommPortIdentifier) pList.nextElement();
    System.out.println("Port " + cpi.getName());
    map.put(cpi.getName(), cpi);
    if (cpi.getPortType() == CommPortIdentifier.PORT_SERIAL) {
    comportCMB.addItem(cpi.getName());
    } else if (cpi.getPortType() == CommPortIdentifier.PORT_PARALLEL) {
    //parallelPortsChoice.setEnabled(true);
    //parallelPortsChoice.addItem(cpi.getName());
    } else {
    //other.addItem(cpi.getName());
    public void SerialPortEvent(SerialPortEvent SEvent){
    switch(SEvent.getEventType()){
    case SerialPortEvent.BI:
    case SerialPortEvent.CD:
    case SerialPortEvent.CTS:
    case SerialPortEvent.DSR:
    case SerialPortEvent.FE:
    case SerialPortEvent.OE:
    case SerialPortEvent.PE:
    case SerialPortEvent.RI:
    case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
    break;
    case SerialPortEvent.DATA_AVAILABLE:
    StringBuffer readBuffer = new StringBuffer();
    System.out.println(readBuffer);
    /** 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() {
    jPanel1 = new javax.swing.JPanel();
    jLabel1 = new javax.swing.JLabel();
    comportCMB = new javax.swing.JComboBox();
    jLabel2 = new javax.swing.JLabel();
    baudCMB = new javax.swing.JComboBox();
    jLabel3 = new javax.swing.JLabel();
    databitsCMB = new javax.swing.JComboBox();
    jLabel4 = new javax.swing.JLabel();
    parityCMB = new javax.swing.JComboBox();
    jLabel5 = new javax.swing.JLabel();
    stopbitsCMB = new javax.swing.JComboBox();
    jLabel6 = new javax.swing.JLabel();
    flowconCMB = new javax.swing.JComboBox();
    connectBTN = new javax.swing.JButton();
    disconnectBTN = new javax.swing.JButton();
    jPanel2 = new javax.swing.JPanel();
    jPanel3 = new javax.swing.JPanel();
    jScrollPane1 = new javax.swing.JScrollPane();
    receiveTBX = new javax.swing.JTextArea();
    jPanel4 = new javax.swing.JPanel();
    jScrollPane2 = new javax.swing.JScrollPane();
    sendTBX = new javax.swing.JTextArea();
    sendBTN = new javax.swing.JButton();
    menuBar = new javax.swing.JMenuBar();
    fileMenu = new javax.swing.JMenu();
    openMenuItem = new javax.swing.JMenuItem();
    saveMenuItem = new javax.swing.JMenuItem();
    saveAsMenuItem = new javax.swing.JMenuItem();
    exitMenuItem = new javax.swing.JMenuItem();
    editMenu = new javax.swing.JMenu();
    cutMenuItem = new javax.swing.JMenuItem();
    copyMenuItem = new javax.swing.JMenuItem();
    pasteMenuItem = new javax.swing.JMenuItem();
    deleteMenuItem = new javax.swing.JMenuItem();
    helpMenu = new javax.swing.JMenu();
    contentsMenuItem = new javax.swing.JMenuItem();
    aboutMenuItem = new javax.swing.JMenuItem();
    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    setTitle("Serial Port");
    setMinimumSize(new java.awt.Dimension(552, 351));
    jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Serial Port Configuration", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Verdana", 1, 12)));
    jLabel1.setFont(new java.awt.Font("Verdana", 0, 11));
    jLabel1.setText("Connect Using :");
    comportCMB.setFont(new java.awt.Font("Verdana", 0, 11));
    jLabel2.setFont(new java.awt.Font("Verdana", 0, 11));
    jLabel2.setText("Bits Per Second :");
    baudCMB.setFont(new java.awt.Font("Verdana", 0, 11));
    baudCMB.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "110", "300", "1200", "2400", "4800", "9600", "19200", "38400", "57600", "115200", "230400", "460800", "921600" }));
    jLabel3.setFont(new java.awt.Font("Verdana", 0, 11));
    jLabel3.setText("Data Bits :");
    databitsCMB.setFont(new java.awt.Font("Verdana", 0, 11));
    databitsCMB.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "5", "6", "7", "8" }));
    jLabel4.setFont(new java.awt.Font("Verdana", 0, 11));
    jLabel4.setText("Parity :");
    parityCMB.setFont(new java.awt.Font("Verdana", 0, 11));
    parityCMB.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Even", "Odd", "None", "Mark", "Space" }));
    jLabel5.setFont(new java.awt.Font("Verdana", 0, 11));
    jLabel5.setText("Stop Bits :");
    stopbitsCMB.setFont(new java.awt.Font("Verdana", 0, 11));
    stopbitsCMB.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "1", "1.5", "2" }));
    jLabel6.setFont(new java.awt.Font("Verdana", 0, 11));
    jLabel6.setText("Flow Control :");
    flowconCMB.setFont(new java.awt.Font("Verdana", 0, 11));
    flowconCMB.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Xon/Xoff In", "Xon/Xoff Out", "RTS/CTS In", "RTS/CTS Out", "None" }));
    connectBTN.setFont(new java.awt.Font("Verdana", 0, 11));
    connectBTN.setLabel("Connect");
    connectBTN.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    connectBTNActionPerformed(evt);
    disconnectBTN.setFont(new java.awt.Font("Verdana", 0, 11));
    disconnectBTN.setLabel("Disconnect");
    disconnectBTN.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    disconnectBTNActionPerformed(evt);
    javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
    jPanel1.setLayout(jPanel1Layout);
    jPanel1Layout.setHorizontalGroup(
    jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(jPanel1Layout.createSequentialGroup()
    .addContainerGap()
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addComponent(jLabel1)
    .addComponent(jLabel2)
    .addComponent(jLabel3)
    .addComponent(jLabel4)
    .addComponent(jLabel5)
    .addComponent(jLabel6))
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
    .addComponent(disconnectBTN, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
    .addComponent(flowconCMB, javax.swing.GroupLayout.Alignment.TRAILING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
    .addComponent(stopbitsCMB, javax.swing.GroupLayout.Alignment.TRAILING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
    .addComponent(parityCMB, javax.swing.GroupLayout.Alignment.TRAILING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
    .addComponent(databitsCMB, javax.swing.GroupLayout.Alignment.TRAILING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
    .addComponent(baudCMB, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
    .addComponent(comportCMB, 0, 86, Short.MAX_VALUE)
    .addComponent(connectBTN, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    jPanel1Layout.setVerticalGroup(
    jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(jPanel1Layout.createSequentialGroup()
    .addContainerGap(19, Short.MAX_VALUE)
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
    .addComponent(comportCMB, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addComponent(jLabel1))
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
    .addComponent(baudCMB, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addComponent(jLabel2))
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
    .addComponent(databitsCMB, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addComponent(jLabel3))
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
    .addComponent(parityCMB, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addComponent(jLabel4))
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
    .addComponent(stopbitsCMB, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addComponent(jLabel5))
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
    .addComponent(flowconCMB, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addComponent(jLabel6))
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addComponent(connectBTN)
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addComponent(disconnectBTN))
    jLabel1.getAccessibleContext().setAccessibleName("");
    jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Data Communication", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Verdana", 1, 12)));
    jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Receive Data", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Verdana", 0, 12)));
    receiveTBX.setColumns(20);
    receiveTBX.setRows(5);
    jScrollPane1.setViewportView(receiveTBX);
    javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
    jPanel3.setLayout(jPanel3Layout);
    jPanel3Layout.setHorizontalGroup(
    jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(jPanel3Layout.createSequentialGroup()
    .addContainerGap()
    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 214, Short.MAX_VALUE)
    .addContainerGap())
    jPanel3Layout.setVerticalGroup(
    jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(jPanel3Layout.createSequentialGroup()
    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 63, Short.MAX_VALUE)
    .addContainerGap())
    jPanel4.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Send Data", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Verdana", 0, 12)));
    sendTBX.setColumns(20);
    sendTBX.setRows(5);
    jScrollPane2.setViewportView(sendTBX);
    sendBTN.setLabel("Send");
    javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
    jPanel4.setLayout(jPanel4Layout);
    jPanel4Layout.setHorizontalGroup(
    jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(jPanel4Layout.createSequentialGroup()
    .addContainerGap()
    .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 214, Short.MAX_VALUE)
    .addComponent(sendBTN, javax.swing.GroupLayout.Alignment.TRAILING))
    .addContainerGap())
    jPanel4Layout.setVerticalGroup(
    jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(jPanel4Layout.createSequentialGroup()
    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addComponent(sendBTN))
    javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
    jPanel2.setLayout(jPanel2Layout);
    jPanel2Layout.setHorizontalGroup(
    jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(jPanel2Layout.createSequentialGroup()
    .addContainerGap()
    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addComponent(jPanel3, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
    .addComponent(jPanel4, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    .addContainerGap())
    jPanel2Layout.setVerticalGroup(
    jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
    .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
    .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
    fileMenu.setText("File");
    openMenuItem.setText("Open");
    fileMenu.add(openMenuItem);
    saveMenuItem.setText("Save");
    fileMenu.add(saveMenuItem);
    saveAsMenuItem.setText("Save As ...");
    fileMenu.add(saveAsMenuItem);
    exitMenuItem.setText("Exit");
    exitMenuItem.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    exitMenuItemActionPerformed(evt);
    fileMenu.add(exitMenuItem);
    menuBar.add(fileMenu);
    editMenu.setText("Edit");
    cutMenuItem.setText("Cut");
    editMenu.add(cutMenuItem);
    copyMenuItem.setText("Copy");
    editMenu.add(copyMenuItem);
    pasteMenuItem.setText("Paste");
    editMenu.add(pasteMenuItem);
    deleteMenuItem.setText("Delete");
    editMenu.add(deleteMenuItem);
    menuBar.add(editMenu);
    helpMenu.setText("Help");
    contentsMenuItem.setText("Contents");
    helpMenu.add(contentsMenuItem);
    aboutMenuItem.setText("About");
    helpMenu.add(aboutMenuItem);
    menuBar.add(helpMenu);
    setJMenuBar(menuBar);
    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
    .addContainerGap()
    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
    .addGap(18, 18, 18)
    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addContainerGap())
    layout.setVerticalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addContainerGap()
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
    .addComponent(jPanel2, javax.swing.GroupLayout.Alignment.LEADING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
    .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    pack();
    }// </editor-fold>
    private void exitMenuItemActionPerformed(java.awt.event.ActionEvent evt) {                                            
    System.exit(0);
    private void connectBTNActionPerformed(java.awt.event.ActionEvent evt) {                                          
    // TODO add your handling code here:
    // Get the CommPortIdentifier.
    thePortID = getSelectedIdentifier();
    System.out.println("Trying to open " + thePortID.getName() + "...");
    try{
    thePort = thePortID.open("DarwinSys DataComm", TIMEOUTSECONDS * 1000);
    SerialPort myPort = (SerialPort) thePort;
    SEvent = (SerialPortEventListener) thePort;
    //SEvent.serialEvent();
    myPort.setSerialPortParams(getBaud(), getDataBits(), getStopBits(), getParity());
    myPort.getFlowControlMode();
    myPort.notifyOnDataAvailable(true);
    myPort.addEventListener(this);
    inputStream = myPort.getInputStream();
    } catch (TooManyListenersException ex) {
    Logger.getLogger(MyComport.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
    Logger.getLogger(MyComport.class.getName()).log(Level.SEVERE, null, ex);
    } catch (UnsupportedCommOperationException ex) {
    Logger.getLogger(MyComport.class.getName()).log(Level.SEVERE, null, ex);
    } catch (PortInUseException ex) {
    Logger.getLogger(MyComport.class.getName()).log(Level.SEVERE, null, ex);
    } //catch(TooManyListenersException e) {}
    System.out.println("Trying to open with BAUD " + getBaud());
    System.out.println("Trying to open with DataBits " + getDataBits());
    System.out.println("Trying to open with Parity " + getParity());
    System.out.println("Trying to open with StopBits " + getStopBits());
    System.out.println("Trying to open with FlowControl " + getFlowControlMode());
    /* The public "getter" to retrieve the selection by CommPortIdentifier. */
    public CommPortIdentifier getSelectedIdentifier() {
    selectedPortName = (String) comportCMB.getSelectedItem();
    // Get the given CommPortIdentifier
    selectedPortIdentifier = (CommPortIdentifier)map.get(selectedPortName);
    return selectedPortIdentifier;
    private void disconnectBTNActionPerformed(java.awt.event.ActionEvent evt) {                                             
    // TODO add your handling code here:
    thePortID = getSelectedIdentifier();
    thePort.close();
    System.out.println("Closed " + thePortID.getName() + "...");
    public int getBaud(){
    int baud;
    baud = Integer.parseInt((String) baudCMB.getSelectedItem()) ;
    return baud;
    public int getDataBits(){
    int databits;
    databits = Integer.parseInt((String) databitsCMB.getSelectedItem());
    return databits;
    public int getParity(){
    String parity;
    parity = (String) parityCMB.getSelectedItem();
    if(parity.equals("Even"))
    return SerialPort.PARITY_EVEN;
    else if(parity.equals("Odd"))
    return SerialPort.PARITY_ODD;
    else if(parity.equals("Mark"))
    return SerialPort.PARITY_MARK;
    else if (parity.equals("Space"))
    return SerialPort.PARITY_SPACE;
    else
    return SerialPort.PARITY_NONE;
    public int getStopBits(){
    String stopbits;
    stopbits = (String) stopbitsCMB.getSelectedItem();
    if(stopbits.equals("1"))
    return SerialPort.STOPBITS_1;
    else if(stopbits.equals("1.5"))
    return SerialPort.STOPBITS_1_5;
    else
    return SerialPort.STOPBITS_2;
    public int getFlowControlMode(){
    String flowcontrol;
    flowcontrol = (String)flowconCMB.getSelectedItem();
    if(flowcontrol.equals("Xon/Xoff In"))
    return SerialPort.FLOWCONTROL_XONXOFF_IN;
    else if(flowcontrol.equals("Xon/Xoff Out"))
    return SerialPort.FLOWCONTROL_XONXOFF_OUT;
    else if(flowcontrol.equals("RTS/CTS In"))
    return SerialPort.FLOWCONTROL_RTSCTS_IN;
    else if(flowcontrol.equals("RTS/CTS Out"))
    return SerialPort.FLOWCONTROL_RTSCTS_OUT;
    else
    return SerialPort.FLOWCONTROL_NONE;
    * @param args the command line arguments
    public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
    new MyComport().setVisible(true);
    // Variables declaration - do not modify
    private javax.swing.JMenuItem aboutMenuItem;
    private javax.swing.JComboBox baudCMB;
    public javax.swing.JComboBox comportCMB;
    private javax.swing.JButton connectBTN;
    private javax.swing.JMenuItem contentsMenuItem;
    private javax.swing.JMenuItem copyMenuItem;
    private javax.swing.JMenuItem cutMenuItem;
    private javax.swing.JComboBox databitsCMB;
    private javax.swing.JMenuItem deleteMenuItem;
    private javax.swing.JButton disconnectBTN;
    private javax.swing.JMenu editMenu;
    private javax.swing.JMenuItem exitMenuItem;
    private javax.swing.JMenu fileMenu;
    private javax.swing.JComboBox flowconCMB;
    private javax.swing.JMenu helpMenu;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JMenuBar menuBar;
    private javax.swing.JMenuItem openMenuItem;
    private javax.swing.JComboBox parityCMB;
    private javax.swing.JMenuItem pasteMenuItem;
    private javax.swing.JTextArea receiveTBX;
    private javax.swing.JMenuItem saveAsMenuItem;
    private javax.swing.JMenuItem saveMenuItem;
    private javax.swing.JButton sendBTN;
    private javax.swing.JTextArea sendTBX;
    private javax.swing.JComboBox stopbitsCMB;
    // End of variables declaration
    }

    Thank you, for your kind reply......
    I tried for plain java coding, it is worling fine.
    It is receiving data on events from my harware.
    But problem while I implement SerialPorteventHandler.
    I am working on Netbeans 6.0.1
    MyCODE : -------
    class MyComport extends javax.swing.JFrame implements SerialPortEventListener{
              // My CODE
    }This give error like.....
    readserialport.MyComport is not abstract and does not override abstract method serialEvent(javax.comm.SerialPortEvent) in javax.comm.SerialPortEventListener
    If I remove this SerialPortEventListener then it doesn't allow me to add event listener.....
    myport.addeventlistner(this);I tried to solve this problem other way, but failed...
    Please help me to sola this problem....

  • Trouble with my dropdown menu

    I'm new to Java and I am getting pretty frustrated. I need a drop-down menu in my calculator and I'm probably doing this all wrong.
    When I compile my code, I don't get any errors but when I run it, I get:
    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at mortgagePaymentAmount.mortgagePaymentAmount(mortgagePaymentAmount.java:50)
    at mortgagePaymentAmount.<init>(mortgagePaymentAmount.java:27)
    at mortgagePaymentAmount$4.run(mortgagePaymentAmount.java:243)
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:598)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:300)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:210)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:200)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:195)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:187)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:121)
    Here is my code. Can someone please help me out? Thank you.
    import java.lang.*;
    import java.text.DecimalFormat;
    import javax.swing.*;   
    public class mortgagePaymentAmount extends javax.swing.JFrame
      public mortgagePaymentAmount()
      mortgagePaymentAmount();
      private void mortgagePaymentAmount()
      /*From http://java.sun.com/docs/books/tutorial/uiswing/learn/index.html*/
      /*Fields for user to input data and labels on the side of the fields*/
      //Amount of mortgage
      loanAmountTextField = new javax.swing.JTextField();
      loanAmountLabel = new javax.swing.JLabel();
      //Term of mortgage
      monthsTextField = new javax.swing.JTextField();
      monthsLabel = new javax.swing.JLabel();
      //Interest rate
      interestTextField = new javax.swing.JTextField();
      interestLabel = new javax.swing.JLabel();
      menuBar = new javax.swing.JMenuBar();
      frame.setJMenuBar(menuBar);
      menu = new javax.swing.JMenu("Menu Label");
      item1 = new javax.swing.JMenuItem("Item Label 1");
      item2 = new javax.swing.JMenuItem("Item Label 2");  
      //Calculate
      calcButton = new javax.swing.JButton();
      calcButton.setText("Calculate");
      calcButton.addActionListener(new java.awt.event.ActionListener()
        public void actionPerformed(java.awt.event.ActionEvent evt)
        { calcButtonActionPerformed(evt); }
      //Reset
      resetButton = new javax.swing.JButton();
      resetButton.setText("Reset form");
      resetButton.addActionListener(new java.awt.event.ActionListener()
        public void actionPerformed(java.awt.event.ActionEvent evt)
        { resetButtonActionPerformed(evt); }
      //Quit
      quitButton = new javax.swing.JButton();
      quitButton.setText("Quit");
      quitButton.addActionListener(new java.awt.event.ActionListener()
        public void actionPerformed(java.awt.event.ActionEvent evt)
        { quitButtonActionPerformed(evt); }
      //Monthly payment amount display
      monthlyPaymentLabel = new javax.swing.JLabel();
      setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
      //Title
      setTitle("Mortgage Calculator v2.3");
      //Labels for each field
      loanAmountLabel.setText("Amount of Mortgage (no commas)");
      monthsLabel.setText("Term of Mortgage (in years)");
      interestLabel.setText("% interest rate");
      monthlyPaymentLabel.setText("Monthly payment amount");
      //Layout of buttons using
      //http://java.sun.com/docs/books/tutorial/uiswing/examples/learn/CelsiusConverterProject/src/learn/CelsiusConverterGUI.java
      //as my template
      javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
      getContentPane().setLayout(layout);
      layout.setHorizontalGroup(  //Horizontal positioning
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
          .addContainerGap()
          .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            //Loan amount field and label position
            .addGroup(layout.createSequentialGroup()
              .addComponent(loanAmountTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
              .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
              .addComponent(loanAmountLabel))
             //Months field and label position
            .addGroup(layout.createSequentialGroup()
              .addComponent(monthsTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
              .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
              .addComponent(monthsLabel))
            //Interest field and label position 
            .addGroup(layout.createSequentialGroup()
              .addComponent(interestTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
              .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
              .addComponent(interestLabel))
            //Menu bar
            .addGroup(layout.createSequentialGroup()
              .addComponent(menuBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
              .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
              .addComponent(menuBar))
            //Calculate button           
            .addGroup(layout.createSequentialGroup()
              .addComponent(calcButton)
              .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
              .addComponent(monthlyPaymentLabel))
            //Reset button           
            .addGroup(layout.createSequentialGroup()
              .addComponent(resetButton)
              .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
              .addComponent(monthlyPaymentLabel))
            //Quit button           
            .addGroup(layout.createSequentialGroup()
              .addComponent(quitButton)
              .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
              .addComponent(monthlyPaymentLabel)))
          .addContainerGap(30, Short.MAX_VALUE)) //length
      layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {item2, item1, menu, menuBar, resetButton, quitButton, calcButton, loanAmountTextField, monthsTextField, interestTextField});   
      layout.setVerticalGroup( //Vertical positioning
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
          .addContainerGap()
          //Loan amount field and label position
          .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
            .addComponent(loanAmountTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addComponent(loanAmountLabel))
          //Months field and label position         
          .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
            .addComponent(monthsTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addComponent(monthsLabel))
          //Interest field and label position 
          .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
            .addComponent(interestTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addComponent(interestLabel))
          //Menu bar
          .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
            .addComponent(menuBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addComponent(menuBar))
          //Calculate button           
          .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
          .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
            .addComponent(calcButton)
            .addComponent(monthlyPaymentLabel))
          //Reset button
          .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
          .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
            .addComponent(resetButton))
          //Quit button
          .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
          .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
            .addComponent(quitButton))
        .addContainerGap(20, Short.MAX_VALUE)) //height
        pack(); 
      //Calculation action
      private void calcButtonActionPerformed(java.awt.event.ActionEvent evt)
      DecimalFormat df = new DecimalFormat("0.##");  //DecimalFormat derived from http://forum.java.sun.com/ to make no more than two decimal places.
      //My calcuations
      double months = ((Double.parseDouble(monthsTextField.getText())) * 12); //months calculated into years
      double loanAmount = (Double.parseDouble(loanAmountTextField.getText()) );
      double interest = ((Double.parseDouble(interestTextField.getText())) / 100); //interest decimal calculated into percentage
      double monthlyAmount = (loanAmount * (interest/12.0))/(1 - 1 /Math.pow((1 + interest/12.0), months));
      monthlyPaymentLabel.setText(df.format(monthlyAmount) + " Monthly payment amount");  //output
      //Reset action
      private void resetButtonActionPerformed(java.awt.event.ActionEvent evt)
      new mortgagePaymentAmount().setVisible(true);
      //Quit action
      private void quitButtonActionPerformed(java.awt.event.ActionEvent evt)
      System.exit(0);
      //Run the program
      public static void main(String args[])
      java.awt.EventQueue.invokeLater(new Runnable()
        public void run()
          new mortgagePaymentAmount().setVisible(true);
        //variables
        private javax.swing.JLabel loanAmountLabel;
        private javax.swing.JLabel monthsLabel;
        private javax.swing.JLabel interestLabel;
        private javax.swing.JFrame frame;
        private javax.swing.JMenuBar menuBar;
        private javax.swing.JMenu menu;
        private javax.swing.JMenuItem item1;
        private javax.swing.JMenuItem item2;
        private javax.swing.JButton calcButton;
        private javax.swing.JLabel monthlyPaymentLabel;
        private javax.swing.JTextField loanAmountTextField;
        private javax.swing.JTextField monthsTextField;
        private javax.swing.JTextField interestTextField;
        private javax.swing.JButton quitButton;
        private javax.swing.JButton resetButton;
    }

    Don't be scared of actually reading these stacktraces - a lot of the time they give you all you need to solve your problem. This one tells you that there's a NullPointerException at line 50 of your class - you're trying to do something to, or call a method on, something that doesn't exist.

  • How to make a Multiple-rows Swing menubar?

    Hello!
    I'd like to le JMenubar to show multi-rows automatically in JFrame or JApplet if one row can not show all menus.
    Does anyone know how to do it? (I've asked several times these days but seems no one knows answer)
    Thank you very much.

    If your design requires that many menubar items that it can't be displayed on a normal window, then perhaps you should reconsider your design. If you really think it is your only option than you can try changing the layout of the menubar.JMenuBar mb = new JMenuBar();
    mb.setLayout(new GridLayout(5, 2));

  • URGENT:problem with memory using swing component

    We use Java SDK 1.4.0-b92 on a Sun Blade Machine with Solaris 8 Operating System.
    We developed a software with a GUI (JFame, JInternalFrame) which have to be refreshed in precise moments and any time we do it there is a big loss of memory(not the Java Virtual Machine Memory but the system memory, see it with the command "vmstat"). It seems that memory isn't released even if we close one or more of the JInternalFrame/JFrame.
    This is a part of our example code which refresh some JTextArea every ten seconds,with the content of a text File called "text.txt" :
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.border.*;
    import java.util.*;
    public class MainFrame extends JFrame {
    static JDesktopPane desktop = new JDesktopPane();
    JMenuBar menuBar = new JMenuBar();
    JMenu menu = new JMenu();
    JMenuItem aggiungi = new JMenuItem();
    int openFrameCount = 0;
    public MainFrame (){
    try{
    desktop.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
    desktop.setBorder(BorderFactory.createLoweredBevelBorder());
    this.setContentPane(desktop);
    Dimension screenSize= Toolkit.getDefaultToolkit().getScreenSize();
    this.setBounds(0, 0, screenSize.width, screenSize.height);
    this.setTitle("Main Frame Prova");
    this.setLocation(0,0);
    this.setVisible(true);
    menu.setText("apri frame");
    aggiungi.setText("Apri");
    aggiungi.addActionListener(new ActionListener () {
    public void actionPerformed(ActionEvent e){
    createFrame();
    menu.add(aggiungi);
    menuBar.add(menu);
    this.setJMenuBar(menuBar);
    catch (Exception e) {e.printStackTrace();}
    private void createFrame (){
    try{
    NsJInternalFrame frame = new NsJInternalFrame("Frame Interno", true, true, true, true);
    openFrameCount++;
    System.out.println("Frame aperti: "+openFrameCount);
    frame.setVisible(true);
    desktop.add(frame);
    frame.setSelected(true);
    frame.setPreferredSize(new Dimension(400,500));
    frame.setSize(new Dimension(400,500));
    finalize();
    catch (Exception e) {e.printStackTrace();}
    catch (Throwable t) {t.printStackTrace();}
    protected void processWindowEvent (WindowEvent e){
    try{
    super.processWindowEvent(e);
    if (e.getID()== WindowEvent.WINDOW_CLOSING) {
    finalize();
    System.exit(0);
    catch (Exception ex) {ex.printStackTrace();}
    catch (Throwable t) {t.printStackTrace();}
    public static void main (String argv[]){
    try {
    UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
    MainFrame mf = new MainFrame();
    while (true){
    Thread.sleep(10000);
    aggiornaTesto();
    Runtime run = Runtime.getRuntime();
    System.out.println("***********************************************************");
    System.out.println("* Memoria Totale "+run.totalMemory()/1000+" *");
    System.out.println("* Memoria Massima occupabile "+run.maxMemory()/1000+" *");
    System.out.println("* *");
    System.out.println("* --------------------------------------------------------- *");
    System.out.println("* *");
    System.out.println("* Memoria Libera "+run.freeMemory()/1000+" *");
    System.out.println("* *");
    System.out.println("***********************************************************");
    System.runFinalization();
    System.gc();
    catch (Exception e) {e.printStackTrace();}
    private static void aggiornaTesto(){
    JInternalFrame[] frameAperti = desktop.getAllFrames();
    for (int i=0; i<frameAperti.length; i++)
    ((NsJInternalFrame)frameAperti).inizializeText();
    System.out.println("----- "+new Date()+" / Aggiornato testo------");
    System.runFinalization();
    System.gc();
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.border.*;
    import java.io.*;
    public class NsJInternalFrame extends JInternalFrame {
    JTextArea textArea=new JTextArea();
    public NsJInternalFrame (String title, boolean resizable, boolean closeable, boolean maximizable, boolean iconifiable){
    super (title, resizable, closeable, maximizable, iconifiable);
    disableEvents (AWTEvent.WINDOW_EVENT_MASK);
    JScrollPane scroll;
    scroll=new JScrollPane(textArea);
    this.setContentPane(scroll);
    this.setDefaultCloseOperation(JInternalFrame.DISPOSE_ON_CLOSE);
    inizializeText();
    public void inizializeText(){
    try{
    RandomAccessFile raf = new RandomAccessFile("text.txt", "r");
    String text = new String(), line = new String();
    while (true) {
    line = raf.readLine();
    if (line==null) break;
    text= text+line;
    textArea.setText(text);
    finalize();
    raf.close();
    catch (Exception e) {e.printStackTrace();}
    catch (Throwable t) {t.printStackTrace();}
    public void dispose (){
    try{
    finalize();
    super.dispose();
    catch (Exception e) {e.printStackTrace();}
    catch (Throwable t) {t.printStackTrace();}
    text.txt
    HELLO HELLO HELLO
    Help Us Please!!
    [email protected]
    [email protected]

    Yes I'm still following the thread.
    Like i said i only have ovi maps running with PhoNetInfo and even today i tested it again. I managed by changing some settings to get 50MB of free RAM when the phone is idle.
    I changed the amount of allowed RAM to be used by ovi maps to the minimum (10%). This time i had 40MB of free ram before calculating the root (again more or less 600km) without tolls and the fastest root. i continued with PhoNetInfo on and following the value of free RAM and they kept falling till i get again the low memory error.
    I tried then a "solution" that i got from nokia that stated to change the configuration of the internet to online, and it worked perfectly. But i don't think this is a solution since i can't have my phone always connected to the internet. I don't know is where i can suggest that nokia try to solve this problem but already sent an email to the client support stating this.
    I don't think i can install a later version of ovimaps since it comes pre-installed on the phone and i don't see where i can uninstall it and where to find the earlier versions.
    But thanks for the reply,

  • Swing and jmf

    can u please have a look to the attached file
    i know that this involves the jmf API but I have the feeling that has to do more with swing, thats whay I post my question here
    this simple application is based on the MDI.java example of the jmf web
    pages
    I also added a slider and want to set the playback rate for the player from
    there if possible
    that is I want everytime that I move the slider and the value is biggerthan
    50 the rate to be reduced according to a simple calculation that converts
    the slider value to a value between 0 an1 for the rate...
    so all i want to do is pass the slider value to the player everytime that
    the slider changes value and this is bigger than 50
    the attached file can do that only when the player starts playing the
    file,,,,
    after the player has started and the rate is set I cant change it even if
    the slider moves
    when I tried to do that from within the stateChanged method of the slider I
    was getting a Nullpointer exception because of the EventDispatching thread,
    so I thought to take this piece of code out of there (create the setnewrate
    method in the jmframe instead),,,,but then of course doesnt work like I
    would want,,,,,
    do I have to register the class that implements the frame for the player as
    a ChangeListener on the slider to achieve that, is something like that
    possible....
    I know that swing is not supposed to be thread safe, so maybe this is what
    the problem is after all...any suggestions to that direction?
    Can u please have a look??
    I am a beginner so any help would really be very much appreciated
    thanx :)
    maria
    .....and the attached file
    I think the problem is with the stateChanged method for the Jslider...
    I am getting a null pointerexception because of the eventdispatching thread
    pls ignore any silly mistakes I am a completely newbie in java
    myAppfr2.java
    import javax.media.*;
    import com.sun.media.ui.*;
    import javax.media.protocol.*;
    import javax.media.protocol.DataSource;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.net.*;
    import java.io.*;
    import java.util.Vector;
    import javax.swing.border.Border.*;
    import java.util.Hashtable;
    public class myAppfr2 extends Frame {
    * VARIABLES
    JMFrame jmframe = null;
    JDesktopPane desktop;
    FileDialog fd = null;
    CheckboxMenuItem cbAutoLoop = null;
    Player player ;
    //Player newPlayer = null;
    String filename;
    boolean stopped;
    public my_slider test_slider;//put it here so I can use it by name by all code
    float rate;
    * MAIN PROGRAM / STATIC METHODS
    public static void main(String args[]) {
    //if (args.length > 0)
         //rate=Float.parseFloat(args[0]);
    myAppfr2 mdi = new myAppfr2();
    static void Fatal(String s) {
    MessageBox mb = new MessageBox("JMF Error", s);
    * METHODS
    public myAppfr2() {
    super("VHE Demo");
    // Add the desktop pane
    setLayout( new BorderLayout() );
    desktop = new JDesktopPane();
    desktop.setDoubleBuffered(true);
         desktop.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);//makes dragging faster
    add("Center", desktop);
    setMenuBar(createMenuBar());
    setSize(640, 480);
    setVisible(true);
         test_slider = new my_slider("networkutil");
         createnetworkutil();
         try {
         UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel") ;
    } catch (Exception e) {
    System.err.println("Could not initialize personal look and feel");
    addWindowListener( new WindowAdapter() {
    public void windowClosing(WindowEvent we) {
    System.exit(0);
    Manager.setHint(Manager.LIGHTWEIGHT_RENDERER, new Boolean(true));
    private MenuBar createMenuBar() {
    ActionListener al = new ActionListener() {
    public void actionPerformed(ActionEvent ae) {
    String command = ae.getActionCommand();
    if (command.equals("Open")) {
    if (fd == null) {
    fd = new FileDialog(myAppfr2.this, "Open File",
    FileDialog.LOAD);
    fd.setDirectory("~/movies");
    fd.show();
    if (fd.getFile() != null) {
    String filename = fd.getDirectory() + fd.getFile();
    openFile("file:" + filename);
    } else if (command.equals("Exit")) {
    dispose();
    System.exit(0);
    MenuItem item;
    MenuBar mb = new MenuBar();
    // File Menu
    Menu mnFile = new Menu("File");
    mnFile.add(item = new MenuItem("Open"));
    item.addActionListener(al);
    mnFile.add(item = new MenuItem("Exit"));
    item.addActionListener(al);
    // Options Menu
    Menu mnOptions = new Menu("Options");
    cbAutoLoop = new CheckboxMenuItem("Auto replay");
    cbAutoLoop.setState(true);
    mnOptions.add(cbAutoLoop);
    mb.add(mnFile);
    mb.add(mnOptions);
    return mb;
    //create slider and add it to desktop
    public void createnetworkutil(){
    test_slider.pack();
    desktop.add(test_slider);
    test_slider.setVisible(true);
    * Open a media file.
    private void openFile(String filename) {
    String mediaFile = filename;
    Player player = null;
    // URL for our media file
    URL url = null;
    try {
    // Create an url from the file name and the url to the
    // document containing this applet.
    if ((url = new URL(mediaFile)) == null) {
    Fatal("Can't build URL for " + mediaFile);
    return;
    // Create an instance of a player for this media
    try {
    player = Manager.createPlayer(url);
    } catch (NoPlayerException e) {
    Fatal("Error: " + e);
    } catch (MalformedURLException e) {
    Fatal("Error:" + e);
    } catch (IOException e) {
    Fatal("Error:" + e);
    if (player != null) {
    this.filename = filename;
    JMFrame jmframe = new JMFrame(player, filename);
    desktop.add(jmframe);
    class JMFrame extends JInternalFrame implements ControllerListener {
    public Player mplayer;
    Component visual = null;
    Component control = null;
    int videoWidth = 0;
    int videoHeight = 0;
    int controlHeight = 30;
    int insetWidth = 10;
    int insetHeight = 30;
    // boolean firstTime = true;
    public JMFrame(Player player, String title) {
    super(title, true, true, true, true);
    getContentPane().setLayout( new BorderLayout() );
    //setSize(320, 10);
    setLocation(200, 25);
    setVisible(true);
    mplayer = player;
    mplayer.addControllerListener((ControllerListener) this);
    mplayer.realize();
    addInternalFrameListener( new InternalFrameAdapter() {
    public void internalFrameClosing(InternalFrameEvent ife) {
    mplayer.close();
    public void controllerUpdate(ControllerEvent ce) {
    // System.out.println("controllerUpdate");
    //SwingUtilities.isEventDispatchThread();
    if (ce instanceof RealizeCompleteEvent) {
    mplayer.prefetch();
    } else if (ce instanceof PrefetchCompleteEvent) {
    if (visual != null)
    return;
         //setnewrate();
         //rate=mplayer.getRate();
         System.out.println( mplayer.getRate());
    if ((visual = mplayer.getVisualComponent()) != null) {
    Dimension size = visual.getPreferredSize();
    videoWidth = size.width;
    videoHeight = size.height;
    getContentPane().add("Center", visual);
    } else
    videoWidth = 320;
    /*if ((control = mplayer.getControlPanelComponent()) != null) {
    controlHeight = control.getPreferredSize().height;
    getContentPane().add("South", control);
    setSize(videoWidth + insetWidth,
    videoHeight + controlHeight + insetHeight);
    validate();
    mplayer.start();
    } else if (ce instanceof StartEvent){
         if (test_slider.netutil==0) {
         mplayer.stop();
         } else if (ce instanceof EndOfMediaEvent && cbAutoLoop.getState()) {
    mplayer.setMediaTime(new Time(0));
              boolean stopped=true;
              mplayer.prefetch();
              mplayer.start();
              stopped=false;
    class my_slider extends JInternalFrame implements ChangeListener{
    //Set up parameters.
    int netini=50;
    public int netutil=netini;
    public my_slider(String windowTitle) {
    super(windowTitle, false, false, false, false);
    getContentPane().setLayout(new BorderLayout());
    setLocation(25,25);// for the internal frame that contains the slider
    setVisible(true); //..same
    //Create the slider(the component included in "my_slider" internal frame
         JSlider mslider = new JSlider(JSlider.VERTICAL,
    0, 100, netini);
    mslider.addChangeListener((ChangeListener) this);
    mslider.setMajorTickSpacing(10);
    mslider.setPaintTicks(true);
    //Create the label table.
    Hashtable labelTable = new Hashtable();
    labelTable.put(new Integer( 0 ),
    new JLabel("0%") );
    labelTable.put(new Integer( 25 ),
    new JLabel("25%") );
    labelTable.put(new Integer( 50 ),
    new JLabel("50%") );
    labelTable.put(new Integer(75),
    new JLabel("75%") );
         labelTable.put(new Integer( 100),
    new JLabel("100%") );     
    mslider.setLabelTable(labelTable);
    mslider.setPaintLabels(true);
    mslider.setBorder(
    BorderFactory.createEmptyBorder(0,0,0,10));
         //Put everything in the content pane.
    getContentPane().add(mslider, BorderLayout.CENTER);
    public void stateChanged(ChangeEvent e) { //System.out.println("stateChanged");
    // SwingUtilities.isEventDispatchThread();
    if (e instanceof ChangeEvent){
    JSlider source = (JSlider)e.getSource();
    if (!source.getValueIsAdjusting()) {
    netutil= (int)source.getValue();
         System.out.println(netutil);
              if (jmframe.mplayer!=null) {
         jmframe.mplayer.setRate((float)(netutil/(netutil+(0.3*netutil))));
              if (jmframe.mplayer.getTargetState() <Player.Started)
         jmframe.mplayer.prefetch();
    i am stuck so any help would be really very much appreciated

    did you ever resolve this.
    I may be having similar problems
    I have an JMF application running under webstart. It runs ok in Java 1.3
    Now I am trying to get ti to run under Java 1.4. The attached error is rather useless,
    but by guess at what is happening is that the JMF control has some .awt. stuff included
    but that Java 1.4 emulates .awt. in swing. But something was not set and the default does not
    work.
    This error messages does not appear in the 1.3 run
    Any suggestions would be greatly appriatated.
    1.4 result:
    mg version 2.1.1a
    player created com.sun.media.content.unknown.Handler@3a1834
    ctr com.sun.media.PlaybackEngine$BitRateA@4a9a7d
    ctr com.sun.media.BasicJMD[panel0,0,0,512x200,invalid,layout=java.awt.BorderLayout]
    duration? javax.media.Time@6b5666 sec = 9.223372036854776E9
    time unknown javax.media.Time@754699
    will realize the player
    realize
    javax.media.TransitionEvent[source=com.sun.media.content.unknown.
    Handler@3a1834,previous=Unrealized,current=Realizing,
    target=Realized]
    start smxBADS
    bass start
    Exception occurred during event dispatching:
    java.lang.NullPointerException
    at javax.swing.plaf.metal.MetalLookAndFeel.getControlInfo(Unknown Source)
    at javax.swing.plaf.metal.MetalScrollButton.paint(Unknown Source)
    at javax.swing.JComponent.paintChildren(Unknown Source)
    at javax.swing.JComponent.paint(Unknown Source)
    at javax.swing.JComponent.paintWithBuffer(Unknown Source)
    at javax.swing.JComponent._paintImmediately(Unknown Source)
    at javax.swing.JComponent.paintImmediately(Unknown Source)
    at javax.swing.RepaintManager.paintDirtyRegions(Unknown Source)
    at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(Unknown Source)
    at java.awt.event.InvocationEvent.dispatch(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)
    Exception occurred during event dispatching:
    java.lang.NullPointerException
    at javax.swing.plaf.metal.MetalLookAndFeel.getControlInfo(Unknown Source)
    at javax.swing.plaf.metal.MetalScrollButton.paint(Unknown Source)
    at javax.swing.JComponent.paintChildren(Unknown Source)
    at javax.swing.JComponent.paint(Unknown Source)
    at javax.swing.JComponent.paintWithBuffer(Unknown Source)
    at javax.swing.JComponent._paintImmediately(Unknown Source)
    at javax.swing.JComponent.paintImmediately(Unknown Source)
    at javax.swing.RepaintManager.paintDirtyRegions(Unknown Source)
    at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(Unknown Source)
    at java.awt.event.InvocationEvent.dispatch(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)
    realize done
    panel found java.awt.Panel[panel1,0,0,0x0,invalid] java.awt.Panel[panel2,4,216,292x30,layout=java.awt.FlowLayout]
    press a button
    Exception occurred during event dispatching:
    java.lang.NullPointerException
    at javax.swing.plaf.metal.MetalLookAndFeel.getControlInfo(Unknown Source)
    at javax.swing.plaf.metal.MetalScrollButton.paint(Unknown Source)
    at javax.swing.JComponent.paintChildren(Unknown Source)
    at javax.swing.JComponent.paint(Unknown Source)
    at javax.swing.JComponent.paintWithBuffer(Unknown Source)
    at javax.swing.JComponent._paintImmediately(Unknown Source)
    at javax.swing.JComponent.paintImmediately(Unknown Source)
    at javax.swing.RepaintManager.paintDirtyRegions(Unknown Source)
    at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(Unknown Source)
    at java.awt.event.InvocationEvent.dispatch(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)
    Exception occurred during event dispatching:
    java.lang.NullPointerException
    1.3 result
    mg version 2.1.1a
    player created com.sun.media.content.unknown.Handler@354749
    ctr com.sun.media.PlaybackEngine$BitRateA@5b484d
    ctr com.sun.media.BasicJMD[panel3,0,0,512x200,invalid,layout=java.awt.BorderLayout]
    duration? javax.media.Time@46d228 sec = 9.223372036854776E9
    time unknown javax.media.Time@f7386
    will realize the player
    realize
    javax.media.TransitionEvent[source=com.sun.media.content.unknown.
    Handler@354749,previous=Unrealized,current=Realizing,
    target=Realized]
    start smxBADS
    bass start
    javax.media.DurationUpdateEvent[source=com.sun.media.content.unknown.Handler@354749,duration=javax.media.Time@55c0f9
    javax.media.Time@55c0f9
    javax.media.RealizeCompleteEvent[source=com.sun.media.content.unknown.Handler@354749,previous=Realizing,current=Realized,target=Realized]
    realized complete
    prefetch
    realize done
    controlComp com.sun.media.ui.DefaultControlPanel[,0,0,74x21,invalid,layout=java.awt.BorderLayout]
    add controlComp 21 java.awt.Panel[panel4,10,-12,258x47,invalid]
    javax.media.TransitionEvent[source=com.sun.media.content.unknown.Handler@354749,previous=Realized,current=Prefetching,target=Prefetched]
    start smxBADS
    bass start
    running ok from here on

  • JAWS does not always read  Swing menus

    I have come across a problem that involves JAWS 4.51 and Java menus in Internet Explorer.
    I have a Java application that has a JMenuBar. The menu bar contains several JMenus that in turn contain several JMenuItems.
    When navigating through a menu, JAWS reads every JMenuItem. However, once a disabled JMenuItem is reached, JAWS no longer reads the JMenuItems below the disabled one in the open JMenu.
    The problem occurs only in Internet Explorer on "plain" menu items that follow a disabled menu item. The problem does not affect "complex" menu items, such as those that open sub menus.
    I can only reproduce this problem in Internet Explorer 6. Netscape Communicator 7, Web Start clients and a command line launch do not suffer from this problem. Also, JAWS 4.02 is fine as well; only 4.51 has this problem.
    Attached at the end is a sample application that recreates the issue. You'll notice in the sample application that JAWS will not read "A check box menu item" and "Another one" while it will read "A submenu."
    Does anyone have a solution to this? Thanks a lot!
    Sample application:
    ======================================================
    Note: The code below is a modification of the Sun menu tutorial found at http://java.sun.com/docs/books/tutorial/uiswing/components/menu.html
    middle.gif can be downloaded from http://java.sun.com/docs/books/tutorial/uiswing/components/example-1dot4/images/middle.gif
    MenuLookDemoApplet.java:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.JMenu;
    import javax.swing.JMenuItem;
    import javax.swing.JCheckBoxMenuItem;
    import javax.swing.JRadioButtonMenuItem;
    import javax.swing.ButtonGroup;
    import javax.swing.JMenuBar;
    import javax.swing.KeyStroke;
    import javax.swing.ImageIcon;
    import javax.swing.JPanel;
    import javax.swing.JTextArea;
    import javax.swing.JScrollPane;
    import javax.swing.JApplet;
    /* MenuLookDemoApplet.java is a 1.4 application that requires images/middle.gif. */
    * This class exists solely to show you what menus look like.
    * It has no menu-related event handling.
    public class MenuLookDemoApplet extends JApplet {
        JTextArea output;
        JScrollPane scrollPane;
        public JMenuBar createMenuBar() {
            JMenuBar menuBar;
            JMenu menu, submenu;
            JMenuItem menuItem;
            JRadioButtonMenuItem rbMenuItem;
            JCheckBoxMenuItem cbMenuItem;
            //Create the menu bar.
            menuBar = new JMenuBar();
            //Build the first menu.
            menu = new JMenu("A Menu");
            menu.setMnemonic(KeyEvent.VK_A);
            menu.getAccessibleContext().setAccessibleDescription(
                    "The only menu in this program that has menu items");
            menuBar.add(menu);
            //a group of JMenuItems
            menuItem = new JMenuItem("A text-only menu item",
                                     KeyEvent.VK_T);
            //menuItem.setMnemonic(KeyEvent.VK_T); //used constructor instead
            menuItem.setAccelerator(KeyStroke.getKeyStroke(
                    KeyEvent.VK_1, ActionEvent.ALT_MASK));
            menuItem.getAccessibleContext().setAccessibleDescription(
                    "This doesn't really do anything");
            menu.add(menuItem);
            ImageIcon icon = createImageIcon("images/middle.gif");
            menuItem = new JMenuItem("Both text and icon", icon);
            menuItem.setMnemonic(KeyEvent.VK_B);
            menu.add(menuItem);
            menuItem = new JMenuItem(icon);
            menuItem.setMnemonic(KeyEvent.VK_D);
            menu.add(menuItem);
            //a group of radio button menu items
            menu.addSeparator();
            ButtonGroup group = new ButtonGroup();
            rbMenuItem = new JRadioButtonMenuItem("A radio button menu item");
            rbMenuItem.setSelected(true);
            rbMenuItem.setMnemonic(KeyEvent.VK_R);
            group.add(rbMenuItem);
            menu.add(rbMenuItem);
            rbMenuItem = new JRadioButtonMenuItem("Another one");
            rbMenuItem.setMnemonic(KeyEvent.VK_O);
            group.add(rbMenuItem);
            menu.add(rbMenuItem);
            rbMenuItem.setEnabled(false);   //@dpb
            //a group of check box menu items
            menu.addSeparator();
            cbMenuItem = new JCheckBoxMenuItem("A check box menu item");
            cbMenuItem.setMnemonic(KeyEvent.VK_C);
            menu.add(cbMenuItem);
            cbMenuItem = new JCheckBoxMenuItem("Another one");
            cbMenuItem.setMnemonic(KeyEvent.VK_H);
            menu.add(cbMenuItem);
            //a submenu
            menu.addSeparator();
            submenu = new JMenu("A submenu");
            submenu.setMnemonic(KeyEvent.VK_S);
            menuItem = new JMenuItem("An item in the submenu");
            menuItem.setAccelerator(KeyStroke.getKeyStroke(
                    KeyEvent.VK_2, ActionEvent.ALT_MASK));
            submenu.add(menuItem);
            menuItem = new JMenuItem("Another item");
            submenu.add(menuItem);
            menu.add(submenu);
            //Build second menu in the menu bar.
            menu = new JMenu("Another Menu");
            menu.setMnemonic(KeyEvent.VK_N);
            menu.getAccessibleContext().setAccessibleDescription(
                    "This menu does nothing");
            menuBar.add(menu);
            return menuBar;
        public Container createContentPane() {
            //Create the content-pane-to-be.
            JPanel contentPane = new JPanel(new BorderLayout());
            contentPane.setOpaque(true);
            //Create a scrolled text area.
            output = new JTextArea(5, 30);
            output.setEditable(false);
            scrollPane = new JScrollPane(output);
            //Add the text area to the content pane.
            contentPane.add(scrollPane, BorderLayout.CENTER);
            return contentPane;
        /** Returns an ImageIcon, or null if the path was invalid. */
        protected static ImageIcon createImageIcon(String path) {
            java.net.URL imgURL = MenuLookDemo.class.getResource(path);
            if (imgURL != null) {
                return new ImageIcon(imgURL);
            } else {
                System.err.println("Couldn't find file: " + path);
                return null;
        public void init() {
            MenuLookDemoApplet demo = new MenuLookDemoApplet();
            setJMenuBar(demo.createMenuBar());
            setContentPane(demo.createContentPane());
    applet.html:
    <html>
    <head>
        <title>Menu Test Page </title>
    </head>
    <body>
    Here's the applet:
    <applet code="MenuLookDemoApplet.class" width="300" height="300">
    </applet>
    </body>
    </html>

    Unfortunately the menu items are fully accessible (or so our internal accessibility tool claims). It doesn't seem to be a problem on that level, but I was hoping that perhaps something else was interfeering.
    As for the JTable reading the previous cell, I've notice that it reads the last non-empty cell (regardless of whether it was the previous cell or not) when clicking or moving with the arrow keys to an empty cell. It works fine when clicking or moving to non-empty cells.
    I don't have any empty cells in the actual application so I did not try to fix it. My suspicions are that either an event is not being fired or the selection position is not being updated on the empty cells.

  • Open image in Swing Application

    Hi,
    I'm having trouble getting an image to open into my swing application and I cant figure out whats wrong. In response to selecting the "Open" button or menu item a JFileChooser opens up and i select an image but the image doesn't actually load. If anyone could help i'd really appreciate it.
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import java.io.*;
    import javax.swing.border.*;
    import javax.imageio.*;
    class PhotoEditor extends JPanel implements ActionListener {
         * Create the GUI and show it.  For thread safety,
         * this method should be invoked from the
         * event-dispatching thread.
        JMenu imageMenu, effectsMenu;
        JFileChooser fc = new JFileChooser();
        BufferedImage img = null;
           public JMenuBar createMenuBar() {     
         JMenuBar menuBar = new JMenuBar();
        /* Build the first menu: */
        JMenu fileMenu = new JMenu("File");
        menuBar.add(fileMenu);
        fileMenu.setMnemonic(KeyEvent.VK_F);
        //a group of JMenuItems under the File option:
            String[] menuItems1 = {"Open", "Save","Save As..", "Close"};
        String[] menuIcons1 = {"Open.gif", "Save.gif", "", ""};
        for (int i = 0; i<menuItems1.length; i++)
                  JMenuItem fileMI = new JMenuItem(menuItems1, new ImageIcon(menuIcons1[i]));
              fileMI.addActionListener(this);
              fileMenu.add(fileMI);
    //adding a separator to the drop down menu list
    fileMenu.addSeparator();
    JMenuItem exitMI = new JMenuItem("Exit", new ImageIcon("Exit.gif"));
    exitMI.addActionListener(this);
    fileMenu.add(exitMI);
    /* Code which builds all the menu here */
    return menuBar;
         public JToolBar createToolBar() {     
         JToolBar toolB = new JToolBar(FlowLayout.LEFT);
    toolB.setLayout(new FlowLayout());
    // contentPane.add(toolB, "North");
    JButton newButton = new JButton(new ImageIcon("new24.gif"));
    newButton.addActionListener(this);
    toolB.add(newButton);
    newButton.setToolTipText("New");
    newButton.setActionCommand("New");
    //adding a separator to the drop down menu list
    toolB.addSeparator();
    JButton openButton = new JButton(new ImageIcon("open24.gif"));
    openButton.addActionListener(this);
    toolB.add(openButton);
    openButton.setToolTipText("Open");
         openButton.setActionCommand("Open");
    /* More code building the toolbar*/
    return toolB;
         public void actionPerformed(ActionEvent e) {
    Object eventSource = e.getSource();
    if ((eventSource instanceof JMenuItem) || (eventSource instanceof JButton));{
    String label = (String) e.getActionCommand();
    //Sets up the Action Listeners
    if (label.equals("Exit")) {
    System.exit(0);
    // Closes application
    else if (label.equals("Open")) {
         openImage();
    /* More codes for each button or menu item */
    protected void openImage() {
              int returnVal = fc.showOpenDialog(this);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
    File file = fc.getSelectedFile();
         try {
                   img = ImageIO.read(file);
                        catch (IOException e1) {
    public void paintComponent(Graphics g) {
         super.paintComponent(g);
    g.drawImage(img, 500, 500, null);
    private static void createAndShowGUI() {
    //Create and set up the window.
    JFrame frame = new JFrame("Photo Editor");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //Create a main label to put in the content pane.
    JLabel main = new JLabel();
    // main.setOpaque(true);
    // main.setBackground(new Color(128, 128, 128));
    main.setPreferredSize(new Dimension(800, 600));
    //Set the menu bar and add the label to the content pane.
    PhotoEditor mainmenu = new PhotoEditor();
    frame.setJMenuBar(mainmenu.createMenuBar());
         frame.getContentPane().add(mainmenu.createToolBar(), BorderLayout.PAGE_START);
    frame.getContentPane().add(main, BorderLayout.CENTER);
    //Display the window.
    frame.pack();
    frame.setVisible(true);
    public static void main(String[] args) {
    //Schedule a job for the event-dispatching thread:
    //creating and showing this application's GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    createAndShowGUI();

    Your PhotoEditor class extends JPanel. In that class you override paintComponent(). But you never add the panel to the GUI, so that method is never invoked.
    Personally I would have the PhotoEditor class extend JFrame. Then in the constructor you build all the components for the frame
    a) build the menu
    b) build the toolbar
    Then I would create a PhotoPanel class that you extend and override the paintComponent(). Then you add this panel to the GUI as your main panel.
    For a simple example of drawing a background image on a panel search the forum for my BackgroundImage example.

  • A question on JInternalFrame of Swing. Let see the code

    Hello everybody,
    I am setting up a Frame that contains 2 JInternalFrames in its desktopPane. The first JInternalFrame is to show the map. The second one have some check box. What I wanna do is, when I check the CheckBox in the second JInternalFrame, after getting the result from Database, it show the result on Map. The result will be some red ellipses on the first JInternalFrame.
    The code work well with Database. But I really need your help to do with the event on InternalFrame
    Thanks in advance !
    Quin,
    Here is the code of the main Frame:
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.font.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.util.*;
    import java.io.*;
    import java.net.*;
    import java.beans.*;
    public class MapLocator
         public static void main(String [] args)
              JFrame frame = new DesktopFrame();
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setVisible(true);
    Create a desktop frames that contains internal frame
    class DesktopFrame extends JFrame implements ActionListener
         public DesktopFrame()
              super("Map Locator v.1.0.0");
              this.setSize(new Dimension(WIDTH,HEIGHT));
              desktop = new JDesktopPane();
              this.setContentPane(desktop);
              this.createInternalFrame(
                   new mapPanel(),"Ban do Thanh pho Ho Chi Minh",0,0,480,515);
              this.createInternalFrame(
                   new commandPanel(),"Chu thich va tim kiem",480,0,320,515);
    Create an internal frame on the desktop.
    @param c the component to display in the internal frame
    @param t the title ofthe internal frame.
         public void createInternalFrame(JPanel c, String t,int ifx, int ify, int ifwidth, int ifheight)
                 final JInternalFrame iframe = new JInternalFrame(t,
                 true//resizeable
                 ,true//closable
                 ,true//maximizable
                 ,true//iconifiable
                 iframe.getContentPane().add(c);
                 desktop.add(iframe);
                 iframe.setFrameIcon(new ImageIcon("new.gif"));
                 //add listener to confirm frame closing
                 iframe.addVetoableChangeListener(new VetoableChangeListener()
                      public void vetoableChange(PropertyChangeEvent event)
                           throws PropertyVetoException
                           String name = event.getPropertyName();
                           Object value = event.getNewValue();
                           //we only want to check attempts to close a frame
                           if(name.equals("closed") && value.equals(Boolean.TRUE))
                                //ask user if it is ok to close
                                int result =
                      JOptionPane.showInternalConfirmDialog(iframe,"OK to close");
                                //if the user doesn't agree, veto the close
                                if(result != JOptionPane.YES_OPTION)
                      throw new PropertyVetoException("User cancel the close",event);
                 iframe.setVisible(true);
                 iframe.setLocation(ifx,ify);
                 iframe.setSize(new Dimension (ifwidth, ifheight));
         private static final int WIDTH = 800;
         private static final int HEIGHT = 600;
         private JDesktopPane desktop;
         private int nextFrameX;
           private int nextFrameY;
            private int frameDistance;
         private JMenuBar menuBar;
         private JMenu fileMenu, viewMenu, searchMenu, windowMenu, helpMenu;
         private JRadioButtonMenuItem javalaf, liquidlaf, motiflaf, windowlaf, threedlaf;
    }Below is the code of first JInternalFrame
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.sql.*;
    import java.awt.font.*;
    import java.awt.geom.*;
    import java.awt.image.BufferedImage;
    import java.io.*;
    import java.util.Random;
    import java.util.*;
    import com.sun.image.codec.jpeg.*;
    Create a canvas that show a map
    public class mapPanel extends JPanel
         implements MouseMotionListener, MouseListener
         public mapPanel()
              addMouseMotionListener(this);
              addMouseListener(this);
    Unbarrier the comment below to see how the map model work
    //Unbarrier this to see -->
             try
                InputStream in = getClass().getResourceAsStream(nameOfMap);
                JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(in);
                mImage = decoder.decodeAsBufferedImage();
                in.close();//Close dong nhap
              catch(ImageFormatException ie)
              { System.out.println ("Error on formating image");}
              catch(IOException ioe)
              { System.out.println ("Error on input/ouput image");}
              catch(Exception e){}
    Connect to database
              connDB();
              String addQuery = "";
              try
              Get the relation amongs points
                   int idStart = 0;
                   int idEnd = 0;
                   addQuery ="SELECT IDStart, IDEnd FROM 2Diem";
                   rs = stmt.executeQuery(addQuery);
                   int incre = 0;
                   while(rs.next())
                        idStart = rs.getInt(1);
                        Rel.add(incre, new Integer(idStart));
                        incre ++;
                        idEnd = rs.getInt(2);
                        Rel.add(incre, new Integer(idEnd));
                        incre ++;
         Load the Coordination of the points to hash table
                   int idPoint = 0;
                   int XP = 0;
                   int YP = 0;
                   addQuery ="SELECT IDDiem, CoorX, CoorY FROM Diem";
                   rs = stmt.executeQuery(addQuery);     
                   while(rs.next())
                        idPoint = rs.getInt(1);
                        XP = rs.getInt(2);
                        YP = rs.getInt(3);
                        hashX.put(new Integer(idPoint), new Integer(XP));
                        hashY.put(new Integer(idPoint), new Integer(YP));
         Create Points to draw the Line
                   line = new Line2D[(Rel.size())/2];
                   for(int i = 0, k = 0; i < Rel.size();i++, k = k+2)
                        X1 = Integer.parseInt(""+hashX.get(Rel.elementAt(i)));
                        Y1 = Integer.parseInt(""+hashY.get(Rel.elementAt(i)));
                        i++;
                        X2 = Integer.parseInt(""+hashX.get(Rel.elementAt(i)));
                        Y2 = Integer.parseInt(""+hashY.get(Rel.elementAt(i)));
                        line[k/2] = new Line2D.Double(X1,Y1,X2,Y2);
              catch(SQLException sqle){}
         private Hashtable hashX = new Hashtable();
         private Hashtable hashY = new Hashtable();
         private Vector Rel = new Vector(100,10);
         private Vector vecBackX = new Vector(10,2);
         private Vector vecBackY = new Vector(10,2);
         private int X1 = 0, X2 = 0, Y1 = 0, Y2 = 0;
         Draw the image to show
         public void paintComponent(Graphics g)
              super.paintComponent(g);
              Graphics2D g2 = (Graphics2D) g;
              g2.setRenderingHint(
                   RenderingHints.KEY_ANTIALIASING,
                   RenderingHints.VALUE_ANTIALIAS_ON);
        //     g2.drawImage(mImage,0,0,null);
        Paint the background with light Gray
              g2.setPaint(Color.lightGray);
              g2.fill(new Rectangle2D.Double(0,0,480,480));          
             fillBack(g2);
        Draw the street with its border is white, its background is orange
             g2.setPaint(Color.white);
              g2.setStroke(new BasicStroke(14,BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
              for(int k = 0; k < Rel.size()/2; k++)
                   g2.draw(line[k]);
              g2.setPaint(Color.orange);
              g2.setStroke(new BasicStroke(10,BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
              for(int k = 0; k < Rel.size()/2; k++)
                   g2.draw(line[k]);
         Draw the grid on map
              g2.setPaint(Color.white);
              g2.setStroke(new BasicStroke(1));
              drawGrid(g2);
              if(point != null)
                   g2.setPaint(Color.red);
                   g2.fillOval(point.x - 3, point.y - 3, 7, 7);
    Draw the Background with tree and water
    @param g2 the Graphics2D that used to draw shapes
         private void fillBack(Graphics2D g2)
              Draw the background for map
              try
                   int BackX = 0;
                   int BackY = 0;
                   int incre = 0;
                   backGround = new GeneralPath[3];
                   for(int idBack = 1; idBack <= 3; idBack++)
    Since we use the vector for each background(tree / water), we have to
    refresh the vector before it can add new path inside
                        vecBackX.clear();
                        vecBackY.clear();
                        String addQuery = "SELECT CoorX, CoorY FROM BackCoor WHERE "
                        + " IDBack =" + idBack;
                        rs = stmt.executeQuery(addQuery);
                        while(rs.next())
                             BackX = rs.getInt(1);
                             BackY = rs.getInt(2);
    This will take the point into vector
                             vecBackX.add(incre,new Integer(BackX));
                             vecBackY.add(incre,new Integer(BackY));
                             incre++;
    Design the shapes of path
                             backGround[(idBack - 1)] =
                                  new GeneralPath(GeneralPath.WIND_EVEN_ODD);
                             backGround[(idBack - 1)].moveTo(
                                  Integer.parseInt(""+vecBackX.elementAt(0)),
                                  Integer.parseInt(""+vecBackY.elementAt(0)));
                             for(int i = 1; i < vecBackX.size(); i++)
                                  backGround[(idBack - 1)].lineTo(
                                       Integer.parseInt(""+vecBackX.elementAt(i)),
                                       Integer.parseInt(""+vecBackY.elementAt(i)));
                             backGround[(idBack - 1)].lineTo(
                                       Integer.parseInt(""+vecBackX.elementAt(0)),
                                       Integer.parseInt(""+vecBackY.elementAt(0)));
                             backGround[(idBack - 1)].closePath();
    Here we have 3 Path that represented to tree and water
    The first and second one is tree.
    The last one is water.
    Draw the path now
                             if(idBack == 3)
                                  g2.setPaint(Color.cyan);
                                  g2.fill(backGround[(idBack - 1)]);
                             else
                                  g2.setPaint(Color.green);
                                  g2.fill(backGround[(idBack - 1)]);
                             incre = 0;
              catch(SQLException sqle)
                   System.out.println ("Khong ve duoc back ground");
    Create the grid on map
    @param g2 the Graphics2D that used to draw shapes
         private void drawGrid(Graphics2D g2)
              try
                 String Query =
                 "SELECT * FROM Grid";
                 rs = stmt.executeQuery(Query);
                 GridX = new Vector(100,2);
                 GridY = new Vector(100,2);
                 GridW = new Vector(100,2);
                 GridH = new Vector(100,2);
                 int incr = 0;
                 while(rs.next())
                      gridX = rs.getInt(2);
                      gridY = rs.getInt(3);
                      gridW = rs.getInt(4);
                      gridH = rs.getInt(5);
                      GridX.add(incr, new Integer(gridX));
                      GridY.add(incr, new Integer(gridY));
                      GridW.add(incr, new Integer(gridW));
                      GridH.add(incr, new Integer(gridH));
                      incr ++;
                 rec = new Rectangle2D.Double[GridX.size()];
                 for(int i = 0; i < GridX.size(); i++)
                      gridX = Integer.parseInt(""+GridX.elementAt(i));
                      gridY = Integer.parseInt(""+GridY.elementAt(i));
                      gridW = Integer.parseInt(""+GridW.elementAt(i));
                      gridH = Integer.parseInt(""+GridH.elementAt(i));
                      rec[i] = new Rectangle2D.Double(gridX, gridY, gridW, gridH);
                      g2.draw(rec);
    catch(SQLException sqle){}
    private Vector GridX, GridY, GridW, GridH;
    private int gridX = 0, gridY = 0, gridW = 0, gridH = 0;
    Fill the point
         public void placePoint(Graphics2D g2,Point p)
              g2.setPaint(Color.red);
              g2.fill(new Ellipse2D.Double(p.x - 3, p.y - 3, 7,7));
    Create connection to Database
         public void connDB()
              System.out.println ("Connecting to Database");
              String fileName = "Pro.mdb";
              String data = "jdbc:odbc:Driver={Microsoft Access Driver " +
         "(*.mdb)};DBQ=" + fileName + ";DriverID=22";
              try
                   Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                   conn = DriverManager.getConnection(data,"","");
                   stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
                        ResultSet.CONCUR_UPDATABLE);
              catch(ClassNotFoundException ce)
              { System.out.println ("Khong tim thay Driver"); }
              catch(SQLException sqle)
              { System.out.println ("Loi SQL trong khi Connect"); }
              Statement stmt = null;
              ResultSet rs = null;
              Connection conn = null;     
    This one is the model map to draw
         private String nameOfMap = "map.jpg";
         private BufferedImage mImage;
    Initialize the path and shapes to draw
         private Line2D line[];
         private Rectangle2D.Double rec[];
         private GeneralPath backGround[];
         private Point point;
         private int changeColor = 0;
    The last one is:
    import java.awt.*;
    import java.awt.geom.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.sql.*;
    public class commandPanel extends JPanel implements ActionListener
    Initial check box
         JCheckBox uyBanNhanDan = new JCheckBox();
         JCheckBox nganHang = new JCheckBox();
         JCheckBox buuDien = new JCheckBox();     
         JCheckBox khachSan = new JCheckBox();     
         JCheckBox benhVien = new JCheckBox();          
         JCheckBox cho = new JCheckBox();     
         JCheckBox nhaHat = new JCheckBox();     
         JCheckBox daiHoc = new JCheckBox();     
         JCheckBox thuvien = new JCheckBox();     
         JCheckBox nhaTho = new JCheckBox();     
         public commandPanel()
              this.setLayout(new BorderLayout());
              this.setBorder(BorderFactory.createCompoundBorder(
                          BorderFactory.createTitledBorder("***Chu dan***"),
                          BorderFactory.createEmptyBorder(5,5,5,5)));
    Create the combobox to show information
              uyBanNhanDan.setText("Uy Ban ND Quan");
              nganHang.setText("Ngan Hang");
              buuDien.setText("Buu Dien");
              khachSan.setText("Khach San");
              benhVien.setText("Benh Vien");
              cho.setText("Cho - Mua Sam");
              nhaHat.setText("Nha Hat");
              daiHoc.setText("Dai Hoc - Dao Tao");
              thuvien.setText("Thu Vien - Nha Sach");
              nhaTho.setText("Nha Tho - Chua");
              uyBanNhanDan.addActionListener(this);
              nganHang.addActionListener(this);
              buuDien.addActionListener(this);
              khachSan.addActionListener(this);
              benhVien.addActionListener(this);
              cho.addActionListener(this);
              nhaHat.addActionListener(this);
              daiHoc.addActionListener(this);
              thuvien.addActionListener(this);
              nhaTho.addActionListener(this);
              uyBanNhanDan.setActionCommand("1");
              nganHang.setActionCommand("2");
              buuDien.setActionCommand("3");
              khachSan.setActionCommand("4");
              benhVien.setActionCommand("5");
              cho.setActionCommand("6");
              nhaHat.setActionCommand("7");
              daiHoc.setActionCommand("8");
              thuvien.setActionCommand("10");
              nhaTho.setActionCommand("11");
              JPanel secP = new JPanel();
              secP.setLayout(new GridLayout(5,2));
              secP.add(uyBanNhanDan);
              secP.add(nganHang);
              secP.add(buuDien);
              secP.add(khachSan);
              secP.add(benhVien);
              secP.add(cho);
              secP.add(nhaHat);
              secP.add(daiHoc);
              secP.add(thuvien);
              secP.add(nhaTho);
              this.add(secP,BorderLayout.NORTH);
         public void actionPerformed(ActionEvent event)
              int x = 0;
              int y = 0;
              try
                   mapPanel mp = new mapPanel();
                   int idDiaDanh = 0;
                   if(event.getActionCommand() == "1")
                        idDiaDanh = 1;
                   String Query =
                   "SELECT CoorX, CoorY FROM MoTa WHERE IDDiaDanh =" + idDiaDanh;
                   mp.rs = mp.stmt.executeQuery(Query);
                   while(mp.rs.next())
    /*I have problem here*/
    /*Process the event for me*/          x = mp.rs.getInt(1);
                        y = mp.rs.getInt(2);
                        Graphics g2 = mp.getGraphics();
                        mp.paintComponents(g2);
                             g2.setPaint(Color.red);
                             g2.fill(new Ellipse2D.Double(x - 3, y - 3, 7, 7));     
              catch(SQLException sqle){}

    Strings are Objects.
    String[] strings = new String[3];
    String[0]="abcde";Right here, you are initializing the String array, and the String at index 0.
    JButton[] buttons = new JButton[2];
    buttons[0].setText("abcde");Right here, you are initializing the JButton array, but not any of the JButtons in the array. You then try to use the setText() method on a null JButton.

  • How to set a Swing component as Modal on a SWT Component?

    How to set a Swing component as Modal on a SWT Componen?.I mean, I have a SWt Component window and from that window I am displaying a SWING Component Modal window.
    The problem is my swing window is not working as Modal always.
    When I opened the swing window from SWT window,swing window is working as Modal.But if Idouble click on Menubar or Title bar of the SWT Window then my Swing window goes back.If I click on any other part of the SWT window.. then once again Swing window is working as modal.
    Can any one suggest me to solve this?
    I think this is isuue related with Swing over SWT..

    pradeep.rajadurai wrote:
    I want set the JTable as a background of jframe or jinternalframe , how it is possible One way that may work, you can always extract the image from a rendered JTable and then paint the same image into the JPanel that holds your components via it's paintComponent method, then added the JPanel to the app's contentPane.
    give me simple pgmIs English your second language? Because if so, please understand that this demand can be taken by some as rude.

  • How to list/access swing components?

    hi all,
    Can anyone give me a clue, how can I access or simply list swing components I have on a frame, long after I created them. E.g. I'd like to change their setEnabled() attribute at a later time, not at creation time, but I don't know how to access them.
    Does Swing/AWT/JFC provides a component hierarchy? can someone share some code on this issue?
    Thanks for any help.
    Thomas

    I guess, you are saying the use of getComponent(int n)?
    Since I'm a beginner in Swing see my short code below:
    import java.awt.BorderLayout;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    import javax.swing.JMenuItem;
    import javax.swing.JTextArea;
    public class EasyFrame {
        public EasyFrame() {
            super();
            startHere();
        public void startHere() {
            JFrame frame = new JFrame("SwingApplication");
            JButton button = new JButton("click here");
            JTextArea area = new JTextArea();
            frame.setSize(300, 200);
            frame.getContentPane().setLayout(new BorderLayout());
            frame.getContentPane().add(area, BorderLayout.CENTER);
            frame.getContentPane().add(button, BorderLayout.SOUTH);
            area.setText("Hello World");
            JMenuBar menuBar = new JMenuBar();
            JMenu menu = new JMenu("A Menu");
            menuBar.add(menu);
            JMenuItem menuItem = new JMenuItem("A text item");
            menu.add(menuItem);
            menu.addSeparator();
            menuItem = new JMenuItem("hello");
            menu.add(menuItem);
            JMenu subMenu = new JMenu("submenu");
            menuItem = new JMenuItem("sub1");
            subMenu.add(menuItem);
            menuItem = new JMenuItem("sub2");
            subMenu.add(menuItem);
            menu.add(subMenu);
            frame.getContentPane().add(menuBar, BorderLayout.NORTH);
            frame.show();
         public static void main(String[] args) {
         EasyFrame ef = new EasyFrame();
    }If I make a System.out.println(frame.getContentPane().getComponentCount());I get 3. But I should dig deeper (with getComponent(2)) to access JMenuBar. But this way I receive a AWT Component / not a JMenuBar Swing component to get its JMenu / and its JMenuItems. And I cannot make it cast to JMenuBar since this walk-through routine should be a universal while(isThereMoreCompenent){} procedure, I don't know when to cast to what (JMenu, JMenuItem, Button and so on).
    My problem is that how can I access the JMenuItems one by one, and change e.g. the setEnabled attribute of the "hello" menu?
    I hope you can make it clear to me.
    Please help if so.

Maybe you are looking for

  • Outlook 2003 has stopped working on windows 7

    Hi, so I started to get this error today, yestarday everything was finne: Problem signature:   Problem Event Name: APPCRASH Application Name: OUTLOOK.EXE   Application Version: 11.0.5510.0   Application Timestamp: 3f1380f0 Fault Module Name: StackHas

  • ICal To-Do's - Can I view only today's To-Do Items?

    Currently using iCal 4.0.3... Is there a way to view only today's To-Do Items rather than viewing the entire list of To-Do's. Appreciate any help! -Tyson

  • To store value

    SO PLEASE RUN THIS CODE AND TRY TO RECTIFY THE ERROR AND SOLVE THIS PROBLEMS. I WILL PLACE THESE TYPE TEXT NEAR BUYME BUTTON WHEN RUN THIS CODE FIRST IT WILL COME SCREEN LIKE "WELCOME TO SHOPPING CART" SELECT BOOKS AND CLICK ON SHOP YOU WILL COME "BO

  • Loud fan and beep sound

    Computer left on overnight when turned on has a loud fan that keeps getting louder and a long single beep every few seconds that gets gradually louder also

  • File not found error when Downloading Crystal Reports 2008

    Hi, I am trying to download a trial version of Crystal Reports 2008. I get the error "file not found" both times when I downloaded the zip file and opened it first from the Free trial link and next from the Diamond community page link.  Can anyone he