JTable in a JMenu

It is posibble to add a jtable in jmenu ??

This is what i;m trying to get : http://kynamar.dublu.ro/java/emoticoane.html
Follow the link please.
I have a jtable with all the icons but i don't know how to add to jmenu!
In that thread the jmenu have 2 columns,not 10 for example!
This is my jtable of icons
import java.util.Enumeration;
import java.util.Vector;
import javax.swing.ImageIcon;
import javax.swing.table.AbstractTableModel;
* @author marian.radu
public class ModelTabelSmyleys extends AbstractTableModel {
    protected Vector<ImageIcon> data;
    protected Vector<String> columnNames ;
    /** Creates a new instance of ModelTabelSmyleys */
    public ModelTabelSmyleys() {
        data=new Vector<ImageIcon>();
        columnNames=new Vector<String>();
        columnNames.addElement("");
        columnNames.addElement("");
        columnNames.addElement("");
        columnNames.addElement("");
        //columnNames.addElement("");
        //columnNames.addElement("");
        ObiectSmyleys smyleys=new ObiectSmyleys();
        smyleys.initializare();
        Enumeration enumeratie=smyleys.getContinut().keys();
                            while(enumeratie.hasMoreElements())
                                String urmatorul=enumeratie.nextElement().toString();
                                       data.addElement(smyleys.getContinut().get(urmatorul));
    public int getRowCount() {
    return data.size() / getColumnCount();
  public int getColumnCount(){
    return columnNames.size();
  public String getColumnName(int columnIndex) {
    String colName = "";
    if (columnIndex <= getColumnCount())
       colName = columnNames.elementAt(columnIndex);
    return colName;
  public Class getColumnClass(int columnIndex){
    return ImageIcon.class;
  public boolean isCellEditable(int rowIndex, int columnIndex) {
    return false;
  public void removeRow(int rowIndex)
      for(int i = 0;i < getColumnCount();i++)
      data.removeElementAt((rowIndex * getColumnCount()));
  public Object getValueAt(int rowIndex, int columnIndex) {
    return data.elementAt
        ( (rowIndex * getColumnCount()) + columnIndex);
  public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
    data.setElementAt((ImageIcon)aValue,(rowIndex * getColumnCount()) + columnIndex);
import java.io.File;
import java.io.IOException;
import java.util.Hashtable;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
* @author marian.radu
public class ObiectSmyleys {
    private Hashtable<String,ImageIcon> continut=new Hashtable<String,ImageIcon>();
    /** Creates a new instance of ObiectSmyleys */
    protected String calea_dir_cur()
            String cale=""; //initializare cale nula
            try
                File f=new File(".");
                cale=f.getCanonicalPath();
            }catch(IOException err){}
            return cale;
    public Hashtable<String,ImageIcon> getContinut()
        return continut;
    public void addSmyleys(String toolTip,String nume_fisier)
        //JLabel label=new JLabel();
        ImageIcon imagine=new ImageIcon(calea_dir_cur()+"\\smiley\\"+nume_fisier);
        //label.setIcon(imagine);
        //label.setToolTipText(toolTip);
        continut.put(toolTip,imagine);
    public ObiectSmyleys() {
    public void initializare()
       addSmyleys(":-)","1.png");
       addSmyleys(":-(","2.png");
       addSmyleys(";-)","3.png");
       addSmyleys(":-D","4.png");
       addSmyleys(":-P","10.png");
       addSmyleys(":-*","11.png");
       addSmyleys(":-X","8.png");
       addSmyleys(":-))","20.png");
    public static void main(String[] args)
        ObiectSmyleys smyle=new ObiectSmyleys();
        System.out.println(smyle.getContinut().size());
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.text.TabExpander;
* @version 1.0 06/19/99
public class AnimatedTableIconExample extends JFrame {
  public AnimatedTableIconExample(){
    super( "AnimatedIconTable Example" );
    final JTable table = new JTable(new ModelTabelSmyleys());
    table.addMouseListener(new MouseAdapter()
    public void mouseClicked(MouseEvent e)
        if (e.getClickCount()==1)
            System.out.println("De 2 ori");
            System.out.println(table.getIntercellSpacing());
           System.out.println(table.getValueAt(table.getSelectedRow(),table.getSelectedColumn()));
    table.setAutoResizeMode(table.AUTO_RESIZE_OFF);
    for(int i=0;i<table.getModel().getColumnCount();i++)
        table.getColumnModel ().getColumn(i).setMaxWidth(18);
    table.setRowHeight(18);
    table.setColumnSelectionAllowed(false);
    table.setRowSelectionAllowed(false);
    table.setCellSelectionEnabled(true);
    table.setIntercellSpacing(new Dimension(0,0));
    //setImageObserver(table);
    JScrollPane pane = new JScrollPane(table);
    getContentPane().add(pane);
    table.repaint();
  private void setImageObserver(JTable table) {
    TableModel model = table.getModel();
    int colCount = model.getColumnCount ();
    int rowCount = model.getRowCount();
    for (int col=0;col<colCount;col++) {
      if (ImageIcon.class == model.getColumnClass(col)) {
        for (int row=0;row<rowCount;row++) {
          ImageIcon icon = (ImageIcon)model.getValueAt(row,col);
          if (icon != null) {
            icon.setImageObserver(new CellImageObserver(table, row, col));
  class CellImageObserver implements ImageObserver {
    JTable table;
    int row;
    int col;
    CellImageObserver(JTable table,int row, int col) {
      this.table = table;
      this.row   = row;
      this.col   = col;
    public boolean imageUpdate(Image img, int flags,
                   int x, int y, int w, int h) {
      if ((flags & (FRAMEBITS|ALLBITS)) != 0) {
        Rectangle rect = table.getCellRect(row,col,false);
        table.repaint(rect);
      return (flags & (ALLBITS|ABORT)) == 0;
  public static void main(String[] args) {
    AnimatedTableIconExample frame = new AnimatedTableIconExample();
    frame.addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
        System.exit(0);
    frame.setSize( 300, 150 );
    frame.setVisible(true);
}

Similar Messages

  • MDI JTable Overlap Area Repaint Problem

    Hi all,
    I have a problem for my application in MDI mode.
    I open many windows (JInternalFrame contain JTable) under JDesktopPane. Some of the windows are overlapping and when they receive update in the table, it seems repaint all of the overlapping windows, not only itself. This make my application performance become poor, slow respond for drap & drop an existing window or open a new window.
    To prove this, i make a simple example for open many simple table and have a thread to update the table's value for every 200 mill second. After i open about 20 windows, the performance become poor again.
    If anyone face the same problem with me and any suggestions to solve the problem ?
    Please help !!!!!
    Following are my sources:
    public class TestMDI extends JFrame {
        private static final long serialVersionUID = 1L;
        private JPanel contentPanel;
        private JDesktopPane desktopPane;
        private JMenuBar menuBar;
        private List<TestPanel> allScreens = new ArrayList<TestPanel>();
        private List<JDialog> freeFloatDialogs = new ArrayList<JDialog>();
        private List<JInternalFrame> mdiInternalFrm = new ArrayList<JInternalFrame>();
        int x = 0;
        int y = 0;
        int index = 0;
        private static int MDI_MODE = 0;
        private static int FREE_FLOAT_MODE = 1;
        private int windowMode = MDI_MODE;
        public TestMDI() {
            init();
        public static void main(String[] args) {
            new TestMDI().show();
        public void init() {
            contentPanel = new JPanel();
            desktopPane = new JDesktopPane();
            desktopPane.setDragMode(JDesktopPane.LIVE_DRAG_MODE);
            desktopPane.setFocusTraversalKeysEnabled(false);
            desktopPane.setFocusTraversalPolicyProvider(false);
            desktopPane.setBorder(null);
            desktopPane.setIgnoreRepaint(true);
            desktopPane.setPreferredSize(new Dimension(1000, 800));
            this.setSize(new Dimension(1000, 800));
            menuBar = new JMenuBar();
            JMenu menu1 = new JMenu("Test");
            JMenuItem menuItem1 = new JMenuItem("Open Lable Screen");
            menuItem1.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    for (int i = 1; i < 4; i++) {
                        final TestJLableScreen screen = new TestJLableScreen("Screen  " + (allScreens.size() + 1));
                        screen.startTime();
                        if (windowMode == MDI_MODE) {
                            JInternalFrame frame = createInternalFram(screen);
                            desktopPane.add(frame);
                            mdiInternalFrm.add(frame);
                            if (allScreens.size() * 60 + 100 < 1000) {
                                x = allScreens.size() * 60;
                                y = 60;
                            } else {
                                x = 60 * index;
                                y = 120;
                                index++;
                            frame.setLocation(x, y);
                            frame.setVisible(true);
                        } else {
                            JDialog dialog = createJDialog(screen);
                            freeFloatDialogs.add(dialog);
                            if (i * 60 + 100 < 1000) {
                                x = i * 60;
                                y = 60;
                            } else {
                                x = 60 * index;
                                y = 120;
                                index++;
                            dialog.setLocation(x, y);
                            dialog.setVisible(true);
                        allScreens.add(screen);
            JMenuItem menuItem2 = new JMenuItem("Open Table Screen");
            menuItem2.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    for (int i = 1; i < 4; i++) {
                        TestTableScreen screen = new TestTableScreen("Screen  " + (allScreens.size() + 1));
                        screen.startTime();
                        if (windowMode == MDI_MODE) {
                            JInternalFrame frame = createInternalFram(screen);
                            desktopPane.add(frame);
                            mdiInternalFrm.add(frame);
                            if (allScreens.size() * 60 + 100 < 1000) {
                                x = allScreens.size() * 60;
                                y = 60;
                            } else {
                                x = 60 * index;
                                y = 120;
                                index++;
                            frame.setLocation(x, y);
                            frame.setVisible(true);
                        } else {
                            JDialog dialog = createJDialog(screen);
                            freeFloatDialogs.add(dialog);
                            if (i * 60 + 100 < 1000) {
                                x = i * 60;
                                y = 60;
                            } else {
                                x = 60 * index;
                                y = 120;
                                index++;
                            dialog.setLocation(x, y);
                            dialog.setVisible(true);
                        allScreens.add(screen);
            menu1.add(menuItem1);
            menu1.add(menuItem2);
            this.setJMenuBar(menuBar);
            this.getJMenuBar().add(menu1);
            this.getJMenuBar().add(createSwitchMenu());
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            this.add(desktopPane);
            desktopPane.setDesktopManager(null);
        public JInternalFrame createInternalFram(final TestPanel panel) {
            final CustomeInternalFrame internalFrame = new CustomeInternalFrame(panel.getTitle(), true, true, true, true) {
                public void doDefaultCloseAction() {
                    super.doDefaultCloseAction();
                    allScreens.remove(panel);
            internalFrame.setPanel(panel);
            // internalFrame.setOpaque(false);
            internalFrame.setSize(new Dimension(1010, 445));
            internalFrame.add(panel);
            internalFrame.setFocusTraversalKeysEnabled(false);
            internalFrame.setFocusTraversalPolicyProvider(false);
            desktopPane.getDesktopManager();
            // internalFrame.setFocusTraversalKeysEnabled(false);
            internalFrame.setIgnoreRepaint(true);
            return internalFrame;
        public JDialog createJDialog(final TestPanel panel) {
            JDialog dialog = new JDialog(this, panel.getTitle());
            dialog.setSize(new Dimension(1010, 445));
            dialog.add(panel);
            dialog.addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                    allScreens.remove(panel);
            return dialog;
        public JMenu createSwitchMenu() {
            JMenu menu = new JMenu("Test2");
            JMenuItem menuItem1 = new JMenuItem("Switch FreeFloat");
            menuItem1.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    windowMode = FREE_FLOAT_MODE;
                    for (JInternalFrame frm : mdiInternalFrm) {
                        frm.setVisible(false);
                        frm.dispose();
                        frm = null;
                    mdiInternalFrm.clear();
                    remove(desktopPane);
                    desktopPane.removeAll();
    //                revalidate();
                    repaint();
                    add(contentPanel);
                    index = 0;
                    for (JDialog dialog : freeFloatDialogs) {
                        dialog.setVisible(false);
                        dialog.dispose();
                        dialog = null;
                    freeFloatDialogs.clear();
                    for (int i = 0; i < allScreens.size(); i++) {
                        JDialog dialog = createJDialog(allScreens.get(i));
                        freeFloatDialogs.add(dialog);
                        if (i * 60 + 100 < 1000) {
                            x = i * 60;
                            y = 60;
                        } else {
                            x = 60 * index;
                            y = 120;
                            index++;
                        dialog.setLocation(x, y);
                        dialog.setVisible(true);
            JMenuItem menuItem2 = new JMenuItem("Switch MDI");
            menuItem2.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    windowMode = MDI_MODE;
                    remove(contentPanel);
                    add(desktopPane);
                    for (int i = 0; i < freeFloatDialogs.size(); i++) {
                        freeFloatDialogs.get(i).setVisible(false);
                        freeFloatDialogs.get(i).dispose();
                    freeFloatDialogs.clear();
    //                revalidate();
                    repaint();
                    for (JInternalFrame frm : mdiInternalFrm) {
                        frm.setVisible(false);
                        frm.dispose();
                        frm = null;
                    mdiInternalFrm.clear();
                    index = 0;
                    for (int i = 0; i < allScreens.size(); i++) {
                        JInternalFrame frame = createInternalFram(allScreens.get(i));
                        desktopPane.add(frame);
                        mdiInternalFrm.add(frame);
                        if (i * 60 + 100 < 1000) {
                            x = i * 60;
                            y = 60;
                        } else {
                            x = 60 * index;
                            y = 120;
                            index++;
                        frame.setLocation(x, y);
                        frame.setVisible(true);
            menu.add(menuItem1);
            menu.add(menuItem2);
            return menu;
    public class TestTableScreen extends TestPanel {
        private static final long serialVersionUID = 1L;
        JTable testTable = new JTable();
        MyTableModel tableModel1 = new MyTableModel(1);
        private boolean notRepaint = false;
        int start = 0;
        JScrollPane scrollPane = new JScrollPane();
        private Timer timmer = new Timer(200, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                Random indexRandom = new Random();
                final int index = indexRandom.nextInt(50);
                Random valRandom = new Random();
                final int val = valRandom.nextInt(600);
                SwingUtilities.invokeLater(new Runnable() {
                    public void run() {
                        notRepaint = false;
                        TestTableScreen.this.update(index + "|" + val);
        public TestTableScreen(String title) {
            this.title = title;
            init();
            tableModel1.setTabelName(title);
        public void startTime() {
            timmer.start();
        public String getTitle() {
            return title;
        public void update(String updateStr) {
            String[] val = updateStr.split("\\|");
            if (val.length == 2) {
                int index = Integer.valueOf(val[0]);
                List vals = tableModel1.getVector();
                if (vals.size() > index) {
                    vals.set(index, val[1]);
    //                 tableModel1.fireTableRowsUpdated(index, index);
                } else {
                    vals.add(val[1]);
    //                 tableModel1.fireTableRowsUpdated(vals.size() - 1, vals.size() - 1);
                tableModel1.fireTableDataChanged();
        public TableModel getTableModel() {
            return tableModel1;
        public void init() {
            testTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
            testTable.setRowSelectionAllowed(true);
            this.testTable.setModel(tableModel1);
            int[] width = { 160, 80, 45, 98, 60, 88, 87, 88, 80, 70, 88, 80, 75, 87, 87, 41, 88, 82, 75, 68, 69 };
            TableColumnModel columnModel = testTable.getColumnModel();
            for (int i = 0; i < width.length; i++) {
                columnModel.getColumn(i).setPreferredWidth(width[i]);
            testTable.setRowHeight(20);
            tableModel1.fireTableDataChanged();
            this.setLayout(new BorderLayout());
            TableColumnModel columnMode2 = testTable.getColumnModel();
            int[] width2 = { 200 };
            for (int i = 0; i < width2.length; i++) {
                columnMode2.getColumn(i).setPreferredWidth(width2[i]);
            scrollPane.getViewport().add(testTable);
            scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
            this.add(scrollPane, BorderLayout.CENTER);
        class MyTableModel extends DefaultTableModel {
            public List list = new ArrayList();
            String titles[] = new String[] { "袨怓1", "袨怓2", "袨怓3", "袨怓4", "袨怓5", "袨怓6", "袨怓7", "袨怓8", "袨怓9", "袨怓10", "袨怓11",
                    "袨怓12", "袨怓13", "袨怓14", "袨怓15", "袨怓16", "袨怓17", "袨怓18", "袨怓19", "袨怓20", "袨怓21" };
            String tabelName = "";
            int type_head = 0;
            int type_data = 1;
            int type = 1;
            public MyTableModel(int type) {
                super();
                this.type = type;
                for (int i = 0; i < 50; i++) {
                    list.add(i);
            public void setTabelName(String name) {
                this.tabelName = name;
            public int getRowCount() {
                if (list != null) {
                    return list.size();
                return 0;
            public List getVector() {
                return list;
            public int getColumnCount() {
                if (type == 0) {
                    return 1;
                } else {
                    return titles.length;
            public String getColumnName(int c) {
                if (type == 0) {
                    return "head";
                } else {
                    return titles[c];
            public boolean isCellEditable(int nRow, int nCol) {
                return false;
            public Object getValueAt(int r, int c) {
                if (list.size() == 0) {
                    return null;
                switch (c) {
                default:
                    if (type == 0) {
                        return r + " " + c + "  test ";
                    } else {
                        return list.get(r) + "   " + c;
        public boolean isNotRepaint() {
            return notRepaint;
        public void setNotRepaint(boolean notRepaint) {
            this.notRepaint = notRepaint;
    public class TestPanel extends JPanel {
        protected String title = "";
        protected boolean needRepaint = false;
        protected boolean isFirstOpen = true;
        public String getTitle() {
            return title;
        public void setNeedRepaint(boolean flag) {
            this.needRepaint = flag;
        public boolean isNeedRepaint() {
            return needRepaint;
        public boolean isFirstOpen() {
            return isFirstOpen;
        public void setFirstOpen(boolean isFirstOpen) {
            this.isFirstOpen = isFirstOpen;
    public class TestJLableScreen extends TestPanel {
        private static final long serialVersionUID = 1L;
        private JLabel[] allLables = new JLabel[20];
        private Timer timmer = new Timer(20, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                Random indexRandom = new Random();
                final int index = indexRandom.nextInt(10);
                Random valRandom = new Random();
                final int val = valRandom.nextInt(600);
                SwingUtilities.invokeLater(new Runnable() {
                    public void run() {
                        TestJLableScreen.this.setNeedRepaint(true);
                        TestJLableScreen.this.update(index + "|" + val);
        public TestJLableScreen(String title) {
            this.title = title;
            init();
        public void startTime() {
            timmer.start();
        public String getTitle() {
            return title;
        public void update(String updateStr) {
            String[] val = updateStr.split("\\|");
            if (val.length == 2) {
                int index = Integer.valueOf(val[0]);
                allLables[index * 2 + 1].setText(val[1]);
        public void init() {
            this.setLayout(new GridLayout(10, 2));
            boolean flag = true;
            for (int i = 0; i < allLables.length; i++) {
                allLables[i] = new JLabel() {
                    // public void setText(String text) {
                    // super.setText(text);
                    // // System.out.println("  setText " + getTitle() + "   ; " + this.getName());
                    public void paint(Graphics g) {
                        super.paint(g);
                        // System.out.println("  paint " + getTitle() + "   ; " + this.getName());
                    // public void repaint() {
                    // super.repaint();
                    // System.out.println("  repaint " + getTitle() + "   ; " + this.getName());
                allLables[i].setName("" + i);
                if (i % 2 == 0) {
                    allLables[i].setText("Name " + i + "  : ");
                } else {
                    allLables[i].setOpaque(true);
                    if (flag) {
                        allLables[i].setBackground(Color.YELLOW);
                        flag = false;
                    } else {
                        allLables[i].setBackground(Color.CYAN);
                        flag = true;
                    allLables[i].setText(i * 8 + "");
            for (int i = 0; i < allLables.length; i++) {
                this.add(allLables[i]);
    public class CustomeInternalFrame extends JInternalFrame {
        protected TestPanel panel;
        public CustomeInternalFrame() {
            this("", false, false, false, false);
        public CustomeInternalFrame(String title) {
            this(title, false, false, false, false);
        public CustomeInternalFrame(String title, boolean resizable) {
            this(title, resizable, false, false, false);
        public CustomeInternalFrame(String title, boolean resizable, boolean closable) {
            this(title, resizable, closable, false, false);
        public CustomeInternalFrame(String title, boolean resizable, boolean closable, boolean maximizable) {
            this(title, resizable, closable, maximizable, false);
        public CustomeInternalFrame(String title, boolean resizable, boolean closable, boolean maximizable,
                boolean iconifiable) {
            super(title, resizable, closable, maximizable, iconifiable);
        public TestPanel getPanel() {
            return panel;
        public void setPanel(TestPanel panel) {
            this.panel = panel;

    i had the same problem with buttons and it seemed that i overlayed my button with something else...
    so check that out first do you put something on that excact place???
    other problem i had was the VAJ one --> VisualAge for Java (terrible program)
    it does strange tricks even when you don't use the drawing tool...
    dunno 2 thoughts i had... check it out...
    SeJo

  • Retrieving values entered in a JTable

    Hi!
    I have made a sudoku solver as many others, but in the purpose of learning recursion, and now I am implementing GUI to that program. I have bean strugling to set up a table that shows the sudokutable, and most of all how to recieve the values entered into the table. I have looked at forums and search at google, but all the topics on this is not good enough. I just simply do not understand what they mean. Most often they just say: "Just paste this code in and it will turn out as intended". I want to know how it works.
    I have added the code below:
    import javax.swing.*;
    import javax.imageio.*;
    import java.awt.*;
    import java.awt.event.*;
    import easyIO.*;
    import java.util.*;
    import java.io.*;
    * Klassen Oblig3 som inneholder main metoden som starter programmet.
    * Dette er Utsynen for programmet.
    * @Param ru - Peker til klassen Rute.
    * @Param br - Peker til klassen Brett.
    * @Param skrivebord - En ny desktpoPane som representerer hovedvinduet..
    public class Oblig3 extends JFrame implements ActionListener {
         Rute  ru   = new Rute();
         Brett br   = new Brett(ru);
         ImageIcon icon;
         Image image;
         JDesktopPane skrivebord;
          * Konstrukt�ren Oblig3 som setter opp hovedvinduet.
          * @Param skjemrStorelse - Lagrer st�relsen p� skjermen.
         public Oblig3() {
              super("Oblig3");
              int innrykk = 400;
              Dimension skjermStorelse = Toolkit.getDefaultToolkit().getScreenSize();
              setBounds(innrykk, innrykk, skjermStorelse.width  - innrykk*3, skjermStorelse.height - innrykk*2);
              skrivebord = new JDesktopPane()
                   Image im = (new ImageIcon("bilder/panzer.gif")).getImage();
                   public void paintComponent(Graphics g){
                        g.drawImage(im,0,0,this);
              setContentPane(skrivebord);
              setJMenuBar(lagMenyList());
              skrivebord.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
         } // Slutt p� konstrukt�ren Oblig3
         * JMenuBar metoden som gir menyen til hovedvinduet.
         * @Param menyList - Peker p� et MenuBar objekt.
         * @Param meny# - Menyene p� menylisten.
         * @Param menyObjekt - Et valg p� gitt meny.
         protected JMenuBar lagMenyList() {
              JMenuBar menyList = new JMenuBar();
              // F�rste menyen
              JMenu meny1 = new JMenu("Fil");
              meny1.setMnemonic(KeyEvent.VK_F);
              menyList.add(meny1);
                   // Gruppe1 med JMenuObjekt
                   JMenuItem menyObjekt = new JMenuItem("�pne brett", new ImageIcon("bilder/folder.gif"));
                   menyObjekt.setMnemonic(KeyEvent.VK_O);
                   menyObjekt.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, ActionEvent.CTRL_MASK));
                   menyObjekt.setActionCommand("�pne brett");
                   menyObjekt.addActionListener(this);
                   meny1.add(menyObjekt);
                   menyObjekt = new JMenuItem("Spare brett", new ImageIcon("bilder/floppy.gif"));
                   menyObjekt.setMnemonic(KeyEvent.VK_S);
                   menyObjekt.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK));
                   menyObjekt.setActionCommand("Spare brett");
                   menyObjekt.addActionListener(this);
                   meny1.add(menyObjekt);
                   meny1.addSeparator();
                   menyObjekt = new JMenuItem("Exit");
                   menyObjekt.setMnemonic(KeyEvent.VK_ESCAPE);
                   menyObjekt.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, ActionEvent.CTRL_MASK));
                   menyObjekt.setActionCommand("Exit");
                   menyObjekt.addActionListener(this);
                   meny1.add(menyObjekt);
              // Lage den andre menyen
              JMenu meny2 = new JMenu("Edit");
              meny1.setMnemonic(KeyEvent.VK_E);
              menyList.add(meny2);
                   // Gruppe2 med JMenObjekt
                   menyObjekt = new JMenuItem("L�s Brett");
                   menyObjekt.setMnemonic(KeyEvent.VK_L);
                   menyObjekt.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L, ActionEvent.CTRL_MASK));
                   menyObjekt.setActionCommand("L�s Brett");
                   menyObjekt.addActionListener(this);
                   meny2.add(menyObjekt);
                   menyObjekt = new JMenuItem("Lag eget brett");
                   menyObjekt.setMnemonic(KeyEvent.VK_L);
                   menyObjekt.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L, ActionEvent.ALT_MASK));
                   menyObjekt.setActionCommand("Lag eget brett");
                   menyObjekt.addActionListener(this);
                   meny2.add(menyObjekt);
              // Lage den tredje menyen
              JMenu meny3 = new JMenu("Hjelp");
              meny1.setMnemonic(KeyEvent.VK_H);
              menyList.add(meny3);
                   // Gruppe3 med JMenObjekt
                   menyObjekt = new JMenuItem("Version?");
                   menyObjekt.setActionCommand("Version?");
                   menyObjekt.addActionListener(this);
                   meny3.add(menyObjekt);
                   menyObjekt = new JMenuItem("www.dresas.com");
                   menyObjekt.setActionCommand("www.dresas.com?");
                   menyObjekt.addActionListener(this);
                   meny3.add(menyObjekt);
              return menyList;
         } // Slutt p� JMenuBar metoden.
         * Metode som lytter p� menyval mm.
         public void actionPerformed(ActionEvent e) {
              if(e.getActionCommand().equals("�pne brett")) {
                   lesFraFil();
              } else if (e.getActionCommand().equals("L�s Brett")) {
                   losning();
              } else if (e.getActionCommand().equals("Exit")) {
                   System.exit(0);
              } else if (e.getActionCommand().equals("Version?")) {
                   version();
              } else if (e.getActionCommand().equals("www.dresas.com")) {
                   link();
              } else if (e.getActionCommand().equals("Lag eget brett")) {
                   lagEgetBrett();
              } // Slutt p� if-else-if setning.
         * Metoden lesFraFil som ber om navn p� fil fra bruker
         * via grensesnittet.
         protected void lesFraFil() {
              final String losFraFil = JOptionPane.showInputDialog(null, "Skriv inn navn p� filen.");
              svarLesFraFil(losFraFil + ".txt");
         } // Slutt p� metoden losFraFil
         * Metoden svarLesFaFil som gir resultat p� inlesning fra fil.
         protected void svarLesFraFil(String filnavn) {
              boolean rF = br.lesBrettFraFil(filnavn);
              if(rF == true) {
                    JOptionPane.showMessageDialog(this, "Filen er lest inn");
              } else {
                    JOptionPane.showMessageDialog(this, "Filen ble ikke lest inn,\n (husk sm� og store bokstaver)");
              } // Slutt p� if-else
         } // Slutt p� metoden svarLosFraFil
         * Metoden losning som gir resultat p� l�st brett.
         protected void losning() {
              ru.provAlleSifferMegOgResten(0);
              br.skrivLosning();
         } // Slutt p� metoden losning
         protected void version() {
              JOptionPane.showMessageDialog(null, "Dette er version 0.7");
         protected void link() {
              OpenBrowser op = new OpenBrowser();
              op.displayURL("www.dresas.com");
         } // Slutt p� metoden link
         * Metoden lagEgetBrett som lar brukeren tegne sitt eget
         * brett og l�se det.
         * @Param ramme - Peker p� objektet av klassen InternRamme som
         *                setter opp det interne vinduet.
         protected void lagEgetBrett() {
              int boksBredde = 3;
              int boksHojde  = 3;
              int brettStorelse = 9;
              boolean b1 = true;
              while (b1) {
                   boksBredde = Integer.parseInt(JOptionPane.showInputDialog(null, "Skriv inn Bredde p� boksen. (2-4)"));
                   if (boksBredde > 1 && boksBredde < 5) {
                        boksHojde  = Integer.parseInt(JOptionPane.showInputDialog(null, "Skriv inn H�jde p� boksen. (3-4)"));
                        if (boksHojde > 2 && boksHojde < 5) {
                             b1 = false;
                        } else {
                             JOptionPane.showMessageDialog(null, "M� vaere mellom 3 og 4.");
                             continue;
                   } else {
                        JOptionPane.showMessageDialog(null, "M� vaere mellom 2 og 4.");
                        continue;
              brettStorelse = boksBredde * boksHojde;
              InternRamme ramme = new InternRamme(brettStorelse * 16, brettStorelse * 16);
                   Object[][] data = new Object[brettStorelse][brettStorelse];
                   for (int i = 0;i < brettStorelse;i++) {
                        for (int j = 0; j < brettStorelse;j++) {
                             data[i][j] = 0;
                   String[] columnNames = new String[brettStorelse];
                   for (int i = 0; i < brettStorelse;i++) {
                        int b = 1 + i;
                        columnNames[i] = String.valueOf(b);
                   JTable sudokuTabell = new JTable(data, columnNames);
                   sudokuTabell.setGridColor (new Color (tilfeldig(256), tilfeldig(256), tilfeldig(256)));
                   sudokuTabell.setFont(new Font ("Tahoma", Font.PLAIN, 16));
                   setVisible(true);
              ramme.add(sudokuTabell);
              ramme.setVisible(true);
              skrivebord.add(ramme);
              try {
                   ramme.setSelected(true);
              } catch (java.beans.PropertyVetoException e) {}
         } // Slutt p� klassen lagEgetBrett
         * Metode som returnerer tilfeldigt verdi st�rre en 0 og mindre
         * en maks.
         public static int tilfeldig (int maks) {
              return (int) (Math.random () * maks);
        * Metoden utsyn som tegner opp programmet p� skjermen.
        * @Param frame - Peker p� objektet Oblig3.
        private static void utsyn() {
            //Create and set up the window.
            Oblig3 frame = new Oblig3();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //Display the window.
            frame.setVisible(true);
        } // Slutt p� metoden utsyn.
        * Metoden main som starter programmet.
        public static void main(String[] args) {
              javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    utsyn();
         } //  Slutt p� metoden main.
    } // Slutt p� klassen Oblig3.
    * Brukt av Oblig3
    class InternRamme extends JInternalFrame {
         static int tellOpneRammer = 0;
         static final int xOffset = 30, yOffset = 30;
         InternRamme(int bredde, int hojde) {
              super("Lag eget Brett #" + (++tellOpneRammer),
                     true, //resizable
                     true, //closable
                     true, //maximizable
                     true);//iconifiable
              //...Create the GUI and put it in the window...
              //...Then set the window size or call pack...
              setSize(bredde,hojde);
              //Set the window's location.
              setLocation(xOffset*tellOpneRammer, yOffset*tellOpneRammer);
    }

    Here is the method in mind, translated...
    protected void ConstructOwnBoard() {
         int boxWidth = 3;
         int boxHeight = 3;
         int BoardSize = 9;
         boolean b1 = true;
         while (b1) {
              boxWidth = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter Width. (2-4)"));
              if (boxWidth > 1 && boxWidth < 5) {
                   boxHeight = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter Height. (3-4)"));
                   if (boxHeight > 2 && boxHeight < 5) {
                        b1 = false;
                   } else {
                        JOptionPane.showMessageDialog(null, "Must be btween 3 og 4.");
                        continue;
              } else {
                   JOptionPane.showMessageDialog(null, "Must be between 2 og 4.");
                   continue;
         BoardSize = boxWidth * boxHeight ;
         InternalFrame frame = new InternalFrame(BoardSize * 16, BoardSize * 16);
         Object[][] data = new Object[BoardSize ][BoardSize ];
         for (int i = 0;i < BoardSize ;i++) {
              for (int j = 0; j < BoardSize ;j++) {
                   data[i][j] = 0;
         String[] columnNames = new String[BoardSize ];
         for (int i = 0; i < BoardSize ;i++) {
              int b = 1 + i;
              columnNames[i] = String.valueOf(b);
         JTable sudokuTable = new JTable(data, columnNames);
         sudokuTable.setGridColor (new Color (tilfeldig(256), tilfeldig(256), tilfeldig(256)));
         sudokuTable.setFont(new Font ("Tahoma", Font.PLAIN, 24));
         TableColumn column = null;
         for (int i = 0; i < BoardSize ; i++) {
              column = sudokuTable.getColumnModel().getColumn(i);
              column.setMinWidth(25);
              column.setMaxWidth(25);
              column.setResizable(false);
         setVisible(true);
         frame.add(sudokuTable);
         frame.setVisible(true);
         desktop.add(ramme);
         try {
              frame.setSelected(true);
         } catch (java.beans.PropertyVetoException e) {}
    } // end of class

  • Problem printing JTable

    here is the code
    import java.awt.*;
    import java.awt.event.*;
    import java.sql.*;
    import java.util.*;
    import java.awt.print.PrinterJob;
    import java.awt.print.*;
    // Java extension packages
    import javax.swing.*;
    import javax.swing.table.*;
    class DisplayQueryResultsDOD extends JFrame implements Printable,ActionListener
    ResultSetTableModelDOD tableModel;
    JTextArea queryArea;
    JTable resultTable;
    // create ResultSetTableModel and GUI
    DisplayQueryResultsDOD()
    super( "Displaying Query Results" );
    // Cloudscape database driver class name
    String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
    // URL to connect to books database
    String url = "jdbc:odbc:MyDataSource";
    // query to select entire authors table
    String query = "SELECT * FROM person";
    // create ResultSetTableModel and display database table
         try
    // create TableModel for results of query
    // SELECT * FROM authors
              tableModel =
              new ResultSetTableModelDOD( driver, url, query );
    // set up JTextArea in which user types queries
              queryArea = new JTextArea( query, 3, 100 );
              queryArea.setWrapStyleWord( true );
              queryArea.setLineWrap( true );
              JScrollPane scrollPane = new JScrollPane( queryArea,
              ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
              ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER );
    // set up JButton for submitting queries
              JButton submitButton = new JButton( "Submit Query" );
    // create Box to manage placement of queryArea and
    Box box = Box.createHorizontalBox();
              box.add( scrollPane );
              box.add( submitButton );
    // create JTable delegate for tableModel
              JTable resultTable = new JTable( tableModel );
    // place GUI components on content pane
              Container c = getContentPane();
              c.add( box, BorderLayout.NORTH );
              c.add( new JScrollPane( resultTable ),
              BorderLayout.CENTER );
    // create event listener for submitButton
              submitButton.addActionListener(
         new ActionListener()
         public void actionPerformed( ActionEvent e )
    // perform a new query
         try
              tableModel.setQuery( queryArea.getText() );
    // catch SQLExceptions that occur when
    // performing a new query
         catch ( SQLException sqlException )
              JOptionPane.showMessageDialog( null,sqlException.toString(),"Database error",JOptionPane.ERROR_MESSAGE );
    } // end actionPerformed
    } // end ActionListener inner class
    // set window size and display window
    JMenuBar menuBar = new JMenuBar();
         JMenu filemenu= new JMenu("File");
         JMenu submenux=new JMenu("Open");
         JMenuItem np=new JMenuItem("Launch Panel");
         submenux.add(np);
         //openmenuitem.addActionListener(this);
         submenux.setActionCommand("Open");
         submenux.setMnemonic('O');
         filemenu.add(submenux);
         menuBar.add(filemenu);
         JMenuItem printItem = new JMenuItem("Print");
         printItem.setMnemonic('P');
         filemenu.add(printItem);
         JMenuItem ExitItem = new JMenuItem("Exit");
    ExitItem.setMnemonic('x');
         filemenu.add(ExitItem);
         JMenu viewmenu=new JMenu("View");
         JMenuItem repItem=new JMenuItem("Reports");
         JMenu submenu=new JMenu("sort by");
         submenu.add(new JMenuItem("Marital Status"));
    submenu.add(new JMenuItem("Rank"));
         submenu.add(new JMenuItem("Tribe"));
         submenu.add(new JMenuItem("Educational Level"));
         viewmenu.add(submenu);
         menuBar.add(viewmenu);
         setJMenuBar(menuBar);
    printItem.addActionListener(this);
         ExitItem.addActionListener
         new ActionListener()
    public void actionPerformed(ActionEvent ae)
    System.exit(0);
    setSize( 1500,900);
    // setVisible( true );
    } // end try
    // catch ClassNotFoundException thrown by
    // ResultSetTableModel if database driver not found
         catch ( ClassNotFoundException classNotFound )
         JOptionPane.showMessageDialog( null,"Cloudscape driver not found", "Driver not found",JOptionPane.ERROR_MESSAGE );
              System.exit( 1 ); // terminate application
    // catch SQLException thrown by ResultSetTableModel
    // if problems occur while setting up database
    // connection and querying database
         catch ( SQLException sqlException )
         JOptionPane.showMessageDialog( null,sqlException.toString(),"Database error", JOptionPane.ERROR_MESSAGE );
         System.exit( 1 ); // terminate application
    } // end DisplayQueryResults constructor
         public void actionPerformed(ActionEvent e)
    PrinterJob printJob = PrinterJob.getPrinterJob();
    printJob.setPrintable(this);
    if (printJob.printDialog())
    try
    printJob.print();
    catch (Exception ex)
    ex.printStackTrace();
         public int print(Graphics g, PageFormat pf, int page) throws
    PrinterException {
    if (page > 0) { /* We have only one page, and 'page' is zero-based */
    return NO_SUCH_PAGE;
    /* User (0,0) is typically outside the imageable area, so we must
    * translate by the X and Y values in the PageFormat to avoid clipping
    Graphics2D g2d = (Graphics2D)g;
    g2d.translate(pf.getImageableX(), pf.getImageableY());
    /* Now print the window and its visible contents */
    resultTable.printAll(g);
    /* tell the caller that this page is part of the printed document */
    return PAGE_EXISTS;
    // execute application
    public static void main( String args[] )
    DisplayQueryResultsDOD app = new DisplayQueryResultsDOD();
    app.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
    } // end class DisplayQueryResults
    I get an exception
    pls help

    I included this statement only to check if it would print or not, because before that I tried printing the table without setting the size. Anyway, when I tried the same code under Windows it worked fine. Talking about platform independent...:-)

  • How to add a JMenubar and a JTable in a JFrame in a single application

    Hi all,
    I require an urgent help from you.I am a beginer in programming Swing.I want to add a menu,combobox,and a table in a single application.I did coding as below:
    package com.BSS;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.border.*;
    import javax.swing.event.*;
    public class newssa extends JFrame
         public JMenuBar menuBar;
         public JToolBar toolBar;
         public JFrame frame;
         private JLabel jLabel1;
         private JLabel jLabel2;
         private JLabel jLabel3;
         private JLabel jLabel4;
         private JLabel jLabel5;
         private JLabel jLabel6;
         private JComboBox jComboBox1;
         private JComboBox jComboBox2;
         private JComboBox jComboBox3;
         private JComboBox jComboBox4;
         private JComboBox jComboBox5;
         private JComboBox jComboBox6;
         private JTable jTable1;
         private JScrollPane jScrollPane1;
         private JPanel contentPane;
         public newssa()
              super();
              initializeComponent();
              this.setVisible(true);
         private void initializeComponent()
              jLabel1 = new JLabel();
              jLabel2 = new JLabel();
              jLabel3 = new JLabel();
              jLabel4 = new JLabel();
              jLabel5 = new JLabel();
              jLabel6 = new JLabel();
              jComboBox1 = new JComboBox();
              jComboBox2 = new JComboBox();
              jComboBox3 = new JComboBox();
              jComboBox4 = new JComboBox();
              jComboBox5 = new JComboBox();
              jComboBox6 = new JComboBox();
              frame=new JFrame();
              //Included here
              JMenuBar menuBar = new JMenuBar();
              JMenu general = new JMenu("General");
         menuBar.add(general);
         JMenu actions =new JMenu("Actions");
         menuBar.add(actions);
         JMenu view=new JMenu("View");
         menuBar.add(view);
         JMenu Timescale=new JMenu("TimeScale");
         menuBar.add(Timescale);
         Timescale.add("Today CTRL+D");
         Timescale.add("Current Week CTRL+W");
         Timescale.add("Current Month CTRL+M");
         Timescale.add("Current Quarter CTRL+Q");
         Timescale.add("Current Year CTRL+Y");
         Timescale.add("Custom TimeScale CTRL+U");
         JMenu start=new JMenu("Start");
         menuBar.add(start);
         JMenu options=new JMenu("Options");
         menuBar.add(options);
         JMenu help=new JMenu("Help");
         menuBar.add(help);
         JFrame.setDefaultLookAndFeelDecorated(true);
         frame.setJMenuBar(menuBar);
         frame.pack();
         frame.setVisible(true);
         toolBar = new JToolBar("Formatting");
         toolBar.addSeparator();
              //Before this included new
              String columnNames[] = { "ColorStatus", "Flash", "Service Order","Configuration","Configuration Description"};
              // Create some data
              String dataValues[][] =
                   { "blue", "flash", "ORT001" },
                   { "AVCONF", "av configuration with warrenty"}
              // Create a new table instance
              //jTable1 = new JTable( dataValues, columnNames );
              jTable1 = new JTable(dataValues,columnNames);
              jScrollPane1 = new JScrollPane(jTable1);
              contentPane = (JPanel)this.getContentPane();
              //scrollPane = new JScrollPane( table );
              //topPanel.add( scrollPane, BorderLayout.CENTER );
              // jLabel1
              jLabel1.setText("Service Centers");
              // jLabel2
              jLabel2.setText("Service Areas");
              // jLabel4
              jLabel3.setText("Skills");
              jLabel4.setText("Availablity Types");
              // jLabel5
              jLabel5.setText("From Date");
              // jLabel6
              jLabel6.setText("To");
              // jComboBox1
              jComboBox1.addItem("Coimbatore");
              jComboBox1.addItem("Chennai");
              jComboBox1.addItem("Mumbai");
              jComboBox1.addItem("New Delhi");
              jComboBox1.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e)
                        jComboBox1_actionPerformed(e);
              // jComboBox2
              jComboBox2.addItem("North Zone");
              jComboBox2.addItem("South Zone");
              jComboBox2.addItem("Central Zone");
              jComboBox2.addItem("Eastern Zone");
              jComboBox2.addItem("Western Zone");
              jComboBox2.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e)
                        jComboBox2_actionPerformed(e);
              // jComboBox3
              jComboBox3.addItem("Microsoft Components");
              jComboBox3.addItem("Java Technologies");
              jComboBox3.addItem("ERP");
              jComboBox3.addItem("Others");
              jComboBox3.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e)
                        jComboBox3_actionPerformed(e);
              // jComboBox4
              jComboBox4.addItem("One");
              jComboBox4.addItem("Two");
              jComboBox4.addItem("Three");
              jComboBox4.addItem("Four");
              jComboBox4.addItem("Five");
              jComboBox4.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e)
                        jComboBox4_actionPerformed(e);
              // jComboBox5
              jComboBox5.addItem("12/12/2004");
              jComboBox5.addItem("13/12/2004");
              jComboBox5.addItem("14/12/2004");
              jComboBox5.setEditable(true);
              jComboBox5.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e)
                        jComboBox5_actionPerformed(e);
              // jComboBox6
              jComboBox6.addItem("12/11/2004");
              jComboBox6.addItem("13/11/2004");
              jComboBox6.addItem("14/11/2004");
              jComboBox6.setEditable(true);
              jComboBox6.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e)
                        jComboBox6_actionPerformed(e);
              // jTable1
              jTable1.setModel(new DefaultTableModel(4, 4));
              // jScrollPane1
              jScrollPane1.setViewportView(jTable1);
              // contentPane
              contentPane.setLayout(null);
              addComponent(contentPane, jLabel1, 2,29,84,18);
              addComponent(contentPane, jLabel2, 201,33,76,18);
              addComponent(contentPane, jLabel3, 384,32,59,18);
              addComponent(contentPane, jLabel4, 2,77,85,18);
              addComponent(contentPane, jLabel5, 197,79,84,18);
              addComponent(contentPane, jLabel6, 384,80,60,18);
              addComponent(contentPane, jComboBox1, 85,32,100,22);
              addComponent(contentPane, jComboBox2, 276,32,100,22);
              addComponent(contentPane, jComboBox3, 419,30,100,22);
              addComponent(contentPane, jComboBox4, 88,76,100,22);
              addComponent(contentPane, jComboBox5, 276,79,100,22);
              addComponent(contentPane, jComboBox6, 421,78,100,22);
              addComponent(contentPane, jScrollPane1, 33,158,504,170);
              // newssa
              this.setTitle("SSA Service Scheduler");
              this.setLocation(new Point(0, 0));
              this.setSize(new Dimension(560, 485));
         /** Add Component Without a Layout Manager (Absolute Positioning) */
         private void addComponent(Container container,Component c,int x,int y,int width,int height)
              c.setBounds(x,y,width,height);
              container.add(c);
         // TODO: Add any appropriate code in the following Event Handling Methods
         private void jComboBox1_actionPerformed(ActionEvent e)
              int index = jComboBox1.getSelectedIndex();
              switch(index)
                   case 0: System.out.println("Area Coimbatore Selected "); break;
                   case 1: System.out.println("Area Chennai selected"); break;
                   case 2: System.out.println("Mumbai being selected"); break;
                   case 3: System.out.println("New Delhi being selected"); break;
         private void jComboBox2_actionPerformed(ActionEvent e)
              int index = jComboBox2.getSelectedIndex();
              switch(index)
                   case 0: System.out.println("North Zone Selcted "); break;
                   case 1: System.out.println("South Zone being selected"); break;
                   case 2: System.out.println("Central Zone being selected"); break;
                   case 3: System.out.println("Eastern Zone being selected"); break;
                   case 4: System.out.println("Western Zone being selected"); break;
         private void jComboBox3_actionPerformed(ActionEvent e)
              int index = jComboBox3.getSelectedIndex();
              switch(index)
                   case 0: System.out.println("Microsoft Components being selected"); break;
                   case 1: System.out.println("Java Technologies being selected"); break;
                   case 2: System.out.println("ERP Tehnologies being selected"); break;
                   case 3: System.out.println("Other's selected"); break;
         private void jComboBox4_actionPerformed(ActionEvent e)
              int index = jComboBox4.getSelectedIndex();
              switch(index)
                   case 0: System.out.println("One selected"); break;
                   case 1: System.out.println("Two selected"); break;
                   case 2: System.out.println("Three selected"); break;
                   case 3: System.out.println("Four selected"); break;
                   case 4: System.out.println("Five selected"); break;
         private void jComboBox5_actionPerformed(ActionEvent e)
              int index = jComboBox5.getSelectedIndex();
              switch(index)
                   case 0: System.out.println("12/12/2004 being selected"); break;
                   case 1: System.out.println("13/12/2004 being selected"); break;
                   case 2: System.out.println("14/12/2004 being selected"); break;
         private void jComboBox6_actionPerformed(ActionEvent e)
              int index = jComboBox6.getSelectedIndex();
              switch(index)
                   case 0: System.out.println("12/11/2004 being selected"); break;
                   case 1: System.out.println("13/11/2004 being selected"); break;
                   case 2: System.out.println("14/11/2004 being selected"); break;
         public static void main(String[] args)
              newssa ssa=new newssa();
              //JFrame.setDefaultLookAndFeelDecorated(true);
              //JDialog.setDefaultLookAndFeelDecorated(true);
              //JFrame frame = new JFrame("SSA Service Scheduler");
    //frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //frame.setJMenuBar(ssa.menuBar);
    //frame.getContentPane( ).add(ssa.toolBar, BorderLayout.NORTH);
    //frame.getContentPane( ).add(ssa.pane, BorderLayout.CENTER);
    //frame.pack( );
    //frame.setVisible(true);
              try
                   //UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
                   UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
              catch (Exception ex)
                   System.out.println("Failed loading L&F: ");
                   System.out.println(ex);
    But as a O/P ,I am getting menu in a seperate windos and the rest of the combobox and jtable in a seperate window.Kindly help me to solve the application.
    VERY URGENT PLEASE..
    Thanks in advance
    with kind regds
    Satheesh.K

    But did u mean this as the next problem,Which I will come across..Yes, the second setVisible(true) seemed to be producing a smaller frame behind the main frame.
    And your JMenuBar is declared twice, but not sure if this will affect the code - haven't read it all.

  • Creating a new row in a JTable

    How do i make a new row in a JTabel?

    is there a line something like: newRow(); but anyway here is the code i have so far thanx for the help:
    class UserSettings extends JFrame implements ActionListener {
      private JMenuBar menu = new JMenuBar();
      private JMenu Settings;
      private JMenuItem exit;
      private JButton sset;
      String[] columnNames = {"users","passwords"};
      Vector dat = new Vector();
      private JTable usertable;
      public UserSettings() {
        setSize(new Dimension(350, 350));
        setTitle("User Setings");
        Settings = new JMenu("Settings");
        menu.add(Settings);
        exit = new JMenuItem("Exit");
        exit.addActionListener(this);
        Settings.add(exit);
        sset = new JButton("Save settings");
        sset.addActionListener(this);
        try {
          BufferedReader userin = new BufferedReader(new FileReader("users/userp.txt"));
          String su;
          while ((su = userin.readLine()) != null) {
            String[] uspa = su.split(" ");
            dat.add(uspa);
        catch (FileNotFoundException ioe) {
          JOptionPane.showMessageDialog(null, "Iternal Error, contact [email protected] if the error persists", "", JOptionPane.WARNING_MESSAGE);
        catch (ClassCastException ioe){}
        catch (NullPointerException ioe) {}
        catch (IOException ioe) {
          JOptionPane.showMessageDialog(null, "Iternal Error, contact [email protected] if the error persists", "", JOptionPane.WARNING_MESSAGE);
        String[][] data = new String[dat.size()][];
        for(int x = 0; x < dat.size(); x++) {
          data[x] = (String[])dat.get(x);
        usertable = new JTable(data, columnNames);
        JScrollPane scrollpane = new JScrollPane(usertable);
        usertable.setPreferredScrollableViewportSize(new Dimension(50, 500));
        JPanel pane = new JPanel(new GridLayout(0, 1));
        getContentPane().add(scrollpane);
        getContentPane().add(sset, BorderLayout.SOUTH);
        setJMenuBar(menu);
      public void actionPerformed(ActionEvent e) {
        if (e.getSource() == sset) {
             int count = usertable.getRowCount();
             if (count == 1) {
             if (count == 2) {
             if (count == 3) {
          try {
               FileWriter uname = new FileWriter("users/usertest.txt");
               String sname;
               uname.write("test");
               uname.close();
          catch (IOException ioe) {
               JOptionPane.showMessageDialog(null, "Error saving you file, if error persists contact [email protected] or reenstal", "", JOptionPane.WARNING_MESSAGE);
          dispose();
        if (e.getSource() == exit) {
          int exitask = JOptionPane.showConfirmDialog(UserSettings.this, "Are you sure you want to exit? Any unsaved settinging changes will be lost!!");
          if (exitask == JOptionPane.YES_OPTION) {
            dispose();
    Thanx again

  • Add and remove columns from JTable

    Help me please!
    A try to remove column from JTable. It's removed, but when I try to add column in table, then I get all old (removed early) columns + new column....
    I completely confused with it.....
    Here is my code for remove column:
    class DelC implements ActionListener
              public void actionPerformed (ActionEvent e )
                   int [] HowManyColDelete = table.getSelectedColumns();
                   if (HowManyColDelete.length !=0)
                        TableColumnModel tableCModel = table.getColumnModel();
                        for (int i = HowManyColDelete.length-1; i>-1; i--)
                             table.getColumnModel().removeColumn (tableCModel.getColumn (HowManyColDelete [ i ]));
                   else
                          JOptionPane.showMessageDialog(JOptionPane.getRootFrame(), "Column is not selected!");
         }

    It's little ex for me, I just try understand clearly how it's work (table models i mean). Here is code. All action with tables take place through menu items.
    My brain is boiled, I've try a lot of variants of code, but did't get right result :((
    It's code represent problem, which I've describe above. If you'll try remove column and then add it again, it will be ma-a-a-any colunms...
    I understand, that my code just hide columns, not delete from table model....
    But now I have not any decision of my problem...
    Thanks a lot for any help. :)
    import javax.swing.*;
    import java.awt.*;
    import javax.swing.table.*;
    import java.awt.event.*;
    import javax.swing.table.DefaultTableModel;
    class JTableF extends JFrame
         Object [] [] data = new Object [0] [2];
         JTable table;
         DefaultTableModel model;
         String [] columnNames = {"1", "2"};
         TableColumnModel cm;
         JTableF()
              super("Table features");
              setDefaultLookAndFeelDecorated( true );
              setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
              JMenuBar MBar = new JMenuBar();
              JMenu [] menus =  {new JMenu("A"), new JMenu("B")};
              JMenuItem [] menu1 =  {new JMenuItem("Add row"), new JMenuItem("Delete row", 'D'),  new JMenuItem("Add column"), new JMenuItem("Delete column")};
              menu1 [ 0 ].addActionListener(new AddL());
              menu1 [ 1 ].addActionListener(new DelL());
              menu1 [ 2 ].addActionListener(new AddC());
              menu1 [ 3 ].addActionListener(new DelC());
              for (int i=0; i<menu1.length; i++)
                   menus [ 0 ].add( menu1 [ i ]);
              for (int i=0; i<menus.length; i++)
                   MBar.add(menus );
              JPanel panel = new JPanel ();
              model = new DefaultTableModel( data, columnNames );
              table = new JTable (model);
              cm = table.getColumnModel();
              panel.add (new JScrollPane(table));
              JButton b = new JButton ("Add row button");
              b.addActionListener(new AddL());
              panel.add (b);
              setJMenuBar (MBar);
              getContentPane().add(panel);
              pack();
              setLocationRelativeTo (null);
              setVisible (true);
         class DelC implements ActionListener
              public void actionPerformed (ActionEvent e )
                   int [] HowManyColDelete = table.getSelectedColumns();
                   if (HowManyColDelete.length !=0)
                        TableColumnModel tableCModel = table.getColumnModel();
                        for (int i = HowManyColDelete.length-1; i>-1; i--)
                             int vizibleCol = table.convertColumnIndexToView(HowManyColDelete [ i ]);
                             tableCModel.removeColumn (tableCModel.getColumn (vizibleCol));
                        //cm = tableCModel;
                   else
                        JOptionPane.showMessageDialog(JOptionPane.getRootFrame(), "Column is not selected!");
         class AddC implements ActionListener
              public void actionPerformed (ActionEvent e)
                   //table.setColumnModel(cm);
                   Object NewColumnName = new String();
                   NewColumnName = JOptionPane.showInputDialog ("Input new column name", "Here");
                   int i = model.getRowCount();
                   int j = model.getColumnCount();
                   Object [] newData = new Object [ i ];
                   model.addColumn ( NewColumnName, newData);
         class AddL implements ActionListener
              public void actionPerformed (ActionEvent e)
                   int i = model.getColumnCount();
                   Object [] Row = new Object [ i ];
                   model.addRow ( Row );
         class DelL implements ActionListener
              public void actionPerformed (ActionEvent e)
                   int [] HowManyRowsDelete = table.getSelectedRows();
                   if (HowManyRowsDelete.length !=0)
                        for (int k = HowManyRowsDelete.length-1; k>-1; k--)
                             model.removeRow (HowManyRowsDelete[k]);
                   else
                        JOptionPane.showMessageDialog(JOptionPane.getRootFrame(), "Row is not selected!");
         public static void main (String [] args)
              javax.swing.SwingUtilities.invokeLater(new Runnable()
                   public void run()
                        JTableF inst = new JTableF();

  • How do i update a JTable with new data?

    Hey
    I have a JTable where the data of some football players are shown. Name, club, matches and goals. What i want is to change the data in
    the JTable when i click a button. For example each team in a league has its own button, so when i click the teams button, JTable has
    data of that teams players.
    Here is the code i have atm, there isnt anything on how to change the data, because i dont know where to start, plz point me in somekind of direction:
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    package test;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.JMenu;
    import javax.swing.JMenuItem;
    import javax.swing.JMenuBar;
    import javax.swing.ImageIcon;
    import javax.swing.JTable;
    import javax.swing.JButton;
    import javax.swing.JTextArea;
    import javax.swing.JScrollPane;
    import javax.swing.JPanel;
    import javax.swing.JFrame;
    * @author Jesper
    public class Main extends JFrame implements ActionListener {
        private Players players;
        private JTextArea output;
        private JScrollPane scrollPane2;
        private JButton button1, button2;
        private String newline = "\n";
        private int club = 1;
        public Main(){
            players = new Players();
        public JMenuBar createMenuBar(){
            JMenuBar menuBar = new JMenuBar();
            JMenu menu = new JMenu("File");
            menu.setMnemonic(KeyEvent.VK_A);
            menu.getAccessibleContext().setAccessibleDescription("The only menu in this program that has menu items");
            menuBar.add(menu);
            // add menuitems/buttons
            JMenuItem menuItemNew   = new JMenuItem("new");
            menuItemNew.setActionCommand("1");
            menuItemNew.addActionListener(this);       
            JMenuItem menuItemOpen   = new JMenuItem("Open");
            JMenuItem menuItemQuit   = new JMenuItem("Quit");
            menuItemQuit.setActionCommand("2");
            menuItemQuit.addActionListener(this);
            // add to menu
            menu.add(menuItemNew);
            menu.add(menuItemOpen);
            menu.add(menuItemQuit);
            return menuBar;
        public void actionPerformed(ActionEvent e){
            String s;
            if ("Silkeborg IF".equals(e.getActionCommand())){
                club = 1;
                s = e.getActionCommand();
                output.append(s + newline);
                button1.setEnabled(false);
                button2.setEnabled(true);
            } else{
                club = 2;
                s = e.getActionCommand();
                output.append(s + newline);
                button1.setEnabled(true);
                button2.setEnabled(false);
        //Quit the application.
        protected void quit() {
            System.exit(0);
        public Container createContent(){
            JPanel contentPane = new JPanel(new GridLayout(3,1));
            ImageIcon icon = createImageIcon("middle.gif", "a pretty but meaningless splat");
            JTable table = new JTable(players.showPlayers(club));
            //Create the first label.
            button1 = new JButton("Silkeborg IF");
            button1.setToolTipText("Klik her for at se Silkeborg IF");
            button1.addActionListener(this);
            button1.setActionCommand("Silkeborg IF");
            //Create the second label.
            button2 = new JButton("FC Midtjylland");
            button2.setToolTipText("Klik her for at se FC Midtjylland");
            button2.addActionListener(this);
            button2.setActionCommand("FC Midtjylland");
            //Create a scrolled text area.
            output = new JTextArea(5, 30);
            output.setEditable(false);
            scrollPane2 = new JScrollPane(output);
            //Add stuff to contentPane.
            contentPane.add(button1);
            contentPane.add(button2);
            contentPane.add(table);
            contentPane.add(scrollPane2, BorderLayout.CENTER);
            return contentPane;
        protected static ImageIcon createImageIcon(String path,
                                                   String description) {
            java.net.URL imgURL = Main.class.getResource(path);
            if (imgURL != null) {
                return new ImageIcon(imgURL, description);
            } else {
                System.err.println("Couldn't find file: " + path);
                return null;
        public static void createGUI(){
            JFrame frame = new JFrame();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            Main main = new Main();
            frame.setJMenuBar(main.createMenuBar());
            frame.setContentPane(main.createContent());
            frame.setSize(500, 500);
            frame.setVisible(true);
         * @param args the command line arguments
        public static void main(String[] args) {
            createGUI();
    }

    ooohh sorry... i posted the wrong code :S
    Here is the correct code:
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    package test;
    import java.util.HashMap;
    import java.util.Set;
    import javax.swing.table.*;
    * @author Jesper
    public class Players {
        HashMap<Player, Stats> players;
        public Players(){
            players = new HashMap<Player, Stats>();
            addPlayer();
        public void addPlayer(){
            //Silkeborg IF
            players.put(new Player("Martin ?rnskov", 1), new Stats(19, 3, 1));
            players.put(new Player("Thomas Raun", 1), new Stats(23, 6, 0));
            players.put(new Player("Jimmy Mayasi", 1), new Stats(26, 26, 3));
            players.put(new Player("Lasse J?rgensen", 1), new Stats(33, 0, 0));
            //FC Midtjylland
            players.put(new Player("Frank Kristensen", 2), new Stats(19, 3, 1));
            players.put(new Player("Thomas R?ll", 2), new Stats(23, 6, 0));
            players.put(new Player("Simon Poulsen", 2), new Stats(26, 26, 3));
            players.put(new Player("Magnus Troels", 2), new Stats(33, 0, 0));
        public DefaultTableModel showPlayers(int club){
            String[] columNames = {"Spiller", "Klub", "Kampe", "M?l", "R?de kort"};
            //Object[][] data = {{"Martin ?rnskov", 19, 3, 1}, {"Thomas Raun", 23, 6, 0}};
            Set<Player> keys = players.keySet();
            Object[][] data = new Object[keys.size()][columNames.length];
            int i = 0;
            for(Player player : keys){
               if(player.getClub() == club){
                   data[0] = player.getName();
    data[i][1] = player.getClub();
    data[i][2] = players.get(player).getMatches();
    data[i][3] = players.get(player).getGoals();
    data[i][4] = players.get(player).getRedCards();
    i++;
    DefaultTableModel table = new DefaultTableModel(data, columNames);
    return table;

  • Returning index of selected comp... jComboBox that is editing a jTable cell

    so, i'm using an array to populate the choices of a combobox
        public String[] progCodes = new String[]{"Standard","Restricted","Combined","Special"};which i'm using to edit a cell in a jtable
    baseCatTable.getColumnModel().getColumn(4).setCellEditor(new DefaultCellEditor(new JComboBox(progCodes)));and when i get the value
    System.out.println(baseCatTable.getValueAt(0, 4))i'd like to return the index of the selected item in the combo box instead of the text:
    Standard
    any suggestions?
    Edited by: hansbig on Jan 24, 2008 5:04 PM

    sorry, but i'm using an IDE and it generates a lot of fluffy code.
    * ProblemView.java
    package problem;
    import org.jdesktop.application.Action;
    import org.jdesktop.application.ResourceMap;
    import org.jdesktop.application.SingleFrameApplication;
    import org.jdesktop.application.FrameView;
    import org.jdesktop.application.TaskMonitor;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.DefaultCellEditor;
    import javax.swing.Timer;
    import javax.swing.Icon;
    import javax.swing.JComboBox;
    import javax.swing.JDialog;
    import javax.swing.JFrame;
    * The application's main frame.
    public class ProblemView extends FrameView {
        public ProblemView(SingleFrameApplication app) {
            super(app);
            initComponents();
            edit = new JComboBox(words);
            // status bar initialization - message timeout, idle icon and busy animation, etc
            ResourceMap resourceMap = getResourceMap();
            int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout");
            messageTimer = new Timer(messageTimeout, new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    statusMessageLabel.setText("");
            messageTimer.setRepeats(false);
            int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate");
            for (int i = 0; i < busyIcons.length; i++) {
                busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]");
            busyIconTimer = new Timer(busyAnimationRate, new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    busyIconIndex = (busyIconIndex + 1) % busyIcons.length;
                    statusAnimationLabel.setIcon(busyIcons[busyIconIndex]);
            idleIcon = resourceMap.getIcon("StatusBar.idleIcon");
            statusAnimationLabel.setIcon(idleIcon);
            progressBar.setVisible(false);
            // connecting action tasks to status bar via TaskMonitor
            TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext());
            taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
                public void propertyChange(java.beans.PropertyChangeEvent evt) {
                    String propertyName = evt.getPropertyName();
                    if ("started".equals(propertyName)) {
                        if (!busyIconTimer.isRunning()) {
                            statusAnimationLabel.setIcon(busyIcons[0]);
                            busyIconIndex = 0;
                            busyIconTimer.start();
                        progressBar.setVisible(true);
                        progressBar.setIndeterminate(true);
                    } else if ("done".equals(propertyName)) {
                        busyIconTimer.stop();
                        statusAnimationLabel.setIcon(idleIcon);
                        progressBar.setVisible(false);
                        progressBar.setValue(0);
                    } else if ("message".equals(propertyName)) {
                        String text = (String)(evt.getNewValue());
                        statusMessageLabel.setText((text == null) ? "" : text);
                        messageTimer.restart();
                    } else if ("progress".equals(propertyName)) {
                        int value = (Integer)(evt.getNewValue());
                        progressBar.setVisible(true);
                        progressBar.setIndeterminate(false);
                        progressBar.setValue(value);
        @Action
        public void showAboutBox() {
            if (aboutBox == null) {
                JFrame mainFrame = ProblemApp.getApplication().getMainFrame();
                aboutBox = new ProblemAboutBox(mainFrame);
                aboutBox.setLocationRelativeTo(mainFrame);
            ProblemApp.getApplication().show(aboutBox);
        /** 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() {
            mainPanel = new javax.swing.JPanel();
            jScrollPane1 = new javax.swing.JScrollPane();
            jTable1 = new javax.swing.JTable();
            jButton1 = new javax.swing.JButton();
            menuBar = new javax.swing.JMenuBar();
            javax.swing.JMenu fileMenu = new javax.swing.JMenu();
            javax.swing.JMenuItem exitMenuItem = new javax.swing.JMenuItem();
            javax.swing.JMenu helpMenu = new javax.swing.JMenu();
            javax.swing.JMenuItem aboutMenuItem = new javax.swing.JMenuItem();
            statusPanel = new javax.swing.JPanel();
            javax.swing.JSeparator statusPanelSeparator = new javax.swing.JSeparator();
            statusMessageLabel = new javax.swing.JLabel();
            statusAnimationLabel = new javax.swing.JLabel();
            progressBar = new javax.swing.JProgressBar();
            mainPanel.setName("mainPanel"); // NOI18N
            jScrollPane1.setName("jScrollPane1"); // NOI18N
            jTable1.setModel(new javax.swing.table.DefaultTableModel(
                new Object [][] {
                    {null}
                new String [] {
                    "Title 1"
            jTable1.setColumnSelectionAllowed(true);
            jTable1.setName("jTable1"); // NOI18N
            jScrollPane1.setViewportView(jTable1);
            jTable1.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
            jTable1.getColumnModel().getColumn(0).setCellEditor(new DefaultCellEditor(edit));
            org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(problem.ProblemApp.class).getContext().getResourceMap(ProblemView.class);
            jButton1.setText(resourceMap.getString("jButton1.text")); // NOI18N
            jButton1.setName("jButton1"); // NOI18N
            jButton1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton1ActionPerformed(evt);
            javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
            mainPanel.setLayout(mainPanelLayout);
            mainPanelLayout.setHorizontalGroup(
                mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(mainPanelLayout.createSequentialGroup()
                    .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(mainPanelLayout.createSequentialGroup()
                            .addContainerGap()
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 166, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(mainPanelLayout.createSequentialGroup()
                            .addGap(46, 46, 46)
                            .addComponent(jButton1)))
                    .addContainerGap(12, Short.MAX_VALUE))
            mainPanelLayout.setVerticalGroup(
                mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(mainPanelLayout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(18, 18, 18)
                    .addComponent(jButton1)
                    .addContainerGap(18, Short.MAX_VALUE))
            menuBar.setName("menuBar"); // NOI18N
            fileMenu.setText(resourceMap.getString("fileMenu.text")); // NOI18N
            fileMenu.setName("fileMenu"); // NOI18N
            javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(problem.ProblemApp.class).getContext().getActionMap(ProblemView.class, this);
            exitMenuItem.setAction(actionMap.get("quit")); // NOI18N
            exitMenuItem.setName("exitMenuItem"); // NOI18N
            fileMenu.add(exitMenuItem);
            menuBar.add(fileMenu);
            helpMenu.setText(resourceMap.getString("helpMenu.text")); // NOI18N
            helpMenu.setName("helpMenu"); // NOI18N
            aboutMenuItem.setAction(actionMap.get("showAboutBox")); // NOI18N
            aboutMenuItem.setName("aboutMenuItem"); // NOI18N
            helpMenu.add(aboutMenuItem);
            menuBar.add(helpMenu);
            statusPanel.setName("statusPanel"); // NOI18N
            statusPanelSeparator.setName("statusPanelSeparator"); // NOI18N
            statusMessageLabel.setName("statusMessageLabel"); // NOI18N
            statusAnimationLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
            statusAnimationLabel.setName("statusAnimationLabel"); // NOI18N
            progressBar.setName("progressBar"); // NOI18N
            javax.swing.GroupLayout statusPanelLayout = new javax.swing.GroupLayout(statusPanel);
            statusPanel.setLayout(statusPanelLayout);
            statusPanelLayout.setHorizontalGroup(
                statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(statusPanelSeparator, javax.swing.GroupLayout.DEFAULT_SIZE, 188, Short.MAX_VALUE)
                .addGroup(statusPanelLayout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(statusMessageLabel)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 14, Short.MAX_VALUE)
                    .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(statusAnimationLabel)
                    .addContainerGap())
            statusPanelLayout.setVerticalGroup(
                statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(statusPanelLayout.createSequentialGroup()
                    .addComponent(statusPanelSeparator, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(statusMessageLabel)
                        .addComponent(statusAnimationLabel)
                        .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGap(3, 3, 3))
            setComponent(mainPanel);
            setMenuBar(menuBar);
            setStatusBar(statusPanel);
        }// </editor-fold>
        private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
            System.out.println(jTable1.getValueAt(0, 0));
            System.out.println(edit.getSelectedIndex());
        // Variables declaration - do not modify
        private javax.swing.JButton jButton1;
        private javax.swing.JScrollPane jScrollPane1;
        private javax.swing.JTable jTable1;
        private javax.swing.JPanel mainPanel;
        private javax.swing.JMenuBar menuBar;
        private javax.swing.JProgressBar progressBar;
        private javax.swing.JLabel statusAnimationLabel;
        private javax.swing.JLabel statusMessageLabel;
        private javax.swing.JPanel statusPanel;
        // End of variables declaration
        public String[] words = new String[]{"one","two"};
        public JComboBox edit;
        private final Timer messageTimer;
        private final Timer busyIconTimer;
        private final Icon idleIcon;
        private final Icon[] busyIcons = new Icon[15];
        private int busyIconIndex = 0;
        private JDialog aboutBox;
    * ProblemApp.java
    package problem;
    import org.jdesktop.application.Application;
    import org.jdesktop.application.SingleFrameApplication;
    * The main class of the application.
    public class ProblemApp extends SingleFrameApplication {
         * At startup create and show the main frame of the application.
        @Override protected void startup() {
            show(new ProblemView(this));
         * This method is to initialize the specified window by injecting resources.
         * Windows shown in our application come fully initialized from the GUI
         * builder, so this additional configuration is not needed.
        @Override protected void configureWindow(java.awt.Window root) {
         * A convenient static getter for the application instance.
         * @return the instance of ProblemApp
        public static ProblemApp getApplication() {
            return Application.getInstance(ProblemApp.class);
         * Main method launching the application.
        public static void main(String[] args) {
            launch(ProblemApp.class, args);
    }i'm getting:
    init:
    deps-jar:
    Compiling 1 source file to C:\Documents and Settings\1\My Documents\NetBeansProjects\problem\build\classes
    compile:
    run:
    Jan 24, 2008 7:58:36 PM org.jdesktop.application.Application$1 run
    SEVERE: Application class problem.ProblemApp failed to launch
    java.lang.NullPointerException
    at javax.swing.DefaultCellEditor.<init>(DefaultCellEditor.java:117)
    at problem.ProblemView.initComponents(ProblemView.java:136)
    at problem.ProblemView.<init>(ProblemView.java:29)
    at problem.ProblemApp.startup(ProblemApp.java:19)
    at org.jdesktop.application.Application$1.run(Application.java:171)
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:597)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:173)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:121)
    Exception in thread "AWT-EventQueue-0" java.lang.Error: Application class problem.ProblemApp failed to launch
    at org.jdesktop.application.Application$1.run(Application.java:177)
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:597)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:173)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:121)
    Caused by: java.lang.NullPointerException
    at javax.swing.DefaultCellEditor.<init>(DefaultCellEditor.java:117)
    at problem.ProblemView.initComponents(ProblemView.java:136)
    at problem.ProblemView.<init>(ProblemView.java:29)
    at problem.ProblemApp.startup(ProblemApp.java:19)
    at org.jdesktop.application.Application$1.run(Application.java:171)
    ... 8 more
    BUILD SUCCESSFUL (total time: 2 seconds)
    also, I made a zip file of the project and put it up here:
    http://www.geocities.com/hansbigtree/problem.zip
    thanks.

  • Problem reading .txt-file into JTable

    My problem is that I�m reading a .txt-file into a J-Table. It all goes okay, the FileChooser opens and the application reads the selected file (line). But then I get a Null Pointer Exception and the JTable does not get updated with the text from the file.
    Here�s my code (I kept it simple, and just want to read the text from the .txt-file to the first cell of the table.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    import java.util.*;
    import java.lang.*;
    import java.io.*;
    public class TeamTable extends JFrame implements ActionListener, ItemListener                {
    static JTable table;
         // constructor
    public TeamTable()                {
    super( "Invoermodule - Team Table" );
    setSize( 740, 365 );
              // setting the rownames
    ListModel listModel = new AbstractListModel()                     {
    String headers[] = {"Team 1", "Team 2", "Team 3", "Team 4", "Team 5", "Team 6", "Team 7", "Team 8", "Team 9",
    "Team 10", "Team 11", "Team 12", "Team 13", "Team 14", "Team 15", "Team 16", "Team 17", "Team 18"};
    public int getSize() { return headers.length; }
    public Object getElementAt(int index) { return headers[index]; }
              // add listModel & rownames to the table
              DefaultTableModel defaultModel = new DefaultTableModel(listModel.getSize(),3);
              JTable table = new JTable( defaultModel );
              // setting the columnnames and center alignment of table cells
              int width = 200;
              int[] vColIndex = {0,1,2};
              String[] ColumnName = {"Name Team", "Name Chairman", "Name Manager"};
              TableCellRenderer centerRenderer = new CenterRenderer();          
              for (int i=0; i < vColIndex.length;i++)          {
                             table.getColumnModel().getColumn(vColIndex).setHeaderValue(ColumnName[i]);
                             table.getColumnModel().getColumn(vColIndex[i]).setPreferredWidth(width);
                             table.getColumnModel().getColumn(vColIndex[i]).setCellRenderer(centerRenderer);
              table.setFont(new java.awt.Font("Dialog", Font.ITALIC, 12));
              // force the header to resize and repaint itself
              table.getTableHeader().resizeAndRepaint();
              // create single component to add to scrollpane (rowHeader is JList with argument listModel)
              JList rowHeader = new JList(listModel);
              rowHeader.setFixedCellWidth(100);
              rowHeader.setFixedCellHeight(table.getRowHeight());
              rowHeader.setCellRenderer(new RowHeaderRenderer(table));
              // add to scroll pane:
              JScrollPane scroll = new JScrollPane( table );
              scroll.setRowHeaderView(rowHeader); // Adds row-list left of the table
              getContentPane().add(scroll, BorderLayout.CENTER);
              // add menubar, menu, menuitems with evenlisteners to the frame.
              JMenuBar menubar = new JMenuBar();
              setJMenuBar (menubar);
              JMenu filemenu = new JMenu("File");
              menubar.add(filemenu);
              JMenuItem open = new JMenuItem("Open");
              JMenuItem save = new JMenuItem("Save");
              JMenuItem exit = new JMenuItem("Exit");
              open.addActionListener(this);
              save.addActionListener(this);
              exit.addActionListener(this);
              filemenu.add(open);
              filemenu.add(save);
              filemenu.add(exit);
              filemenu.addItemListener(this);
    // ActionListener for ActionEvents on JMenuItems.
    public void actionPerformed(ActionEvent e) {       
         String open = "Open";
         String save = "Save";
         String exit = "Exit";
              if (e.getSource() instanceof JMenuItem)     {
                   JMenuItem source = (JMenuItem)(e.getSource());
                   String x = source.getText();
                        if (x == open)          {
                             System.out.println("open file");
                        // create JFileChooser.
                        String filename = File.separator+"tmp";
                        JFileChooser fc = new JFileChooser(new File(filename));
                        // set default directory.
                        File wrkDir = new File("C:/Documents and Settings/Erwin en G-M/Mijn documenten/Erwin/Match Day");
                        fc.setCurrentDirectory(wrkDir);
                        // show open dialog.
                        int returnVal =     fc.showOpenDialog(null);
                        File selFile = fc.getSelectedFile();
                        if(returnVal == JFileChooser.APPROVE_OPTION) {
                        System.out.println("You chose to open this file: " +
                   fc.getSelectedFile().getName());
                        try          {
                             BufferedReader invoer = new BufferedReader(new FileReader(selFile));
                             String line = invoer.readLine();
                             System.out.println(line);
                             // THIS IS WHERE IT GOES WRONG, I THINK
                             table.setValueAt(line, 1, 1);
                             table.fireTableDataChanged();
                        catch (IOException ioExc){
                        if (x == save)          {
                             System.out.println("save file");
                        if (x == exit)          {
                             System.out.println("exit file");
    // ItemListener for ItemEvents on JMenu.
    public void itemStateChanged(ItemEvent e) {       
              String s = "Item event detected. Event source: " + e.getSource();
              System.out.println(s);
         public static void main(String[] args)                {
              TeamTable frame = new TeamTable();
              frame.setUndecorated(true);
         frame.getRootPane().setWindowDecorationStyle(JRootPane.FRAME);
              frame.addWindowListener( new WindowAdapter()           {
                   public void windowClosing( WindowEvent e )                {
         System.exit(0);
    frame.setVisible(true);
    * Define the look/content for a cell in the row header
    * In this instance uses the JTables header properties
    class RowHeaderRenderer extends JLabel implements ListCellRenderer           {
    * Constructor creates all cells the same
    * To change look for individual cells put code in
    * getListCellRendererComponent method
    RowHeaderRenderer(JTable table)      {
    JTableHeader header = table.getTableHeader();
    setOpaque(true);
    setBorder(UIManager.getBorder("TableHeader.cellBorder"));
    setHorizontalAlignment(CENTER);
    setForeground(header.getForeground());
    setBackground(header.getBackground());
    setFont(header.getFont());
    * Returns the JLabel after setting the text of the cell
         public Component getListCellRendererComponent( JList list,
    Object value, int index, boolean isSelected, boolean cellHasFocus)      {
    setText((value == null) ? "" : value.toString());
    return this;

    My problem is that I�m reading a .txt-file into a J-Table. It all goes okay, the FileChooser opens and the application reads the selected file (line). But then I get a Null Pointer Exception and the JTable does not get updated with the text from the file.
    Here�s my code (I kept it simple, and just want to read the text from the .txt-file to the first cell of the table.
    A MORE READABLE VERSION !
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    import java.util.*;
    import java.lang.*;
    import java.io.*;
    public class TeamTable extends JFrame implements ActionListener, ItemListener                {
    static JTable table;
         // constructor
        public TeamTable()                {
            super( "Invoermodule - Team Table" );
            setSize( 740, 365 );
              // setting the rownames
            ListModel listModel = new AbstractListModel()                     {
                String headers[] = {"Team 1", "Team 2", "Team 3", "Team 4", "Team 5", "Team 6", "Team 7", "Team 8", "Team 9",
                "Team 10", "Team 11", "Team 12", "Team 13", "Team 14", "Team 15", "Team 16", "Team 17", "Team 18"};
                public int getSize() { return headers.length; }
                public Object getElementAt(int index) { return headers[index]; }
              // add listModel & rownames to the table
              DefaultTableModel defaultModel = new DefaultTableModel(listModel.getSize(),3);
              JTable table = new JTable( defaultModel );
              // setting the columnnames and center alignment of table cells
              int width = 200;
              int[] vColIndex = {0,1,2};
              String[] ColumnName = {"Name Team", "Name Chairman", "Name Manager"};
              TableCellRenderer centerRenderer = new CenterRenderer();          
              for (int i=0; i < vColIndex.length;i++)          {
                             table.getColumnModel().getColumn(vColIndex).setHeaderValue(ColumnName[i]);
                             table.getColumnModel().getColumn(vColIndex[i]).setPreferredWidth(width);
                             table.getColumnModel().getColumn(vColIndex[i]).setCellRenderer(centerRenderer);
              table.setFont(new java.awt.Font("Dialog", Font.ITALIC, 12));
              // force the header to resize and repaint itself
              table.getTableHeader().resizeAndRepaint();
              // create single component to add to scrollpane (rowHeader is JList with argument listModel)
              JList rowHeader = new JList(listModel);
              rowHeader.setFixedCellWidth(100);
              rowHeader.setFixedCellHeight(table.getRowHeight());
              rowHeader.setCellRenderer(new RowHeaderRenderer(table));
              // add to scroll pane:
              JScrollPane scroll = new JScrollPane( table );
              scroll.setRowHeaderView(rowHeader); // Adds row-list left of the table
              getContentPane().add(scroll, BorderLayout.CENTER);
              // add menubar, menu, menuitems with evenlisteners to the frame.
              JMenuBar menubar = new JMenuBar();
              setJMenuBar (menubar);
              JMenu filemenu = new JMenu("File");
              menubar.add(filemenu);
              JMenuItem open = new JMenuItem("Open");
              JMenuItem save = new JMenuItem("Save");
              JMenuItem exit = new JMenuItem("Exit");
              open.addActionListener(this);
              save.addActionListener(this);
              exit.addActionListener(this);
              filemenu.add(open);
              filemenu.add(save);
              filemenu.add(exit);
              filemenu.addItemListener(this);
    // ActionListener for ActionEvents on JMenuItems.
    public void actionPerformed(ActionEvent e) {       
         String open = "Open";
         String save = "Save";
         String exit = "Exit";
              if (e.getSource() instanceof JMenuItem)     {
                   JMenuItem source = (JMenuItem)(e.getSource());
                   String x = source.getText();
                        if (x == open)          {
                             System.out.println("open file");
                        // create JFileChooser.
                        String filename = File.separator+"tmp";
                        JFileChooser fc = new JFileChooser(new File(filename));
                        // set default directory.
                        File wrkDir = new File("C:/Documents and Settings/Erwin en G-M/Mijn documenten/Erwin/Match Day");
                        fc.setCurrentDirectory(wrkDir);
                        // show open dialog.
                        int returnVal =     fc.showOpenDialog(null);
                        File selFile = fc.getSelectedFile();
                        if(returnVal == JFileChooser.APPROVE_OPTION) {
                        System.out.println("You chose to open this file: " +
                   fc.getSelectedFile().getName());
                        try          {
                             BufferedReader invoer = new BufferedReader(new FileReader(selFile));
                             String line = invoer.readLine();
                             System.out.println(line);
                             // THIS IS WHERE IT GOES WRONG, I THINK
                             table.setValueAt(line, 1, 1);
                             table.fireTableDataChanged();
                        catch (IOException ioExc){
                        if (x == save)          {
                             System.out.println("save file");
                        if (x == exit)          {
                             System.out.println("exit file");
    // ItemListener for ItemEvents on JMenu.
    public void itemStateChanged(ItemEvent e) {       
              String s = "Item event detected. Event source: " + e.getSource();
              System.out.println(s);
         public static void main(String[] args)                {
              TeamTable frame = new TeamTable();
              frame.setUndecorated(true);
         frame.getRootPane().setWindowDecorationStyle(JRootPane.FRAME);
              frame.addWindowListener( new WindowAdapter()           {
                   public void windowClosing( WindowEvent e )                {
         System.exit(0);
    frame.setVisible(true);
    * Define the look/content for a cell in the row header
    * In this instance uses the JTables header properties
    class RowHeaderRenderer extends JLabel implements ListCellRenderer           {
    * Constructor creates all cells the same
    * To change look for individual cells put code in
    * getListCellRendererComponent method
    RowHeaderRenderer(JTable table)      {
    JTableHeader header = table.getTableHeader();
    setOpaque(true);
    setBorder(UIManager.getBorder("TableHeader.cellBorder"));
    setHorizontalAlignment(CENTER);
    setForeground(header.getForeground());
    setBackground(header.getBackground());
    setFont(header.getFont());
    * Returns the JLabel after setting the text of the cell
         public Component getListCellRendererComponent( JList list,
    Object value, int index, boolean isSelected, boolean cellHasFocus)      {
    setText((value == null) ? "" : value.toString());
    return this;

  • Button panel replaced by JTable result set

    Hi guys. Here's the problem. Below is my current working code.
    When run - a JOption pane opens, into which I type the database location (using /'s instead of \'s as it is a String input).
    The main UI opens. That indicates that the connection was successful. The UI consists of a JPanel (north) containg a number of buttons. Below that is a space for a JTable. Each button represents a diiferent query to the database and a different result set is displayed in the JTable beneath the buttons depending on which button is clicked.
    This all works fine.
    However I would like to now modify the code so that when the program runs the user is faced with the JPanel containing the Buttons only. And when a button is clicked the current panel is replaced with a full JTable containing the result set.
    So basically I want a JPanel with a number of buttons. Once clicked the result set JTable is displayed fully in the JFrame possibly with another button to bring the user back to the initial button panel.
    import java.io.*;
    import java.sql.*;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.table.*;
    public class Test12 extends JFrame {
    // java.sql types needed for database processing
    private Connection connection;
    private Statement statement;
    private ResultSet resultSet;
    private ResultSetMetaData rsMetaData;
    // javax.swing types needed for GUI
    private JTable table;
    private JTextArea inputQuery;
    public Test12()
    super( "Johnny Project" );
    // The URL specifying the Books database to which
    // this program connects using JDBC to connect to a
    // Microsoft ODBC database.
    // Load the driver to allow connection to the database
    try {
         Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
         String myFilename = JOptionPane.showInputDialog("Enter Database Location");
                   String myDatabase = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=";
                   myDatabase+= myFilename.trim() + ";DriverID=22;READONLY=true}";
                   connection = DriverManager.getConnection(myDatabase,"","");
    catch ( ClassNotFoundException cnfex ) {
    System.err.println(
    "Failed to load JDBC/ODBC driver." );
    cnfex.printStackTrace();
    System.exit( 1 ); // terminate program
    catch ( SQLException sqlex ) {
    System.err.println( "Unable to connect" );
    sqlex.printStackTrace();
    System.exit( 1 ); // terminate program
              //If connection succeeds - build GUI
              buildMenu();
              buildGUI();
              setSize(800, 800);
              show();
    private void getTable(String recievedQuery)
    try {
    String query = recievedQuery;
    statement = connection.createStatement();
    resultSet = statement.executeQuery(query);
    displayResultSet(resultSet);
    catch (SQLException sqlex) {
    sqlex.printStackTrace();
    private void displayResultSet(ResultSet rs)
    throws SQLException
    // position to first record
    boolean moreRecords = rs.next();
    // If there are no records, display a message
    if (! moreRecords) {
    JOptionPane.showMessageDialog( this,
    "ResultSet contained no records" );
    setTitle( "No records to display" );
    return;
    Vector columnHeads = new Vector();
    Vector rows = new Vector();
    try {
    // get column heads
    ResultSetMetaData rsmd = rs.getMetaData();
    for ( int i = 1; i <= rsmd.getColumnCount(); ++i )
    columnHeads.addElement( rsmd.getColumnName( i ) );
    // get row data
    do {
    rows.addElement( getNextRow( rs, rsmd ) );
    } while ( rs.next() );
    // display table with ResultSet contents
    table = new JTable( rows, columnHeads );
    JScrollPane scroller = new JScrollPane( table );
    Container c = getContentPane();
    c.remove( 1 );
    c.add( scroller, BorderLayout.CENTER );
    c.validate();
    catch ( SQLException sqlex ) {
    sqlex.printStackTrace();
    private Vector getNextRow( ResultSet rs, ResultSetMetaData rsmd )
    throws SQLException
    Vector currentRow = new Vector();
    for ( int i = 1; i <= rsmd.getColumnCount(); ++i )
    switch( rsmd.getColumnType( i ) ) {
    case Types.VARCHAR:
    case Types.LONGVARCHAR:
    currentRow.addElement( rs.getString( i ) );
    break;
    case Types.INTEGER:
    currentRow.addElement(
    new Long( rs.getLong( i ) ) );
    break;
    default:
    System.out.println( "Type was: " +
    rsmd.getColumnTypeName( i ) );
    return currentRow;
    public void shutDown()
    try {
    connection.close();
    catch ( SQLException sqlex ) {
    System.err.println( "Unable to disconnect" );
    sqlex.printStackTrace();
    private void buildGUI()
              inputQuery = new JTextArea(4, 30);
              Icon people = new ImageIcon("people.gif");
              JButton searchAll = new JButton("All", people);
              searchAll.setToolTipText("Search All People");
              searchAll.setBorder(null);
              searchAll.addActionListener(
         new ActionListener() {
    public void actionPerformed(ActionEvent e)
              String searchAllString = new String("Select * from 0001_per_year");
         getTable(searchAllString);
              JButton searchPathway = new JButton("Pathway", people);
              searchPathway.setToolTipText("Search Students by Pathway");     
              searchPathway.setBorder(null);
              searchPathway.addActionListener(
         new ActionListener() {
    public void actionPerformed(ActionEvent e)
              String searchPathwayString = new String("Select Student_Number, Pathway from 0001_per_year");
         getTable(searchPathwayString);
              JButton searchPeriod = new JButton("Study", people);
              searchPeriod.setToolTipText("Search Students by Period");     
              searchPeriod.setBorder(null);
              searchPeriod.addActionListener(
         new ActionListener() {
    public void actionPerformed(ActionEvent e)
              String searchPeriodString = new String("Select Student_Number, Period_of_Study from 0001_per_year");
         getTable(searchPeriodString);
              JButton searchAttendance = new JButton("Attendance", people);
              searchAttendance.setToolTipText("Search Students by Attendance");     
              searchAttendance.setBorder(null);
              searchAttendance.addActionListener(
         new ActionListener() {
    public void actionPerformed(ActionEvent e)
              String searchAttendanceString = new String("Select Student_Number, Attendance_Status from 0001_per_year");
         getTable(searchAttendanceString);
              JLabel j1 = new JLabel ();     
              JLabel j2 = new JLabel ();
              JLabel j3 = new JLabel ();
              JLabel j4 = new JLabel ();
              JLabel j5 = new JLabel ();
              JLabel j6 = new JLabel ();
              JLabel j7 = new JLabel ();
              JLabel j8 = new JLabel ();
              JLabel j9 = new JLabel ();
              JLabel j10 = new JLabel ();
              JLabel j11 =new JLabel ();
              JLabel j12 = new JLabel ();
              GridLayout grid;
              grid = new GridLayout(4,4);
                   JPanel topPanel = new JPanel();
              topPanel.setLayout(grid);
              topPanel.add(j1);
              topPanel.add(j2);
              topPanel.add(j3);
              topPanel.add(j4);
              topPanel.add(j5);
              topPanel.add(searchAll);
              topPanel.add(searchPathway);
              topPanel.add(j6);
              topPanel.add(j7);
                   topPanel.add(searchPeriod);
                   topPanel.add(searchAttendance);
                   topPanel.add(j8);
                   topPanel.add(j9);
                   topPanel.add(j10);
                   topPanel.add(j11);
                   topPanel.add(j12);
                   table = new JTable();
              Container c = getContentPane();
              c.setLayout( new BorderLayout() );
              c.add( topPanel, BorderLayout.NORTH );
              c.add( table, BorderLayout.CENTER );
              show();
    private void buildMenu()
    JMenuBar myMenuBar = new JMenuBar();
    JMenu myFileMenu = new JMenu("File");
    JMenuItem myExitItem = new JMenuItem("Exit");
    //Exit item closes the application
    myExitItem.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent e)
    System.exit(0);
    myFileMenu.add(myExitItem);
    myMenuBar.add(myFileMenu);
    setJMenuBar(myMenuBar);
    public static void main( String args[] )
    final Test12 app = new Test12();
    app.addWindowListener(
    new WindowAdapter() {
    public void windowClosing( WindowEvent e )
    app.shutDown();
    System.exit( 0 );

    Your welcome. I don't really compete for Duke's, but I'm glad the issue is resolved.
    - Saish
    "My karma ran over your dogma." - Anon

  • Updating a Jtable

    Hi,
    im trying to do a music library that connects to mysql.
    My problem is that I dont know how to updatethe table after I have been modifying the database.
    Ex.
    I want to be able to import information to my database and then I want to see the changes instantly.
    At the moment I only see the changes after a restart of the program.
    My code:
    import java.sql.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.Vector;
    import javax.swing.JTable;
    import javax.swing.table.AbstractTableModel;
    import java.awt.Dimension;
    import functions.*;
    public class MusicLibrary extends JFrame implements ActionListener
         //DEFENITIONS
         JLabel north, south, deepSouth;
         JScrollPane scrollPane,scrollPane2;
         ImageIcon background,top,bottom;
         JTextField searchField;
         JButton searchButton;
         JTable table;
         JMenuBar menuBar;
         JMenu file;
         JMenuItem importSong,removeSong,close;
         Container c;
         public MusicLibrary()
              //MENU
              menuBar = new JMenuBar();
              file = new JMenu("File");
              file.setMnemonic(KeyEvent.VK_F);
              importSong = new JMenuItem("Import Song", KeyEvent.VK_I);
              removeSong = new JMenuItem("Remove Song", KeyEvent.VK_R);
              close = new JMenuItem("Close",KeyEvent.VK_C);
              setJMenuBar(menuBar);
              menuBar.add(file);
              file.add(importSong);
              file.add(removeSong);
              file.addSeparator();
              file.add(close);
              //SOUTH
              background = new ImageIcon("background.gif");
              south = new JLabel (background);
              //NORTH
              top = new ImageIcon("top.gif");
              north = new JLabel(top);
              north.setLayout(new FlowLayout());
              north.setBackground(new Color(0,0,0));
              searchField = new JTextField(50);
              searchButton = new JButton("Search");
              north.add(searchField);
              north.add(searchButton);
              //CONTAINER
              c = getContentPane();
              c.setLayout(new BorderLayout());
              c.add(north, BorderLayout.NORTH);
              setSize(800,620);
              setVisible(true);
              setResizable(false);
              setDefaultCloseOperation(EXIT_ON_CLOSE);
              //DEEP SOUTH
              bottom = new ImageIcon("bottom.gif");
              deepSouth = new JLabel(bottom);
              c.add(deepSouth, BorderLayout.SOUTH);
              //LISTENERS
              close.addActionListener(this);
              //searchField.addActionListener(this);
              searchButton.addActionListener(this);
              importSong.addActionListener(this);
              //DATABASE CONNECTION
              try {
                   // load driver, create connection and statement
                   Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                   Connection con = DriverManager.getConnection("jdbc:odbc:XXX);
                   Statement stmt = con.createStatement();
                   // query database
                   ResultSet rs = stmt.executeQuery("SELECT * FROM song");
                   // display result
                   getTable(rs);
                   scrollPane = new JScrollPane(table);
                   c.add(scrollPane, BorderLayout.CENTER);
                   // close statement and connection
                   stmt.close();
                   con.close();
              catch (ClassNotFoundException e) {
                   JOptionPane.showMessageDialog(null, e.toString(),
                        "ClassNotFoundException", JOptionPane.ERROR_MESSAGE);
                   System.exit(1);
              catch (SQLException e) {
                   JOptionPane.showMessageDialog(null, e.toString(),
                        "SQLException", JOptionPane.ERROR_MESSAGE);
                   System.exit(1);
              //addWindowListener(new WindowHandler());
              setVisible(true);
         public void actionPerformed (ActionEvent e)
              if(e.getSource()==close)
                   System.exit(0);
              else if(e.getSource()==searchButton)
                   String textsearch = searchField.getText();
                   JOptionPane.showMessageDialog(null,"You searched for " + textsearch);
                   try {
                        // load driver, create connection and statement
                        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                        Connection con = DriverManager.getConnection("jdbc:odbc:XXX);
                        Statement stmt = con.createStatement();
                        // query database
                        ResultSet rs = stmt.executeQuery("SELECT * FROM song WHERE Song_Name = 'Africa'");
                        // display result
                        getTable(rs);
                        stmt.close();
                        con.close();
                   catch (ClassNotFoundException f) {
                        JOptionPane.showMessageDialog(null, f.toString(),
                             "ClassNotFoundException", JOptionPane.ERROR_MESSAGE);
                        System.exit(1);
                   catch (SQLException f) {
                        JOptionPane.showMessageDialog(null, f.toString(),
                             "SQLException", JOptionPane.ERROR_MESSAGE);
                        System.exit(1);
              else if(e.getSource()==importSong)
                   try
                        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                        Connection con = DriverManager.getConnection("jdbc:odbc:XXX);
                        EditDatabase.importMp3(con);          
                        //TEST
                        Statement stmt = con.createStatement();
                        // query database
                        ResultSet rs = stmt.executeQuery("SELECT * FROM song");
                        // display result
                        getTable(rs);
                        stmt.close();
                        con.close();
                   catch (Exception q){System.out.println("error" + q);}
              repaint();
         private void getTable(ResultSet rs) throws SQLException
              ResultSetMetaData rsmd = rs.getMetaData();
              Vector cols = new Vector();
              Vector rows = new Vector();
              // get column names
              for (int i = 1; i <= rsmd.getColumnCount(); i++) {
                   cols.addElement(rsmd.getColumnName(i));
              // get rows
              while (rs.next()) {
                   Vector nextRow = new Vector();
                   for (int i = 1; i <= rsmd.getColumnCount(); i++) {
                        nextRow.addElement(rs.getString(i));
                   rows.addElement(nextRow);
              // create table
              table = new JTable(rows, cols);
         //-WINDOW HANDLER-
         private class WindowHandler extends WindowAdapter
              public void windowClosing(WindowEvent e)
                   System.exit(0);
         //-MAIN-
         public static void main (String[] arg)
              new MusicLibrary();
    *Functions is a package containing importMp3 and deleteMp3
    I really appreciate all the help I can get!

    Thanks for poiting in the right direction.
    I had to rethink the design and I stumbled upon some code of yours camickr, thanks.
    Now the code looks like this:
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.sql.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    import functions.*;
    public class TableFromDatabase extends JFrame implements ActionListener, TableModelListener
         String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
         String url = "jdbc:odbc:mild";  // if using ODBC Data Source name
         String userid = "frenkan";
         String password = "tfb";
         Container c;
         JTable table;
         JScrollPane scrollPane;
         JMenuItem      importSong,
         removeSong,
         close;
         Connection connection;
         public TableFromDatabase()
              Vector columnNames = new Vector();
              Vector data = new Vector();
              try
                   //  Connect to the Database               
                   Class.forName( driver );
                   Connection connection = DriverManager.getConnection( url, userid, password );
                   //  Read data from a table
                   String sql = "Select * from Song";
                   Statement stmt = connection.createStatement();
                   ResultSet rs = stmt.executeQuery( sql );
                   ResultSetMetaData md = rs.getMetaData();
                   int columns = md.getColumnCount();
                   //  Get column names
                   for (int i = 1; i <= columns; i++)
                        columnNames.addElement( md.getColumnName(i) );
                   //  Get row data
                   while (rs.next())
                        Vector row = new Vector(columns);
                        for (int i = 1; i <= columns; i++)
                             row.addElement( rs.getObject(i) );
                        data.addElement( row );
                   rs.close();
                   stmt.close();
              catch(Exception e)
                   System.out.println( e );
              // Create TableModel with databases data
              DefaultTableModel model = new DefaultTableModel(data, columnNames);
              //model.addTableModelListener(this);
              //  Create table with model as TableModel
              table = new JTable(model)
                   public Class getColumnClass(int column)
                        return getValueAt(0, column).getClass();
              scrollPane = new JScrollPane( table );
              getContentPane().add( scrollPane );
              JPanel buttonPanel = new JPanel();
              c = getContentPane();
              c.add( buttonPanel, BorderLayout.SOUTH );
              //MENU
              JMenuBar menuBar = new JMenuBar();
              JMenu file = new JMenu("File");
              importSong = new JMenuItem("Import Song");
              removeSong = new JMenuItem("Remove Song");
              close = new JMenuItem("Close");
              importSong.addActionListener(this);
              removeSong.addActionListener(this);
              close.addActionListener(this);
              setJMenuBar(menuBar);
              menuBar.add(file);
              file.add(importSong);
              file.add(removeSong);
              file.addSeparator();
              file.add(close);
         public void tableChanged(TableModelEvent e)
         public void actionPerformed (ActionEvent e)
              if (e.getSource() == close)
                   System.exit(0);
              else if (e.getSource() == importSong)
                   try
                        //  Connect to the Database               
                        Class.forName( driver );
                        Connection connection = DriverManager.getConnection( url, userid, password );
                        EditDatabase.importMp3(connection);
                   catch (Exception exception)
                        System.out.println("Fel: " + exception);
         public static void main(String[] args)
              TableFromDatabase frame = new TableFromDatabase();
              frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
              frame.pack();
              frame.setVisible(true);
    }Basicly the same as your with some few modifications.
    What I want to know is how to update the table after I have imported a song to the database thru my importMp3() function? Please respond on a basic level. Any help is much appreciated!

  • JTable - getValueAt Problem

    I am new to Java and am having a problem with a JTable. I want the user to enter 12 months of rain that will go into an array list. The input sreen is O.K., but I cant retrieve the data or clear the cells. Any suggestings would be appreciated. Here is the code. Thanks Ronnie
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.BorderFactory.*;
    import javax.swing.table.*;
    import java.awt.event.FocusEvent;
    import java.awt.event.FocusListener;
    import javax.swing.JMenuBar;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    public class GridBagWindow extends JFrame implements ActionListener,
    FocusListener {
    public GridBagWindow() {
    setTitle("User Rainfall Data");
    JComboBox userCboRainCounty, userCboRainYr;
    DefaultTableModel dtmUserRain = new DefaultTableModel();
    JMenuBar userRainJMB = new JMenuBar();
    JMenu userRainfileMenu = new JMenu("File");
    JMenu userRainprintMenu = new JMenu("Print");
    JMenu userRainclearMenu = new JMenu("Clear");
    JMenu userRaintotalsMenu = new JMenu("Totals");
    // Need to add additional menu option because evnet can not be added
    // directly to JMenu
    JMenuItem userRainOpen = new JMenuItem("Open");
    JMenuItem userRainSave = new JMenuItem("Save");
    JMenuItem userRainPrint = new JMenuItem("Print");
    JMenuItem userRainClear = new JMenuItem("Clear");
    JMenuItem userRainTotals = new JMenuItem("Totals");
    userRainJMB.add(userRainfileMenu);
    userRainfileMenu.add(userRainOpen);
    userRainfileMenu.add(userRainSave);
    userRainJMB.add(userRainprintMenu);
    userRainprintMenu.add(userRainPrint);
    userRainJMB.add(userRainclearMenu);
    userRainclearMenu.add(userRainClear);
    userRainJMB.add(userRaintotalsMenu);
    userRaintotalsMenu.add(userRainTotals);
    userRainOpen.addActionListener(this);
    userRainSave.addActionListener(this);
    userRainPrint.addActionListener(this);
    userRainClear.addActionListener(this);
    userRainTotals.addActionListener(this);
    setJMenuBar(userRainJMB);
    Container contentPane = getContentPane();
    setFont(new Font("Arial", Font.BOLD, 16));
    GridBagLayout gridbag = new GridBagLayout();
    GridBagConstraints c = new GridBagConstraints();
    contentPane.setLayout(gridbag);
    int width = 800;
    int height = 500;
    Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
    int x = (screen.width - width) / 2;
    int y = (screen.height - height) / 2;
    setBounds(x, y, 600, 600);
    setJMenuBar(userRainJMB);
    JLabel userRainLblCounty = new JLabel(
    " County");
    userRainLblCounty.setFont(new Font("Arial", Font.BOLD, 16));
    buidConstraints(c, 2, 0, 1, 1, 0, 0);
    c.anchor = GridBagConstraints.EAST;
    c.insets = new Insets(1, 25, 1, 1);
    gridbag.setConstraints(userRainLblCounty, c);
    contentPane.add(userRainLblCounty);
    userCboRainCounty = new JComboBox();
    userCboRainCounty.setFont(new Font("Arial", Font.BOLD, 16));
    userCboRainCounty.setBackground(Color.white);
    buidConstraints(c, 3, 0, 1, 1, 0, 0);
    c.insets = new Insets(1, 1, 1, 1);
    c.anchor = GridBagConstraints.EAST;
    gridbag.setConstraints(userCboRainCounty, c);
    userCboRainCounty.addFocusListener(this);
    contentPane.add(userCboRainCounty);
    String[] header = { "Jan", "Feb", "Mar", "Apr", "May", "June",
    "July", "Aug", "Sep", "Oct", "Nov", "Dec", "Total" };
    DefaultTableModel dftModel = new DefaultTableModel(header, 1);
    JTable userRainTable = new JTable(dftModel);
    userRainTable.setEnabled(true);
    JScrollPane scrollPane = new JScrollPane(userRainTable);
    buidConstraints(c, 1, 1, 3, 1, 0, 0);
    c.anchor = GridBagConstraints.WEST;
    c.insets = new Insets(10, 10, 1, 1);
    gridbag.setConstraints(scrollPane, c);
    contentPane.add(scrollPane);
    JLabel userRainLblRain = new JLabel("Rain (in)");
    userRainLblCounty.setFont(new Font("Arial", Font.BOLD, 16));
    buidConstraints(c, 0, 1, 1, 1, 0, 0);
    c.anchor = GridBagConstraints.EAST;
    gridbag.setConstraints(userRainLblRain, c);
    contentPane.add(userRainLblRain);
    userRainTable
    .setPreferredScrollableViewportSize(new Dimension(600, 20));
    JLabel userRainLblRainYr = new JLabel("Rainfall Years");
    userRainLblRainYr.setFont(new Font("Arial", Font.BOLD, 16));
    buidConstraints(c, 0, 2, 1, 1, 0, 0);
    c.anchor = GridBagConstraints.SOUTH;
    c.insets = new Insets(0, 1, 1, 1);
    gridbag.setConstraints(userRainLblRainYr, c);
    contentPane.add(userRainLblRainYr);
    userCboRainYr = new JComboBox();
    userCboRainYr.setFont(new Font("Arial", Font.BOLD, 16));
    userCboRainYr.setBackground(Color.white);
    buidConstraints(c, 1, 2, 1, 1, 0, 0);
    c.insets = new Insets(1, 1, 1, 1);
    c.anchor = GridBagConstraints.EAST;
    gridbag.setConstraints(userCboRainYr, c);
    // userCboRainCounty.addFocusListener(this);
    contentPane.add(userCboRainYr);
    JLabel userRainLblTitle = new JLabel("Title");
    userRainLblTitle.setFont(new Font("Arial", Font.BOLD, 16));
    buidConstraints(c, 2, 2, 1, 1, 0, 0);
    c.anchor = GridBagConstraints.EAST;
    // c.insets = new Insets(1, 14,1,1);
    gridbag.setConstraints(userRainLblTitle, c);
    contentPane.add(userRainLblTitle);
    JTextField userRainTxtTitle = new JTextField(18);
    userRainTxtTitle.setFont(new Font("Arial", Font.BOLD, 16));
    buidConstraints(c, 3, 2, 1, 1, 0, 0);
    c.anchor = GridBagConstraints.EAST;
    c.insets = new Insets(1, 1, 1, 1);
    gridbag.setConstraints(userRainTxtTitle, c);
    contentPane.add(userRainTxtTitle);
    JLabel userLblRainBlank = new JLabel(" ");
    buidConstraints(c, 0, 3, 4, 4, 0, 0);
    c.insets = new Insets(15, 15, 1, 1);
    gridbag.setConstraints(userLblRainBlank, c);
    contentPane.add(userLblRainBlank);
    JButton userBtnRainDefault = new JButton(" Default ");
    userBtnRainDefault.setFont(new Font("Arial", Font.BOLD, 16));
    userBtnRainDefault.setBorder(BorderFactory.createRaisedBevelBorder());
    buidConstraints(c, 1, 4, 1, 1, 0, 0);
    c.anchor = GridBagConstraints.EAST;
    gridbag.setConstraints(userBtnRainDefault, c);
    contentPane.add(userBtnRainDefault);
    JButton userBtnRainCancel = new JButton(" Cancel ");
    userBtnRainCancel.setFont(new Font("Arial", Font.BOLD, 16));
    userBtnRainCancel.setBorder(BorderFactory.createRaisedBevelBorder());
    buidConstraints(c, 2, 4, 1, 1, 0, 0);
    c.anchor = GridBagConstraints.CENTER;
    c.insets = new Insets(15, 0, 0, 0);
    gridbag.setConstraints(userBtnRainCancel, c);
    contentPane.add(userBtnRainCancel);
    JButton userBtnRainOK = new JButton(" O.K ");
    userBtnRainOK.setFont(new Font("Arial", Font.BOLD, 16));
    userBtnRainOK.setBorder(BorderFactory.createRaisedBevelBorder());
    buidConstraints(c, 3, 4, 1, 1, 20, 20);
    c.insets = new Insets(15, 0, 0, 150);
    c.anchor = GridBagConstraints.EAST;
    gridbag.setConstraints(userBtnRainOK, c);
    userBtnRainOK.addActionListener(this);
    contentPane.add(userBtnRainOK);
    // //User Definded Cold Protection
    // Input Combo Box for County Selection, two counties per line
    userCboRainCounty.addItem("CHARLOTTE");
    userCboRainCounty.addItem("CITRUS");
    userCboRainCounty.setSelectedIndex(5);
    userCboRainYr.addItem(String.valueOf(1));
    userCboRainYr.addItem(String.valueOf(5));
    userCboRainYr.addItem(String.valueOf(10));
    userCboRainYr.setSelectedIndex(-1);
    addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    pack();
    setVisible(true);
    void buidConstraints(GridBagConstraints c, int gx, int gy, int gw, int gh,
    int wx, int wy) {
    c.gridx = gx;
    c.gridy = gy;
    c.gridwidth = gw;
    c.gridheight = gh;
    c.weightx = wx;
    c.weighty = wy;
    public void focusGained(FocusEvent af) {
    // if(af.getSource() == userRainTable){
    // userRainTable.setBackground(Color.yellow);
    public static void main(String args[]) {
    GridBagWindow window = new GridBagWindow();
    public void actionPerformed(ActionEvent evt) {
    String actionName = evt.getActionCommand();
    System.out.println("Button \"" + actionName + "\" was pressed.");
    // userRainTable.getValueAt(1,1);
    if (actionName == "Clear") {
    for (int i = 0; i > 14; i++) {
    // userRainfallTable.setValueAt(0, 1 , 1);
    System.out.println("Yes Continue");
    if (actionName == "Totals") {
    System.out.println("Yes Continue");
    }

    Hello Ronnie,
    this is a nice little piece of code. ;-)
    No chance of reducing it a little bit just to show the problem?
    And what about making it at least to compile error free? (Just tried on 1.5_06)
    Also place tags around to make it more readable.
    Regards
    J�rg                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Seveval columns in a JMenu ?

    Hello,
    i build a JMenu with many items (20) which are very small (kind of gif smileys),
    so i'd like to make 4 columns instead of a long one.
    Is there any solution except a complex JTable ?
    thx !!!

    myMenu.getPopupMenu().setLayout(new GridLayout(10,0));

  • JComboBox, JTable, cellRendering CHALLENGE

    Hi all,
    I would like to ask a question of the resident guru concerning a Netbeans/MYSQL application. I based it on a tutorial found here: [http://www.netbeans.org/kb/61/java/gui-db-custom.html].
    I have two seperate JDialogs that write data to a master table. One of the JDialogs is called "Customer Editor" and it contains various text fields bound to cells on the masterTable, no big deal.
    Also in the "Customer Editor" JDialog there is a JComboBox that has a list of four values to choose from which are "Good", "Standby", "Failed", and "Complete".
    I would like the data selected from the JComboBox to color itself when it writes to the JTable row/cell on the masterTable. For example if the user selects "Good" from the list, in the masterTable the font color of the String will be GREEN. Similarly, if the user selects "Failed" from the JComboBox I would like the String to return RED...following on "Standby" - BLUE, "Complete" - no color change.
    Question: How do I write code that allows me to change the color of text in a cell when it comes from a JComboBox list?
    If anyone out there picks up this thread, I will of course supply the code I have so far. I won't do it now as I am not sure even where the code should go. I think it would go in the source code for the masterTable view but I am not certain.
    Any Java masters out there?
    David

    Thanks for the reply. I have been writing different cell renderers to get it working. Where should the code reside?
    This is my operations view class. Should it be in here.
    /CODE/
    package operationsrecords;
    import org.jdesktop.application.Action;
    import org.jdesktop.application.ResourceMap;
    import org.jdesktop.application.SingleFrameApplication;
    import org.jdesktop.application.FrameView;
    import org.jdesktop.application.TaskMonitor;
    import org.jdesktop.application.Task;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.ArrayList;
    import java.util.Collection;
    import java.util.Iterator;
    import java.util.LinkedList;
    import java.util.List;
    import javax.persistence.RollbackException;
    import javax.swing.Timer;
    import javax.swing.Icon;
    import javax.swing.JDialog;
    import javax.swing.JFrame;
    import javax.swing.JOptionPane;
    import javax.swing.event.ListSelectionEvent;
    import javax.swing.event.ListSelectionListener;
    import org.jdesktop.beansbinding.AbstractBindingListener;
    import org.jdesktop.beansbinding.Binding;
    import org.jdesktop.beansbinding.PropertyStateEvent;
    * The application's main frame.
    public class OperationsRecordsView extends FrameView {
    public OperationsRecordsView(SingleFrameApplication app) {
    super(app);
    initComponents();
    // status bar initialization - message timeout, idle icon and busy animation, etc
    ResourceMap resourceMap = getResourceMap();
    int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout");
         messageTimer = new Timer(messageTimeout, new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    statusMessageLabel.setText("");
         messageTimer.setRepeats(false);
    int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate");
    for (int i = 0; i < busyIcons.length; i++) {
    busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]");
    busyIconTimer = new Timer(busyAnimationRate, new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    busyIconIndex = (busyIconIndex + 1) % busyIcons.length;
    statusAnimationLabel.setIcon(busyIcons[busyIconIndex]);
    idleIcon = resourceMap.getIcon("StatusBar.idleIcon");
    statusAnimationLabel.setIcon(idleIcon);
    progressBar.setVisible(false);
    // connecting action tasks to status bar via TaskMonitor
    TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext());
    taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
    public void propertyChange(java.beans.PropertyChangeEvent evt) {
    String propertyName = evt.getPropertyName();
    if ("started".equals(propertyName)) {
    if (!busyIconTimer.isRunning()) {
    statusAnimationLabel.setIcon(busyIcons[0]);
    busyIconIndex = 0;
    busyIconTimer.start();
    progressBar.setVisible(true);
    progressBar.setIndeterminate(true);
    } else if ("done".equals(propertyName)) {
    busyIconTimer.stop();
    statusAnimationLabel.setIcon(idleIcon);
    progressBar.setVisible(false);
    progressBar.setValue(0);
    } else if ("message".equals(propertyName)) {
    String text = (String)(evt.getNewValue());
    statusMessageLabel.setText((text == null) ? "" : text);
    messageTimer.restart();
    } else if ("progress".equals(propertyName)) {
    int value = (Integer)(evt.getNewValue());
    progressBar.setVisible(true);
    progressBar.setIndeterminate(false);
    progressBar.setValue(value);
    // tracking table selection
    masterTable.getSelectionModel().addListSelectionListener(
    new ListSelectionListener() {
    public void valueChanged(ListSelectionEvent e) {
    firePropertyChange("recordSelected", !isRecordSelected(), isRecordSelected());
    detailTable.getSelectionModel().addListSelectionListener(
    new ListSelectionListener() {
    public void valueChanged(ListSelectionEvent e) {
    firePropertyChange("detailRecordSelected", !isDetailRecordSelected(), isDetailRecordSelected());
    // tracking changes to save
    bindingGroup.addBindingListener(new AbstractBindingListener() {
    @Override
    public void targetChanged(Binding binding, PropertyStateEvent event) {
    // save action observes saveNeeded property
    setSaveNeeded(true);
    // have a transaction started
    entityManager.getTransaction().begin();
    public boolean isSaveNeeded() {
    return saveNeeded;
    private void setSaveNeeded(boolean saveNeeded) {
    if (saveNeeded != this.saveNeeded) {
    this.saveNeeded = saveNeeded;
    firePropertyChange("saveNeeded", !saveNeeded, saveNeeded);
    public boolean isRecordSelected() {
    return masterTable.getSelectedRow() != -1;
    public boolean isDetailRecordSelected() {
    return detailTable.getSelectedRow() != -1;
    @Action
    public void newRecord() {
    operationsrecords.Customers c = new operationsrecords.Customers();
    entityManager.persist(c);
    list.add(c);
    int row = masterTable.getRowCount() - 1;
    masterTable.setRowSelectionInterval(row, row);
    masterTable.scrollRectToVisible(masterTable.getCellRect(row, 0, true));
    setSaveNeeded(true);
    JFrame mainFrame = OperationsRecordsApp.getApplication().getMainFrame();
    CustomerEditor ce = new CustomerEditor(mainFrame, false);
    ce.setCurrentRecord(c);
    ce.setVisible(true);
    if (ce.isCustomerConfirmed()) {
    save().run();
    } else {
    refresh().run();
    @Action(enabledProperty = "recordSelected")
    public void deleteRecord() {
    Object[] options = {"OK", "Cancel"};
    int n = JOptionPane.showConfirmDialog(null, "Delete the records permanently?", "Warning",
    JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null);
    if (n == JOptionPane.YES_OPTION) {
    int[] selected = masterTable.getSelectedRows();
    List<operationsrecords.Customers> toRemove = new ArrayList<operationsrecords.Customers>(selected.length);
    for (int idx = 0; idx < selected.length; idx++) {
    operationsrecords.Customers c = list.get(masterTable.convertRowIndexToModel(selected[idx]));
    toRemove.add(c);
    entityManager.remove(c);
    list.removeAll(toRemove);
    save().run();
    } else {
    refresh().run();
    @Action(enabledProperty = "recordSelected")
    public void newDetailRecord() {
    int index = masterTable.getSelectedRow();
    operationsrecords.Customers c = list.get(masterTable.convertRowIndexToModel(index));
    Collection<operationsrecords.Orders> os = c.getOrdersCollection();
    if (os == null) {
    os = new LinkedList<operationsrecords.Orders>();
    c.setOrdersCollection(os);
    operationsrecords.Orders o = new operationsrecords.Orders();
    o.setShipDate(new java.util.Date());
    entityManager.persist(o);
    o.setCustomerId(c);
    os.add(o);
    masterTable.clearSelection();
    masterTable.setRowSelectionInterval(index, index);
    int row = os.size()-1;
    detailTable.setRowSelectionInterval(row, row);
    detailTable.scrollRectToVisible(detailTable.getCellRect(row, 0, true));
    setSaveNeeded(true);
    JFrame mainFrame = OperationsRecordsApp.getApplication().getMainFrame();
    OrderEditor oe = new OrderEditor(mainFrame, false);
    oe.setCurrentOrderRecord(o);
    oe.setVisible(true);
    if (oe.isOrderConfirmed()) {
    save().run();
    } else {
    refresh().run();
    @Action(enabledProperty = "detailRecordSelected")
    public void deleteDetailRecord() {
    Object[] options = {"OK", "Cancel"};
    int n = JOptionPane.showConfirmDialog(null, "Delete the records permanently?", "Warning",
    JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null);
    if (n == JOptionPane.YES_OPTION) {
    int index = masterTable.getSelectedRow();
    operationsrecords.Customers c = list.get(masterTable.convertRowIndexToModel(index));
    Collection<operationsrecords.Orders> os = c.getOrdersCollection();
    int[] selected = detailTable.getSelectedRows();
    List<operationsrecords.Orders> toRemove = new ArrayList<operationsrecords.Orders>(selected.length);
    for (int idx = 0; idx < selected.length; idx++) {
    selected[idx] = detailTable.convertRowIndexToModel(selected[idx]);
    int count = 0;
    Iterator<operationsrecords.Orders> iter = os.iterator();
    while (count++ < selected[idx]) {
    iter.next();
    operationsrecords.Orders o = iter.next();
    toRemove.add(o);
    entityManager.remove(o);
    os.removeAll(toRemove);
    masterTable.clearSelection();
    masterTable.setRowSelectionInterval(index, index);
    list.removeAll(toRemove);
    save().run();
    } else {
    refresh().run();
    @Action(enabledProperty = "saveNeeded")
    public Task save() {
    return new SaveTask(getApplication());
    private class SaveTask extends Task {
    SaveTask(org.jdesktop.application.Application app) {
    super(app);
    @Override protected Void doInBackground() {
    try {
    entityManager.getTransaction().commit();
    entityManager.getTransaction().begin();
    } catch (RollbackException rex) {
    rex.printStackTrace();
    entityManager.getTransaction().begin();
    List<operationsrecords.Customers> merged = new ArrayList<operationsrecords.Customers>(list.size());
    for (operationsrecords.Customers c : list) {
    merged.add(entityManager.merge(c));
    list.clear();
    list.addAll(merged);
    return null;
    @Override protected void finished() {
    setSaveNeeded(false);
    * An example action method showing how to create asynchronous tasks
    * (running on background) and how to show their progress. Note the
    * artificial 'Thread.sleep' calls making the task long enough to see the
    * progress visualization - remove the sleeps for real application.
    @Action
    public Task refresh() {
    return new RefreshTask(getApplication());
    private class RefreshTask extends Task {
    RefreshTask(org.jdesktop.application.Application app) {
    super(app);
    @SuppressWarnings("unchecked")
    @Override protected Void doInBackground() {
    setProgress(0, 0, 4);
    setMessage("Rolling back the current changes...");
    setProgress(1, 0, 4);
    entityManager.getTransaction().rollback();
    setProgress(2, 0, 4);
    setMessage("Starting a new transaction...");
    entityManager.getTransaction().begin();
    setProgress(3, 0, 4);
    setMessage("Fetching new data...");
    java.util.Collection data = query.getResultList();
    for (Object entity : data) {
    entityManager.refresh(entity);
    setProgress(4, 0, 4);
    list.clear();
    list.addAll(data);
    return null;
    @Override protected void finished() {
    setMessage("Done.");
    setSaveNeeded(false);
    @Action
    public void showAboutBox() {
    if (aboutBox == null) {
    JFrame mainFrame = OperationsRecordsApp.getApplication().getMainFrame();
    aboutBox = new OperationsRecordsAboutBox(mainFrame);
    aboutBox.setLocationRelativeTo(mainFrame);
    OperationsRecordsApp.getApplication().show(aboutBox);
    /** 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() {
    bindingGroup = new org.jdesktop.beansbinding.BindingGroup();
    mainPanel = new javax.swing.JPanel();
    masterScrollPane = new javax.swing.JScrollPane();
    masterTable = new javax.swing.JTable();
    newButton = new javax.swing.JButton();
    deleteButton = new javax.swing.JButton();
    detailScrollPane = new javax.swing.JScrollPane();
    detailTable = new javax.swing.JTable();
    deleteDetailButton = new javax.swing.JButton();
    newDetailButton = new javax.swing.JButton();
    jButton1 = new javax.swing.JButton();
    jButton2 = new javax.swing.JButton();
    jLabel1 = new javax.swing.JLabel();
    jTextField1 = new javax.swing.JTextField();
    jLabel2 = new javax.swing.JLabel();
    menuBar = new javax.swing.JMenuBar();
    javax.swing.JMenu fileMenu = new javax.swing.JMenu();
    javax.swing.JMenuItem newRecordMenuItem = new javax.swing.JMenuItem();
    javax.swing.JMenuItem deleteRecordMenuItem = new javax.swing.JMenuItem();
    jSeparator1 = new javax.swing.JSeparator();
    javax.swing.JMenuItem saveMenuItem = new javax.swing.JMenuItem();
    javax.swing.JMenuItem refreshMenuItem = new javax.swing.JMenuItem();
    jSeparator2 = new javax.swing.JSeparator();
    javax.swing.JMenuItem exitMenuItem = new javax.swing.JMenuItem();
    javax.swing.JMenu helpMenu = new javax.swing.JMenu();
    javax.swing.JMenuItem aboutMenuItem = new javax.swing.JMenuItem();
    statusPanel = new javax.swing.JPanel();
    javax.swing.JSeparator statusPanelSeparator = new javax.swing.JSeparator();
    statusMessageLabel = new javax.swing.JLabel();
    statusAnimationLabel = new javax.swing.JLabel();
    progressBar = new javax.swing.JProgressBar();
    entityManager = java.beans.Beans.isDesignTime() ? null : javax.persistence.Persistence.createEntityManagerFactory("OperationsRecordsPU").createEntityManager();
    org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(operationsrecords.OperationsRecordsApp.class).getContext().getResourceMap(OperationsRecordsView.class);
    query = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery(resourceMap.getString("query.query")); // NOI18N
    list = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(query.getResultList());
    rowSorterToStringConverter1 = new operationsrecords.RowSorterToStringConverter();
    mainPanel.setBackground(resourceMap.getColor("mainPanel.background")); // NOI18N
    mainPanel.setName("mainPanel"); // NOI18N
    masterScrollPane.setName("masterScrollPane"); // NOI18N
    masterTable.setBackground(resourceMap.getColor("masterTable.background")); // NOI18N
    masterTable.setGridColor(resourceMap.getColor("masterTable.gridColor")); // NOI18N
    masterTable.setName("masterTable"); // NOI18N
    masterTable.setShowVerticalLines(false);
    org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, list, masterTable);
    org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${jobId}"));
    columnBinding.setColumnName("Job Id");
    columnBinding.setColumnClass(String.class);
    columnBinding.setEditable(false);
    columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${statusId.status}"));
    columnBinding.setColumnName("Status Id.status");
    columnBinding.setColumnClass(String.class);
    columnBinding.setEditable(false);
    columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${company}"));
    columnBinding.setColumnName("Company");
    columnBinding.setColumnClass(String.class);
    columnBinding.setEditable(false);
    columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${rig}"));
    columnBinding.setColumnName("Rig");
    columnBinding.setColumnClass(String.class);
    columnBinding.setEditable(false);
    columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${well}"));
    columnBinding.setColumnName("Well");
    columnBinding.setColumnClass(String.class);
    columnBinding.setEditable(false);
    columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${county}"));
    columnBinding.setColumnName("County");
    columnBinding.setColumnClass(String.class);
    columnBinding.setEditable(false);
    columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${state}"));
    columnBinding.setColumnName("State");
    columnBinding.setColumnClass(String.class);
    columnBinding.setEditable(false);
    columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${companyMan}"));
    columnBinding.setColumnName("Company Man");
    columnBinding.setColumnClass(String.class);
    columnBinding.setEditable(false);
    columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${phone}"));
    columnBinding.setColumnName("Phone");
    columnBinding.setColumnClass(String.class);
    columnBinding.setEditable(false);
    columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${fax}"));
    columnBinding.setColumnName("Fax");
    columnBinding.setColumnClass(String.class);
    columnBinding.setEditable(false);
    columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${emailAddress}"));
    columnBinding.setColumnName("Email Address");
    columnBinding.setColumnClass(String.class);
    columnBinding.setEditable(false);
    bindingGroup.addBinding(jTableBinding);
    jTableBinding.bind();
    masterScrollPane.setViewportView(masterTable);
    masterTable.getColumnModel().getColumn(0).setHeaderValue(resourceMap.getString("masterTable.columnModel.title0")); // NOI18N
    masterTable.getColumnModel().getColumn(1).setHeaderValue(resourceMap.getString("masterTable.columnModel.title1")); // NOI18N
    masterTable.getColumnModel().getColumn(2).setHeaderValue(resourceMap.getString("masterTable.columnModel.title2")); // NOI18N
    masterTable.getColumnModel().getColumn(3).setHeaderValue(resourceMap.getString("masterTable.columnModel.title3")); // NOI18N
    masterTable.getColumnModel().getColumn(4).setHeaderValue(resourceMap.getString("masterTable.columnModel.title4")); // NOI18N
    masterTable.getColumnModel().getColumn(5).setHeaderValue(resourceMap.getString("masterTable.columnModel.title5")); // NOI18N
    masterTable.getColumnModel().getColumn(6).setHeaderValue(resourceMap.getString("masterTable.columnModel.title6")); // NOI18N
    masterTable.getColumnModel().getColumn(7).setHeaderValue(resourceMap.getString("masterTable.columnModel.title7")); // NOI18N
    masterTable.getColumnModel().getColumn(8).setHeaderValue(resourceMap.getString("masterTable.columnModel.title8")); // NOI18N
    masterTable.getColumnModel().getColumn(9).setHeaderValue(resourceMap.getString("masterTable.columnModel.title9")); // NOI18N
    masterTable.getColumnModel().getColumn(10).setHeaderValue(resourceMap.getString("masterTable.columnModel.title10")); // NOI18N
    javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(operationsrecords.OperationsRecordsApp.class).getContext().getActionMap(OperationsRecordsView.class, this);
    newButton.setAction(actionMap.get("newRecord")); // NOI18N
    newButton.setBackground(resourceMap.getColor("newButton.background")); // NOI18N
    newButton.setName("newButton"); // NOI18N
    deleteButton.setAction(actionMap.get("deleteRecord")); // NOI18N
    deleteButton.setBackground(resourceMap.getColor("jButton1.background")); // NOI18N
    deleteButton.setName("deleteButton"); // NOI18N
    detailScrollPane.setName("detailScrollPane"); // NOI18N
    detailTable.setGridColor(resourceMap.getColor("detailTable.gridColor")); // NOI18N
    detailTable.setName("detailTable"); // NOI18N
    detailTable.setShowVerticalLines(false);
    detailTable.getTableHeader().setReorderingAllowed(false);
    org.jdesktop.beansbinding.ELProperty eLProperty = org.jdesktop.beansbinding.ELProperty.create("${selectedElement.ordersCollection}");
    jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, eLProperty, detailTable);
    columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${shipDate}"));
    columnBinding.setColumnName("Ship Date");
    columnBinding.setColumnClass(java.util.Date.class);
    columnBinding.setEditable(false);
    columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${tool}"));
    columnBinding.setColumnName("Tool");
    columnBinding.setColumnClass(String.class);
    columnBinding.setEditable(false);
    columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${collar}"));
    columnBinding.setColumnName("Collar");
    columnBinding.setColumnClass(String.class);
    columnBinding.setEditable(false);
    columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${xo}"));
    columnBinding.setColumnName("Xo");
    columnBinding.setColumnClass(String.class);
    columnBinding.setEditable(false);
    columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${xo2}"));
    columnBinding.setColumnName("Xo2");
    columnBinding.setColumnClass(String.class);
    columnBinding.setEditable(false);
    columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${surfaceKit}"));
    columnBinding.setColumnName("Surface Kit");
    columnBinding.setColumnClass(String.class);
    columnBinding.setEditable(false);
    columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${comments}"));
    columnBinding.setColumnName("Comments");
    columnBinding.setColumnClass(String.class);
    columnBinding.setEditable(false);
    columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${directions}"));
    columnBinding.setColumnName("Directions");
    columnBinding.setColumnClass(String.class);
    columnBinding.setEditable(false);
    jTableBinding.setSourceUnreadableValue(java.util.Collections.emptyList());
    bindingGroup.addBinding(jTableBinding);
    jTableBinding.bind();
    detailScrollPane.setViewportView(detailTable);
    detailTable.getColumnModel().getColumn(0).setResizable(false);
    detailTable.getColumnModel().getColumn(0).setPreferredWidth(10);
    detailTable.getColumnModel().getColumn(0).setHeaderValue(resourceMap.getString("detailTable.columnModel.title0")); // NOI18N
    detailTable.getColumnModel().getColumn(1).setResizable(false);
    detailTable.getColumnModel().getColumn(1).setPreferredWidth(5);
    detailTable.getColumnModel().getColumn(1).setHeaderValue(resourceMap.getString("detailTable.columnModel.title1")); // NOI18N
    detailTable.getColumnModel().getColumn(2).setResizable(false);
    detailTable.getColumnModel().getColumn(2).setPreferredWidth(5);
    detailTable.getColumnModel().getColumn(2).setHeaderValue(resourceMap.getString("detailTable.columnModel.title2")); // NOI18N
    detailTable.getColumnModel().getColumn(3).setResizable(false);
    detailTable.getColumnModel().getColumn(3).setPreferredWidth(5);
    detailTable.getColumnModel().getColumn(3).setHeaderValue(resourceMap.getString("detailTable.columnModel.title3")); // NOI18N
    detailTable.getColumnModel().getColumn(4).setResizable(false);
    detailTable.getColumnModel().getColumn(4).setPreferredWidth(5);
    detailTable.getColumnModel().getColumn(4).setHeaderValue(resourceMap.getString("detailTable.columnModel.title4")); // NOI18N
    detailTable.getColumnModel().getColumn(5).setResizable(false);
    detailTable.getColumnModel().getColumn(5).setPreferredWidth(5);
    detailTable.getColumnModel().getColumn(5).setHeaderValue(resourceMap.getString("detailTable.columnModel.title5")); // NOI18N
    detailTable.getColumnModel().getColumn(6).setResizable(false);
    detailTable.getColumnModel().getColumn(6).setPreferredWidth(300);
    detailTable.getColumnModel().getColumn(6).setHeaderValue(resourceMap.getString("detailTable.columnModel.title6")); // NOI18N
    detailTable.getColumnModel().getColumn(7).setResizable(false);
    detailTable.getColumnModel().getColumn(7).setPreferredWidth(300);
    detailTable.getColumnModel().getColumn(7).setHeaderValue(resourceMap.getString("detailTable.columnModel.title7")); // NOI18N
    deleteDetailButton.setAction(actionMap.get("deleteDetailRecord")); // NOI18N
    deleteDetailButton.setBackground(resourceMap.getColor("jButton1.background")); // NOI18N
    deleteDetailButton.setName("deleteDetailButton"); // NOI18N
    newDetailButton.setAction(actionMap.get("newDetailRecord")); // NOI18N
    newDetailButton.setBackground(resourceMap.getColor("jButton1.background")); // NOI18N
    newDetailButton.setName("newDetailButton"); // NOI18N
    jButton1.setAction(actionMap.get("editCustomer")); // NOI18N
    jButton1.setBackground(resourceMap.getColor("jButton1.background")); // NOI18N
    jButton1.setText(resourceMap.getString("jButton1.text")); // NOI18N
    jButton1.setName("jButton1"); // NOI18N
    jButton2.setAction(actionMap.get("editOrder")); // NOI18N
    jButton2.setBackground(resourceMap.getColor("jButton1.background")); // NOI18N
    jButton2.setText(resourceMap.getString("jButton2.text")); // NOI18N
    jButton2.setName("jButton2"); // NOI18N
    jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
    jLabel1.setName("jLabel1"); // NOI18N
    jTextField1.setName("jTextField1"); // NOI18N
    org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${rowSorter}"), jTextField1, org.jdesktop.beansbinding.BeanProperty.create("text"));
    binding.setConverter(rowSorterToStringConverter1);
    bindingGroup.addBinding(binding);
    jLabel2.setIcon(resourceMap.getIcon("jLabel2.icon")); // NOI18N
    jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
    jLabel2.setName("jLabel2"); // NOI18N
    javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
    mainPanel.setLayout(mainPanelLayout);
    mainPanelLayout.setHorizontalGroup(
    mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(mainPanelLayout.createSequentialGroup()
    .addContainerGap()
    .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addComponent(detailScrollPane, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 1057, Short.MAX_VALUE)
    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, mainPanelLayout.createSequentialGroup()
    .addComponent(newDetailButton)
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addComponent(jButton2)
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addComponent(deleteDetailButton))
    .addComponent(masterScrollPane, javax.swing.GroupLayout.DEFAULT

Maybe you are looking for

  • Stuck "Slide to Answer"

    At least once a day, with seemingly no pattern to it, the "Slide To Answer" does not work at all or it only moves halfway, thus making it impossible to answer my call. I have read of some others with this problem, but thus far no solutions. (I have t

  • Help me! I dont get to reinstall Premiere Pro CS4!

    Hi, I m trying to reinstall premiere pro cs4 but it shows a screen saying: Critical errors were found in setup for Adobe Premiere Pro CS4: - Incompatible payloads already installed Please see the Setup log file for details. Click Quit to exit Setup.

  • Billing pirce in the cross-company stock transfer

    Hi,    We went to use the cross-company stock transfer to move our stock from one company to another, as we know price of the Intercompany billing copy from condition table.but we went the price copy from the transfer order(PO),How to do it? Lance

  • Button execution issue

    I've been having issues with buttons that are tied to my emerson drive talking modbus ethernet. The issue being that when I press a momentary pushbutton, I get a double bump like I hit the pushbutton twice. It'll hold true every once in a while too.

  • Re-installing Photoshop 2.0

    My computer shut off while I had Adobe Photoshop 2.0 open.  I thought it had corrupted the picture data file (it's backed up!) so I deleted the file off computer.  I then determined it had corrupted one of the program files. I deleted the program thr