Search Results

Search found 269 results on 11 pages for 'actionlistener'.

Page 5/11 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11  | Next Page >

  • Open new panel with button clicked.

    - by bat
    Java Swing GUI: I am using ActionListener to preform the action when a button is clicked. What i want to do is when a button is clicked, open a new panel, but load/get the new panel from a different file. This is what i have so far but i rather just link to another file. THANKS! =] public void actionPerformed(java.awt.event.ActionEvent e) { //something like this... loadFile(newPlane.java); }

    Read the article

  • Making a app show inside a GUI in Java

    - by José
    Hello. I have one problem I've been dealing with for this week. You see, I'm new to Java, so that's probably it... Anyways, I've started a project out of pure curiosity. I had it done in Java, but in plain CMD-style, which is not very pretty. It calls one of my ten programs, chosen by the user using "Case". Eg.: If you type 1, it will go to program 1. After you finish it, it goes back to selection until the user press 0. After that, I've been trying to make a GUI for it. I've been able to create the selector alone and make it respond to the numbers chosen. If you press 1 and click ok, it will tell you you've chosen program 1. I, however, have not been able to make it run the program. I've been trying to make the program show up in a jPanel, part of the main GUI. I failed miserably. The program runs in separate but I can't make them run together like the CMD one. The apps were made in Eclipse SDK 3.5.2 The GUIs were made in Netbeans IDE 6.8 Here's the code for the GUI only (the prints are in PT-BR, my native language): Main program: /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * ProgramasGUI.java * * Created on 31/01/2010, 22:56:19 */ package Main; import Main.Prog1; /** * * @author Zeh® */ public class ProgramasGUI extends javax.swing.JFrame { /** Creates new form ProgramasGUI */ public ProgramasGUI() { initComponents(); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code"> private void initComponents() { selecao = new javax.swing.JTextField(); mostrador = new javax.swing.JLabel(); selecionar = new javax.swing.JButton(); mostrador1 = new javax.swing.JLabel(); jPanel1 = new javax.swing.JPanel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); selecao.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { selecaoActionPerformed(evt); } }); mostrador.setText("Qual o programa desejado?"); selecionar.setText("OK"); selecionar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { selecionarActionPerformed(evt); } }); mostrador1.setText("Saiba aqui o Programa escolhido!"); jPanel1.addComponentListener(new java.awt.event.ComponentAdapter() { public void componentShown(java.awt.event.ComponentEvent evt) { jPanel1ComponentShown(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 100, Short.MAX_VALUE) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 100, Short.MAX_VALUE) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(selecao, javax.swing.GroupLayout.PREFERRED_SIZE, 203, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(selecionar, javax.swing.GroupLayout.DEFAULT_SIZE, 203, Short.MAX_VALUE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(mostrador1, javax.swing.GroupLayout.PREFERRED_SIZE, 193, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(mostrador, javax.swing.GroupLayout.PREFERRED_SIZE, 179, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(layout.createSequentialGroup() .addGap(162, 162, 162) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(39, Short.MAX_VALUE) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(30, 30, 30) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(selecao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(mostrador, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(selecionar) .addComponent(mostrador1)) .addContainerGap()) ); pack(); }// </editor-fold> private void selecaoActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: } private void selecionarActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: int programa = (int)((Double.parseDouble(selecao.getText()))); switch (programa) { case 1: mostrador1.setText("O programa " + programa + " foi escolhido!" ); break; case 2: mostrador1.setText("O programa " + programa + " foi escolhido!" ); break; case 3: mostrador1.setText("O programa " + programa + " foi escolhido!" ); break; case 4: mostrador1.setText("O programa " + programa + " foi escolhido!" ); break; case 5: mostrador1.setText("O programa " + programa + " foi escolhido!" ); break; case 6: mostrador1.setText("O programa " + programa + " foi escolhido!" ); break; case 7: mostrador1.setText("O programa " + programa + " foi escolhido!" ); break; case 8: mostrador1.setText("O programa " + programa + " foi escolhido!" ); break; case 9: mostrador1.setText("O programa " + programa + " foi escolhido!" ); break; case 10: mostrador1.setText("O programa " + programa + " foi escolhido!" ); break;} } private void jPanel1ComponentShown(java.awt.event.ComponentEvent evt) { int programa = (int)((Double.parseDouble(selecao.getText()))); switch (programa) { case 1: addNotify(Prog1.); break;} } /** * @param args the command line arguments */ public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new ProgramasGUI().setVisible(true); } }); } // Variables declaration - do not modify private javax.swing.JPanel jPanel1; private javax.swing.JLabel mostrador; private javax.swing.JLabel mostrador1; private javax.swing.JTextField selecao; private javax.swing.JButton selecionar; // End of variables declaration } And here's the sub-program: /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * Prog1.java * * Created on 02/02/2010, 23:57:59 */ package Main; /** * * @author Zeh® */ public class Prog1 extends javax.swing.JPanel { /** Creates new form Prog1 */ public Prog1() { initComponents(); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code"> private void initComponents() { jLabel1 = new javax.swing.JLabel(); numesc = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jButton1 = new javax.swing.JButton(); campo = new javax.swing.JTextField(); jLabel1.setText("Saiba aqui o Antecessor!"); numesc.setText("O número escolhido é: X"); jLabel3.setText("Saiba aqui o Sucessor!"); jLabel4.setText("Insira um número para saber seu Antecessor e Sucessor!"); jButton1.setText("Calcular!"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); campo.setText("Insira seu número"); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(16, 16, 16) .addComponent(jButton1)) .addComponent(campo, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(10, 10, 10) .addComponent(jLabel3)) .addGroup(layout.createSequentialGroup() .addGap(10, 10, 10) .addComponent(numesc, javax.swing.GroupLayout.DEFAULT_SIZE, 154, Short.MAX_VALUE)) .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 164, Short.MAX_VALUE))) .addComponent(jLabel4)) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel4) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(campo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel1)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(numesc) .addGap(11, 11, 11) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(jButton1)) .addContainerGap(24, Short.MAX_VALUE)) ); }// </editor-fold> private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { int num = (int)((Double.parseDouble(campo.getText()))); numesc.setText("O número escolhido é: " + num); int x = num-1; jLabel1.setText ("O antecessor é: " + x); int y = num+1; jLabel3.setText ("O sucessor é: " + y); } // Variables declaration - do not modify private javax.swing.JTextField campo; private javax.swing.JButton jButton1; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel numesc; // End of variables declaration } Any help would be very appreciated. If I, for some reason, made a mistake typing and/or setting the layout of this post incorrectly, please accept my apologies.

    Read the article

  • using ResultSet.Previous method not working in Java using .mdb file OBDC

    - by jsonnie
    Hello, I'm currently having an issue with my open result set not working how I believe it should. The only function that is currently working is the next() method, nothing else will work. If the project is placed into a debug mode you can follow through actionperformed event on the button it hits the previous() method and jumps over the remaining code in the method. If someone could point me in the right direction it would be truly appreciated. FORM CODE: import java.sql.; import javax.swing.; public class DataNavigator extends javax.swing.JFrame { public DataInterface db = null; public Statement s = null; public Connection con = null; public PreparedStatement stmt = null; public ResultSet rs = null; /** Creates new form DataNavigator */ public DataNavigator() { initComponents(); try { db = new DataInterface("jdbc:odbc:CMPS422"); con = db.getConnection(); stmt = con.prepareStatement("SELECT * FROM Products"); rs = stmt.executeQuery(); rs.last(); } catch (Exception e) { } } /** 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() { btnFirst = new javax.swing.JButton(); btnNext = new javax.swing.JButton(); btnLast = new javax.swing.JButton(); btnUpdate = new javax.swing.JButton(); btnInsert = new javax.swing.JButton(); btnDelete = new javax.swing.JButton(); txtPartNum = new javax.swing.JTextField(); txtDesc = new javax.swing.JTextField(); txtQty = new javax.swing.JTextField(); txtPrice = new javax.swing.JTextField(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); btnPrev = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Assignment 3 Data Navigator"); addWindowListener(new java.awt.event.WindowAdapter() { public void windowOpened(java.awt.event.WindowEvent evt) { formWindowOpened(evt); } }); btnFirst.setText("First"); btnFirst.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnFirstActionPerformed(evt); } }); btnNext.setText("Next"); btnNext.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnNextActionPerformed(evt); } }); btnLast.setText("Last"); btnLast.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnLastActionPerformed(evt); } }); btnUpdate.setText("Update"); btnInsert.setText("Insert"); btnDelete.setText("Delete"); jLabel1.setText("Part Number:"); jLabel2.setText("Description:"); jLabel3.setText("Quantity:"); jLabel4.setText("Price:"); btnPrev.setText("Prev"); btnPrev.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { btnPrevMouseClicked(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(btnFirst) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(2, 2, 2) .addComponent(btnPrev) .addGap(4, 4, 4) .addComponent(btnNext) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnLast)) .addComponent(jLabel1) .addComponent(jLabel2) .addComponent(jLabel3) .addComponent(jLabel4)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(txtPartNum) .addGroup(layout.createSequentialGroup() .addComponent(btnUpdate) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnInsert) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnDelete)) .addComponent(txtDesc) .addComponent(txtQty) .addComponent(txtPrice)) .addContainerGap(71, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnFirst) .addComponent(btnNext) .addComponent(btnLast) .addComponent(btnUpdate) .addComponent(btnInsert) .addComponent(btnDelete) .addComponent(btnPrev)) .addGap(66, 66, 66) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel1) .addComponent(txtPartNum, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(txtDesc, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel2)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(txtQty, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel3)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(txtPrice, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel4)) .addContainerGap(102, Short.MAX_VALUE)) ); pack(); }// </editor-fold> private void formWindowOpened(java.awt.event.WindowEvent evt) { try { this.txtPartNum.setText(rs.getString("Partnum")); this.txtDesc.setText(rs.getString("Description")); this.txtPrice.setText(rs.getString("Price")); this.txtQty.setText(rs.getString("Quantity")); } catch (SQLException e) { } } private void btnNextActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: try { System.out.println(rs.getCursorName()); rs.next(); rs.moveToCurrentRow(); System.out.println(rs.getCursorName()); this.txtPartNum.setText(rs.getString("Partnum")); this.txtDesc.setText(rs.getString("Description")); this.txtPrice.setText(rs.getString("Price")); this.txtQty.setText(rs.getString("Quantity")); System.out.println(rs.getRow()); } catch (Exception e) { } } private void btnLastActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: try { rs.last(); this.txtPartNum.setText(rs.getString("Partnum")); this.txtDesc.setText(rs.getString("Description")); this.txtPrice.setText(rs.getString("Price")); this.txtQty.setText(rs.getString("Quantity")); } catch (Exception e) { } } private void btnFirstActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: try { rs.first(); this.txtPartNum.setText(rs.getString("Partnum")); this.txtDesc.setText(rs.getString("Description")); this.txtPrice.setText(rs.getString("Price")); this.txtQty.setText(rs.getString("Quantity")); } catch (Exception e) { } } private void btnPrevMouseClicked(java.awt.event.MouseEvent evt) { // TODO add your handling code here: try { int i; i = rs.getRow(); if (i > 0) { rs.previous(); System.out.println(rs.getRow()); this.txtPartNum.setText(rs.getString("Partnum")); this.txtDesc.setText(rs.getString("Description")); this.txtPrice.setText(rs.getString("Price")); this.txtQty.setText(rs.getString("Quantity")); } else { System.out.println("FALSE"); } } catch (Exception e) { } } /** * @param args the command line arguments */ public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new DataNavigator().setVisible(true); } }); } // Variables declaration - do not modify private javax.swing.JButton btnDelete; private javax.swing.JButton btnFirst; private javax.swing.JButton btnInsert; private javax.swing.JButton btnLast; private javax.swing.JButton btnNext; private javax.swing.JButton btnPrev; private javax.swing.JButton btnUpdate; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JTextField txtDesc; private javax.swing.JTextField txtPartNum; private javax.swing.JTextField txtPrice; private javax.swing.JTextField txtQty; // End of variables declaration } CLASS OBJECT CODE: import java.sql.*; import javax.swing.JOptionPane; public class DataInterface { private static DataInterface dbint = null; private static Connection conn = null; // connection object. private static ResultSet rset = null; public DataInterface(String ODBCDSN) { try { // See if the driver is present. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); // Open connection to database. conn = DriverManager.getConnection(ODBCDSN); JOptionPane.showMessageDialog(null, "Database successfully opened"); } catch (Exception e) { JOptionPane.showMessageDialog(null, e.toString()); } } public Connection getConnection() { return conn; } public static DataInterface getInstance() { return dbint; } public static ResultSet getResultSet() { return rset; } public PreparedStatement setStatement(String a) throws SQLException{ PreparedStatement stmt = conn.prepareStatement(a); return stmt; }

    Read the article

  • Why Look and feel is not getting updated properly?

    - by swift
    I’m developing a swing application in which I have an option to change the Look and feel of the application on click of a button. Now my problem is when I click the button to change the theme it’s not properly updating the L&F of my app, say my previous theme is “noire” and I choose “MCWin” after it, but the style of the noire theme is still there Here is sample working code: package whiteboard; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ComponentEvent; import java.awt.event.ComponentListener; import javax.swing.JFrame; import javax.swing.JLayeredPane; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.WindowConstants; public class DiscussionBoard extends JFrame implements ComponentListener,ActionListener { // Variables declaration private JMenuItem audioMenuItem; private JMenuItem boardMenuItem; private JMenuItem exitMenuItem; private JMenuItem clientsMenuItem; private JMenuItem acryl; private JMenuItem hifi; private JMenuItem aero; private JMenuItem aluminium; private JMenuItem bernstein; private JMenuItem fast; private JMenuItem graphite; private JMenuItem luna; private JMenuItem mcwin; private JMenuItem noire; private JMenuItem smart; private JMenuBar boardMenuBar; private JMenuItem messengerMenuItem; private JMenu openMenu; private JMenu saveMenu; private JMenu themesMenu; private JMenuItem saveMessengerMenuItem; private JMenuItem saveWhiteboardMenuItem; private JMenu userMenu; JLayeredPane layerpane; /** Creates new form discussionBoard * @param connection */ public DiscussionBoard() { initComponents(); setLocationRelativeTo(null); addComponentListener(this); } private void initComponents() { boardMenuBar = new JMenuBar(); openMenu = new JMenu(); themesMenu = new JMenu(); messengerMenuItem = new JMenuItem(); boardMenuItem = new JMenuItem(); audioMenuItem = new JMenuItem(); saveMenu = new JMenu(); saveMessengerMenuItem = new JMenuItem(); saveWhiteboardMenuItem = new JMenuItem(); userMenu = new JMenu(); clientsMenuItem = new JMenuItem(); exitMenuItem = new JMenuItem(); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); setLayout(new GridBagLayout()); setResizable(false); setTitle("Discussion Board"); openMenu.setText("Open"); saveMenu.setText("Save"); themesMenu.setText("Themes"); acryl = new JMenuItem("Acryl"); hifi = new JMenuItem("HiFi"); aero = new JMenuItem("Aero"); aluminium = new JMenuItem("Aluminium"); bernstein = new JMenuItem("Bernstein"); fast = new JMenuItem("Fast"); graphite = new JMenuItem("Graphite"); luna = new JMenuItem("Luna"); mcwin = new JMenuItem("MCwin"); noire = new JMenuItem("Noire"); smart = new JMenuItem("Smart"); hifi.addActionListener(this); acryl.addActionListener(this); aero.addActionListener(this); aluminium.addActionListener(this); bernstein.addActionListener(this); fast.addActionListener(this); graphite.addActionListener(this); luna.addActionListener(this); mcwin.addActionListener(this); noire.addActionListener(this); smart.addActionListener(this); messengerMenuItem.setText("Messenger"); openMenu.add(messengerMenuItem); openMenu.add(boardMenuItem); audioMenuItem.setText("Audio Messenger"); openMenu.add(audioMenuItem); exitMenuItem.setText("Exit"); exitMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { exitMenuItemActionPerformed(evt); } }); openMenu.add(exitMenuItem); boardMenuBar.add(openMenu); saveMessengerMenuItem.setText("Messenger"); saveMenu.add(saveMessengerMenuItem); saveWhiteboardMenuItem.setText("Whiteboard"); saveMenu.add(saveWhiteboardMenuItem); boardMenuBar.add(saveMenu); userMenu.setText("Users"); clientsMenuItem.setText("Current Session"); userMenu.add(clientsMenuItem); themesMenu.add(acryl); themesMenu.add(hifi); themesMenu.add(aero); themesMenu.add(aluminium); themesMenu.add(bernstein); themesMenu.add(fast); themesMenu.add(graphite); themesMenu.add(luna); themesMenu.add(mcwin); themesMenu.add(noire); themesMenu.add(smart); boardMenuBar.add(userMenu); boardMenuBar.add(themesMenu); saveMessengerMenuItem.setEnabled(false); saveWhiteboardMenuItem.setEnabled(false); setJMenuBar(boardMenuBar); setSize(1024, 740); setVisible(true); } protected void exitMenuItemActionPerformed(ActionEvent evt) { System.exit(0); } @Override public void componentHidden(ComponentEvent arg0) { } @Override public void componentMoved(ComponentEvent e) { } @Override public void componentResized(ComponentEvent arg0) { } @Override public void componentShown(ComponentEvent arg0) { } @Override public void actionPerformed(ActionEvent e) { try { if(e.getSource()==hifi) { UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel"); SwingUtilities.updateComponentTreeUI(getRootPane()); UIManager.setLookAndFeel("com.jtattoo.plaf.hifi.HiFiLookAndFeel"); enableTheme(); hifi.setEnabled(false); } else if(e.getSource()==acryl) { UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel"); SwingUtilities.updateComponentTreeUI(getRootPane()); UIManager.setLookAndFeel("com.jtattoo.plaf.acryl.AcrylLookAndFeel"); enableTheme(); acryl.setEnabled(false); } else if(e.getSource()==aero) { UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel"); SwingUtilities.updateComponentTreeUI(getRootPane()); UIManager.setLookAndFeel("com.jtattoo.plaf.aero.AeroLookAndFeel"); enableTheme(); aero.setEnabled(false); } else if(e.getSource()==aluminium) { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); SwingUtilities.updateComponentTreeUI(getRootPane()); UIManager.setLookAndFeel("com.jtattoo.plaf.aluminium.AluminiumLookAndFeel"); enableTheme(); aluminium.setEnabled(false); } else if(e.getSource()==bernstein) { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); SwingUtilities.updateComponentTreeUI(getRootPane()); UIManager.setLookAndFeel("com.jtattoo.plaf.bernstein.BernsteinLookAndFeel"); enableTheme(); bernstein.setEnabled(false); } else if(e.getSource()==fast) { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); SwingUtilities.updateComponentTreeUI(getRootPane()); UIManager.setLookAndFeel("com.jtattoo.plaf.fast.FastLookAndFeel"); enableTheme(); fast.setEnabled(false); } else if(e.getSource()==graphite) { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); SwingUtilities.updateComponentTreeUI(getRootPane()); UIManager.setLookAndFeel("com.jtattoo.plaf.graphite.GraphiteLookAndFeel"); enableTheme(); graphite.setEnabled(false); } else if(e.getSource()==luna) { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); SwingUtilities.updateComponentTreeUI(getRootPane()); UIManager.setLookAndFeel("com.jtattoo.plaf.luna.LunaLookAndFeel"); enableTheme(); luna.setEnabled(false); } else if(e.getSource()==mcwin) { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); SwingUtilities.updateComponentTreeUI(getRootPane()); UIManager.setLookAndFeel("com.jtattoo.plaf.mcwin.McWinLookAndFeel"); enableTheme(); mcwin.setEnabled(false); } else if(e.getSource()==noire) { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); SwingUtilities.updateComponentTreeUI(getRootPane()); UIManager.setLookAndFeel("com.jtattoo.plaf.noire.NoireLookAndFeel"); enableTheme(); noire.setEnabled(false); } else if(e.getSource()==smart) { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); SwingUtilities.updateComponentTreeUI(getRootPane()); UIManager.setLookAndFeel("com.jtattoo.plaf.smart.SmartLookAndFeel"); enableTheme(); smart.setEnabled(false); } SwingUtilities.updateComponentTreeUI(getRootPane()); } catch (Exception ex) { ex.printStackTrace(); } } private void enableTheme() { acryl.setEnabled(true); hifi.setEnabled(true); aero.setEnabled(true); aluminium.setEnabled(true); bernstein.setEnabled(true); fast.setEnabled(true); graphite.setEnabled(true); luna.setEnabled(true); mcwin.setEnabled(true); noire.setEnabled(true); smart.setEnabled(true); } public static void main(String []ar) { try { UIManager.setLookAndFeel("com.jtattoo.plaf.acryl.AcrylLookAndFeel"); } catch (Exception e) { e.printStackTrace(); } new DiscussionBoard(); } } What’s the problem here? why its not getting updated? There is a demo application here which is exactly doing what i want but i cant get a clear idea of it.

    Read the article

  • Data from 6 ArrayLists into a single JTable - Java Swing

    - by Splunk
    I have created a JTable which is populated by various arraylists which get their data from a text list using a "~" to split. The issue I am having is that the table is displaying all data from the list on a single row. For example: Column1 Column2 Column2 Column2 Column3 Column4 1,2,3,4,5 1,2,3,4,5 1,2,3,4,5 1,2,3,4,5 1,2,3,4,5 1,2,3,4,5 When I want it to display Column1 Column2 Column2 Column2 Column3 Column4 1 1 1 1 1 1 2 2 2 2 2 2 3 3 3 3 3 3 You get the idea. From previous advice, I think the issue may be looping, but I am not sure. Any advice would be great. The code is below: private void table(){ String[] colName = { "Course", "Examiner", "Moderator", "Semester Available ", "Associated Programs", "Associated Majors"}; DefaultTableModel model = new DefaultTableModel(colName,0); for(Object item : courseList){ Object[] row = new Object[6]; // String[] row = new String[6]; row[0] = fileManage.getCourseList(); row[1] = fileManage.getNameList(); row[2] = fileManage.getModeratorList(); row[3] = fileManage.getSemesterList(); row[4] = fileManage.getProgramList(); row[5] = fileManage.getMajorList(); model.addRow(row); textArea = new JTable(model); } This is the class that has the arraylists: import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.Scanner; public class FileIOManagement { private ArrayList<String> nameList = new ArrayList<String>(); private ArrayList<String> courseList = new ArrayList<String>(); private ArrayList<String> semesterList = new ArrayList<String>(); private ArrayList<String> moderatorList = new ArrayList<String>(); private ArrayList<String> programList = new ArrayList<String>(); private ArrayList<String> majorList = new ArrayList<String>(); public ArrayList<String> getNameList(){ return this.nameList; } public ArrayList<String> getCourseList(){ return this.courseList; } public ArrayList<String> getSemesterList(){ return this.semesterList; } public ArrayList<String> getModeratorList(){ return this.moderatorList; } public ArrayList<String> getProgramList(){ return this.programList; } public ArrayList<String> getMajorList(){ return this.majorList; } public void setNameList(ArrayList<String> nameList){ this.nameList = nameList; } public void setCourseList(ArrayList<String> courseList){ this.courseList = courseList; } public void setSemesterList(ArrayList<String> semesterList){ this.semesterList = semesterList; } public void setModeratorList(ArrayList<String> moderatorList){ this.moderatorList = moderatorList; } public void setProgramList(ArrayList<String> programList){ this.programList = programList; } public void setMajorList(ArrayList<String> majorList){ this.majorList = majorList; } public FileIOManagement(){ setNameList(new ArrayList<String>()); setCourseList(new ArrayList<String>()); setSemesterList(new ArrayList<String>()); setModeratorList(new ArrayList<String>()); setProgramList(new ArrayList<String>()); setMajorList(new ArrayList<String>()); readTextFile(); getNameList(); getCourseList(); } private void readTextFile(){ try{ Scanner scan = new Scanner(new File("Course.txt")); while(scan.hasNextLine()){ String line = scan.nextLine(); String[] tokens = line.split("~"); String course = tokens[0].trim(); String examiner = tokens[1].trim(); String moderator = tokens[2].trim(); String semester = tokens[3].trim(); String program = tokens[4].trim(); String major = tokens[5].trim(); courseList.add(course); semesterList.add(semester); nameList.add(examiner); moderatorList.add(moderator); programList.add(program); majorList.add(major); HashSet hs = new HashSet(); hs.addAll(nameList); nameList.clear(); nameList.addAll(hs); Collections.sort(nameList); } scan.close(); } catch (FileNotFoundException e){ e.printStackTrace(); } } } This is the class where I need to have the JTable: import java.awt.*; import javax.swing.*; import java.io.*; import javax.swing.border.EmptyBorder; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import javax.swing.table.DefaultTableModel; public class AllDataGUI extends JFrame{ private JButton saveCloseBtn = new JButton("Save Changes and Close"); private JButton closeButton = new JButton("Exit Without Saving"); private JFrame frame=new JFrame("Viewing All Program Details"); private final FileIOManagement fileManage = new FileIOManagement(); private ArrayList<String> nameList = new ArrayList(); private ArrayList<String> courseList = new ArrayList(); private ArrayList<String> semesterList = new ArrayList(); private ArrayList<String> moderatorList = new ArrayList(); private ArrayList<String> majorList = new ArrayList(); private ArrayList<String> programList = new ArrayList(); private JTable textArea; public ArrayList<String> getNameList(){ return this.nameList; } public ArrayList<String> getCourseList(){ return this.courseList; } public ArrayList<String> getSemesterList(){ return this.semesterList; } public ArrayList<String> getModeratorList(){ return this.moderatorList; } public ArrayList<String> getProgramList(){ return this.programList; } public ArrayList<String> getMajorList(){ return this.majorList; } public void setNameList(ArrayList<String> nameList){ this.nameList = nameList; } public void setCourseList(ArrayList<String> courseList){ this.courseList = courseList; } public void setSemesterList(ArrayList<String> semesterList){ this.semesterList = semesterList; } public void setModeratorList(ArrayList<String> moderatorList){ this.moderatorList = moderatorList; } public void setProgramList(ArrayList<String> programList){ this.programList = programList; } public void setMajorList(ArrayList<String> majorList){ this.majorList = majorList; } public AllDataGUI(){ getData(); table(); panels(); } public Object getValueAt(int rowIndex, int columnIndex) { String[] token = nameList.get(rowIndex).split(","); return token[columnIndex]; } private void table(){ String[] colName = { "Course", "Examiner", "Moderator", "Semester Available ", "Associated Programs", "Associated Majors"}; DefaultTableModel model = new DefaultTableModel(colName,0); for(Object item : courseList){ Object[] row = new Object[6]; // String[] row = new String[6]; row[0] = fileManage.getCourseList(); row[1] = fileManage.getNameList(); row[2] = fileManage.getModeratorList(); row[3] = fileManage.getSemesterList(); row[4] = fileManage.getProgramList(); row[5] = fileManage.getMajorList(); model.addRow(row); textArea = new JTable(model); // String END_OF_LINE = ","; // // String[] colName = { "Course", "Examiner", "Moderator", "Semester Available ", "Associated Programs", "Associated Majors"}; //// textArea.getTableHeader().setBackground(Color.WHITE); //// textArea.getTableHeader().setForeground(Color.BLUE); // // Font Tablefont = new Font("Details", Font.BOLD, 12); // // textArea.getTableHeader().setFont(Tablefont); // Object[][] object = new Object[100][100]; // int i = 0; // if (fileManage.size() != 0) { // for (fileManage book : fileManage) { // object[i][0] = fileManage.getCourseList(); // object[i][1] = fileManage.getNameList(); // object[i][2] = fileManage.getModeratorList(); // object[i][3] = fileManage.getSemesterList(); // object[i][4] = fileManage.getProgramList(); // object[i][5] = fileManage.getMajorList(); // // textArea = new JTable(object, colName); // } // } } } public void getData(){ nameList = fileManage.getNameList(); courseList = fileManage.getCourseList(); semesterList = fileManage.getSemesterList(); moderatorList = fileManage.getModeratorList(); majorList = fileManage.getMajorList(); programList = fileManage.getProgramList(); // textArea.(write()); } private JButton getCloseButton(){ return closeButton; } private void panels(){ JPanel panel = new JPanel(new GridLayout(1,1)); panel.setBorder(new EmptyBorder(5, 5, 5, 5)); JPanel rightPanel = new JPanel(new GridLayout(15,0,10,10)); rightPanel.setBorder(new EmptyBorder(15, 5, 5, 10)); JScrollPane scrollBarForTextArea=new JScrollPane(textArea,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); panel.add(scrollBarForTextArea); frame.add(panel); frame.getContentPane().add(rightPanel,BorderLayout.EAST); rightPanel.add(saveCloseBtn); rightPanel.add(closeButton); closeButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { frame.dispose(); } }); saveCloseBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { //saveBtn(); frame.dispose(); } }); frame.setSize(1000, 700); frame.setVisible(true); frame.setLocationRelativeTo(null); } // private void saveBtn(){ // File file = null; // FileWriter out=null; // try { // file = new File("Course.txt"); // out = new FileWriter(file); // out.write(textArea.getText()); // out.close(); // } catch (FileNotFoundException e) { // e.printStackTrace(); // } catch (IOException e) { // e.printStackTrace(); // } // JOptionPane.showMessageDialog(this, "File Successfully Updated"); // // } }

    Read the article

  • 'SImple' 2 class Java calculator doesn't accept inputs or do calculations

    - by Tony O'Keeffe
    Hi, I'm trying to get a two class java calculator working (new to java) to work but so far i'm having no success. the two classes are outlined below, calcFrame is for the interface and calEngine should do the actual calculations but i can't get them to talk to one another. i'd really appreciate any assistance on same. Thanks. CalcFrame Code - import java.awt.; import javax.swing.; import javax.swing.border.; import java.awt.event.; /** *A Class that operates as the framework for a calculator. *No calculations are performed in this section */ public class CalcFrame implements ActionListener { private CalcEngine calc; private JFrame frame; private JTextField display; private JLabel status; /** * Constructor for objects of class GridLayoutExample */ public CalcFrame() { makeFrame(); //calc = engine; } /** * This allows you to quit the calculator. */ // Alows the class to quit. private void quit() { System.exit(0); } // Calls the dialog frame with the information about the project. private void showAbout() { JOptionPane.showMessageDialog(frame, "Group Project", "About Calculator Group Project", JOptionPane.INFORMATION_MESSAGE); } private void makeFrame() { frame = new JFrame("Group Project Calculator"); makeMenuBar(frame); JPanel contentPane = (JPanel)frame.getContentPane(); contentPane.setLayout(new BorderLayout(8, 8)); contentPane.setBorder(new EmptyBorder( 10, 10, 10, 10)); /** * Insert a text field */ display = new JTextField(); contentPane.add(display, BorderLayout.NORTH); //Container contentPane = frame.getContentPane(); contentPane.setLayout(new GridLayout(4, 4)); JPanel buttonPanel = new JPanel(new GridLayout(4, 4)); contentPane.add(new JButton("1")); contentPane.add(new JButton("2")); contentPane.add(new JButton("3")); contentPane.add(new JButton("4")); contentPane.add(new JButton("5")); contentPane.add(new JButton("6")); contentPane.add(new JButton("7")); contentPane.add(new JButton("8")); contentPane.add(new JButton("9")); contentPane.add(new JButton("0")); contentPane.add(new JButton("+")); contentPane.add(new JButton("-")); contentPane.add(new JButton("/")); contentPane.add(new JButton("*")); contentPane.add(new JButton("=")); contentPane.add(new JButton("C")); contentPane.add(buttonPanel, BorderLayout.CENTER); //status = new JLabel(calc.getAuthor()); //contentPane.add(status, BorderLayout.SOUTH); frame.pack(); frame.setVisible(true); } /** * Create the main frame's menu bar. * The frame that the menu bar should be added to. */ private void makeMenuBar(JFrame frame) { final int SHORTCUT_MASK = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); JMenuBar menubar = new JMenuBar(); frame.setJMenuBar(menubar); JMenu menu; JMenuItem item; // create the File menu menu = new JMenu("File"); menubar.add(menu); // create the Quit menu with a shortcut "Q" key. item = new JMenuItem("Quit"); item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, SHORTCUT_MASK)); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { quit(); } }); menu.add(item); // Adds an about menu. menu = new JMenu("About"); menubar.add(menu); // Displays item = new JMenuItem("Calculator Project"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { showAbout(); } }); menu.add(item); } /** * An interface action has been performed. * Find out what it was and handle it. * @param event The event that has occured. */ public void actionPerformed(ActionEvent event) { String command = event.getActionCommand(); if(command.equals("0") || command.equals("1") || command.equals("2") || command.equals("3") || command.equals("4") || command.equals("5") || command.equals("6") || command.equals("7") || command.equals("8") || command.equals("9")) { int number = Integer.parseInt(command); calc.numberPressed(number); } else if(command.equals("+")) { calc.plus(); } else if(command.equals("-")) { calc.minus(); } else if(command.equals("=")) { calc.equals(); } else if(command.equals("C")) { calc.clear(); } else if(command.equals("?")) { } // else unknown command. redisplay(); } /** * Update the interface display to show the current value of the * calculator. */ private void redisplay() { display.setText("" + calc.getDisplayValue()); } /** * Toggle the info display in the calculator's status area between the * author and version information. */ } CalcEngine - public class CalcEngine { // The calculator's state is maintained in three fields: // buildingDisplayValue, haveLeftOperand, and lastOperator. // The current value (to be) shown in the display. private int displayValue; // The value of an existing left operand. private int leftOperand; /** * Create a CalcEngine. */ public CalcEngine() { clear(); } public int getDisplayValue() { return displayValue; } /** * A number button was pressed. * Either start a new operand, or incorporate this number as * the least significant digit of an existing one. * @param number The number pressed on the calculator. */ public void numberPressed(int number) { if(buildingDisplayValue) { // Incorporate this digit. displayValue = displayValue*10 + number; } else { // Start building a new number. displayValue = number; buildingDisplayValue = true; } } /** * The 'plus' button was pressed. */ public void plus() { applyOperator('+'); } /** * The 'minus' button was pressed. */ public void minus() { applyOperator('-'); } /** * The '=' button was pressed. */ public void equals() { // This should completes the building of a second operand, // so ensure that we really have a left operand, an operator // and a right operand. if(haveLeftOperand && lastOperator != '?' && buildingDisplayValue) { calculateResult(); lastOperator = '?'; buildingDisplayValue = false; } else { keySequenceError(); } } /** * The 'C' (clear) button was pressed. * Reset everything to a starting state. */ public void clear() { lastOperator = '?'; haveLeftOperand = false; buildingDisplayValue = false; displayValue = 0; } /** * @return The title of this calculation engine. */ public String getTitle() { return "Java Calculator"; } /** * @return The author of this engine. */ public String getAuthor() { return "David J. Barnes and Michael Kolling"; } /** * @return The version number of this engine. */ public String getVersion() { return "Version 1.0"; } /** * Combine leftOperand, lastOperator, and the * current display value. * The result becomes both the leftOperand and * the new display value. */ private void calculateResult() { switch(lastOperator) { case '+': displayValue = leftOperand + displayValue; haveLeftOperand = true; leftOperand = displayValue; break; case '-': displayValue = leftOperand - displayValue; haveLeftOperand = true; leftOperand = displayValue; break; default: keySequenceError(); break; } } /** * Apply an operator. * @param operator The operator to apply. */ private void applyOperator(char operator) { // If we are not in the process of building a new operand // then it is an error, unless we have just calculated a // result using '='. if(!buildingDisplayValue && !(haveLeftOperand && lastOperator == '?')) { keySequenceError(); return; } if(lastOperator != '?') { // First apply the previous operator. calculateResult(); } else { // The displayValue now becomes the left operand of this // new operator. haveLeftOperand = true; leftOperand = displayValue; } lastOperator = operator; buildingDisplayValue = false; } /** * Report an error in the sequence of keys that was pressed. */ private void keySequenceError() { System.out.println("A key sequence error has occurred."); // Reset everything. clear(); } }

    Read the article

  • How do I get my code to read the spaces between longs?

    - by WahtsUpWorld
    I apologize for any inconvenience that may occur in answering my question, I'm fairly new to programming and I'm so far only in the last weeks of my community college Java I class. The problem I am facing is in my code of which I cannot seem to get the PrintWriter to address the spaces in between my longs' phone number and social security I.D. The entire code consists of two classes in which one pulls from the other the information needed to parse and present the file writer/print writer. Here is the entire code w/ the second class after it: public class FinalProjectGroup1 { public static void main(String[] args) { } public String name; public long ssid; public double pay; public String address; public long number; public void cleanUpConstructor() {} public FinalProjectGroup1(String name, String address, double pay, long ssid, long number){ this.name = name; this.pay = pay; this.ssid = ssid; this.address = address; this.number = number; cleanUpConstructor(); } public void setName(String name) { this.name = name; } public String getName() { return name; } public void setPay(double pay) { this.pay = pay; } public double getPay() { return pay; } public void setSSID(long ssid) { this.ssid = ssid; } public long getSSID() { return ssid; } public void setAddress(String address) { this.address = address; } public String getAddress() { return address; } public void setNumber(long number) { this.number = number; } public long getNumber() { return number; } } SECOND CLASS import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JLabel; import java.awt.Font; import javax.swing.JFileChooser; import javax.swing.JButton; import javax.swing.JTextField; import FinalProjectGroup1; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.io.FileWriter; import java.io.PrintWriter; public class FinalProjectGroup1Window { public JFrame frmTheBosssSecretary; public JTextField txtName; public JTextField txtSSID; public JTextField txtAddress; public JTextField txtNumber; public JTextField txtPay; public JTextField txtFindName; public JTextField txtFindSSID; public JTextField txtFindPay; public JTextField txtFolder; public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { FinalProjectGroup1Window window = new FinalProjectGroup1Window(); window.frmTheBosssSecretary.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } public FinalProjectGroup1Window() { initialize(); } private void initialize() { frmTheBosssSecretary = new JFrame(); frmTheBosssSecretary.setFont(new Font("Times New Roman", Font.PLAIN, 12)); frmTheBosssSecretary.setTitle("The Boss's Secretary: Employee Generator/Finder"); frmTheBosssSecretary.setBounds(100, 100, 547, 302); frmTheBosssSecretary.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frmTheBosssSecretary.getContentPane().setLayout(null); JLabel lblFile = new JLabel("Employee Folder:"); lblFile.setFont(new Font("Times New Roman", Font.PLAIN, 12)); lblFile.setBounds(10, 10, 93, 14); frmTheBosssSecretary.getContentPane().add(lblFile); JLabel lblFindEmployee = new JLabel("Employee Finder"); lblFindEmployee.setFont(new Font("Times New Roman", Font.BOLD, 18)); lblFindEmployee.setBounds(194, 159, 142, 20); frmTheBosssSecretary.getContentPane().add(lblFindEmployee); JLabel lblEmployeeName = new JLabel("Employee Name:"); lblEmployeeName.setFont(new Font("Times New Roman", Font.PLAIN, 12)); lblEmployeeName.setBounds(10, 35, 93, 14); frmTheBosssSecretary.getContentPane().add(lblEmployeeName); JLabel lblSSID = new JLabel("Employee SSID:"); lblSSID.setFont(new Font("Times New Roman", Font.PLAIN, 12)); lblSSID.setBounds(10, 135, 85, 14); frmTheBosssSecretary.getContentPane().add(lblSSID); JLabel lblAddress = new JLabel("Employee Address:"); lblAddress.setFont(new Font("Times New Roman", Font.PLAIN, 12)); lblAddress.setBounds(10, 60, 105, 14); frmTheBosssSecretary.getContentPane().add(lblAddress); JLabel lblPhoneNumber = new JLabel("Employee Phone Number:"); lblPhoneNumber.setFont(new Font("Times New Roman", Font.PLAIN, 12)); lblPhoneNumber.setBounds(10, 85, 134, 14); frmTheBosssSecretary.getContentPane().add(lblPhoneNumber); JLabel lblPayRate = new JLabel("Employee Pay Rate:"); lblPayRate.setFont(new Font("Times New Roman", Font.PLAIN, 12)); lblPayRate.setBounds(10, 110, 105, 14); frmTheBosssSecretary.getContentPane().add(lblPayRate); JLabel lblFindEmployeeName = new JLabel("Find Employee Name:"); lblFindEmployeeName.setFont(new Font("Times New Roman", Font.PLAIN, 12)); lblFindEmployeeName.setBounds(10, 183, 115, 14); frmTheBosssSecretary.getContentPane().add(lblFindEmployeeName); JLabel lblFindSSID = new JLabel("Find Employee SSID:"); lblFindSSID.setFont(new Font("Times New Roman", Font.PLAIN, 12)); lblFindSSID.setBounds(10, 208, 105, 14); frmTheBosssSecretary.getContentPane().add(lblFindSSID); JLabel lblFindPay = new JLabel("Find Employee Address:"); lblFindPay.setFont(new Font("Times New Roman", Font.PLAIN, 12)); lblFindPay.setBounds(10, 233, 124, 14); frmTheBosssSecretary.getContentPane().add(lblFindPay); txtFolder = new JTextField(); txtFolder.setFont(new Font("Times New Roman", Font.PLAIN, 12)); txtFolder.setBounds(105, 7, 314, 20); frmTheBosssSecretary.getContentPane().add(txtFolder); txtFolder.setColumns(10); txtName = new JTextField(); txtName.setFont(new Font("Times New Roman", Font.PLAIN, 12)); txtName.setBounds(99, 32, 247, 20); frmTheBosssSecretary.getContentPane().add(txtName); txtName.setColumns(10); txtAddress = new JTextField(); txtAddress.setFont(new Font("Times New Roman", Font.PLAIN, 12)); txtAddress.setBounds(109, 57, 237, 20); frmTheBosssSecretary.getContentPane().add(txtAddress); txtAddress.setColumns(10); txtNumber = new JTextField(); txtNumber.setFont(new Font("Times New Roman", Font.PLAIN, 12)); txtNumber.setBounds(141, 82, 160, 20); frmTheBosssSecretary.getContentPane().add(txtNumber); txtNumber.setColumns(10); txtPay = new JTextField(); txtPay.setFont(new Font("Times New Roman", Font.PLAIN, 12)); txtPay.setBounds(116, 107, 105, 20); frmTheBosssSecretary.getContentPane().add(txtPay); txtPay.setColumns(10); txtSSID = new JTextField(); txtSSID.setFont(new Font("Times New Roman", Font.PLAIN, 12)); txtSSID.setBounds(97, 132, 124, 20); frmTheBosssSecretary.getContentPane().add(txtSSID); txtSSID.setColumns(10); txtFindName = new JTextField(); txtFindName.setFont(new Font("Times New Roman", Font.PLAIN, 12)); txtFindName.setBounds(122, 180, 314, 20); frmTheBosssSecretary.getContentPane().add(txtFindName); txtFindName.setColumns(10); txtFindSSID = new JTextField(); txtFindSSID.setFont(new Font("Times New Roman", Font.PLAIN, 12)); txtFindSSID.setBounds(122, 205, 122, 20); frmTheBosssSecretary.getContentPane().add(txtFindSSID); txtFindSSID.setColumns(10); txtFindPay = new JTextField(); txtFindPay.setFont(new Font("Times New Roman", Font.PLAIN, 12)); txtFindPay.setBounds(141, 230, 237, 20); frmTheBosssSecretary.getContentPane().add(txtFindPay); txtFindPay.setColumns(10); JButton btnAddEmployee = new JButton("Add Employee"); btnAddEmployee.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { try { String name = txtName.getText(); String address = txtAddress.getText(); double pay = Double.parseDouble(txtPay.getText()); long ssid = Long.parseLong(txtSSID.getText()); long number = Long.parseLong(txtNumber.getText()); FinalProjectGroup1 ee = new FinalProjectGroup1(name, address, pay, ssid, number); FileWriter writer = new FileWriter(txtFolder.getText(), true); PrintWriter pw = new PrintWriter(writer); pw.println(ee.getName() + ", " + ee.getAddress() + ", " + ee.getNumber() + ", " + ee.getPay() + ", " + ee.getSSID()); pw.close(); } catch (Exception e) { return; } } }); JButton btnFolder = new JButton("Folder"); btnFolder.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { JFileChooser bsearch = new JFileChooser(); int result = bsearch.showOpenDialog(null); if (result != JFileChooser.APPROVE_OPTION) return; txtFolder.setText(bsearch.getSelectedFile().getAbsolutePath()); } }); btnFolder.setFont(new Font("Times New Roman", Font.PLAIN, 12)); btnFolder.setBounds(429, 6, 75, 23); frmTheBosssSecretary.getContentPane().add(btnFolder); btnAddEmployee.setFont(new Font("Times New Roman", Font.PLAIN, 12)); btnAddEmployee.setBounds(356, 42, 159, 107); frmTheBosssSecretary.getContentPane().add(btnAddEmployee); JButton btnFindName = new JButton("Find"); btnFindName.setFont(new Font("Times New Roman", Font.PLAIN, 12)); btnFindName.setBounds(446, 179, 69, 23); frmTheBosssSecretary.getContentPane().add(btnFindName); JButton btnFindSSID = new JButton("Find"); btnFindSSID.setFont(new Font("Times New Roman", Font.PLAIN, 12)); btnFindSSID.setBounds(250, 204, 85, 23); frmTheBosssSecretary.getContentPane().add(btnFindSSID); JButton btnFindAddress = new JButton("Find"); btnFindAddress.setFont(new Font("Times New Roman", Font.PLAIN, 12)); btnFindAddress.setBounds(389, 229, 85, 23); frmTheBosssSecretary.getContentPane().add(btnFindAddress); } } The problem here lies in the JButton Add Employee. Where, as previously mentioned, the long's phone number and social security I.D. don't show the spaces in the text file.

    Read the article

  • Repaint() not calling paint() in Java

    - by Joshua Auriemma
    Let me start off by saying I know I've violated some basic Java principles in this messy code, but I'm desperately trying to finish a program by Tuesday for a social science experiment, and I don't know Java, so I'm basically just fumbling through it for now. With that disclaimer out of the way, I have a separate program working where a circle is moving around the screen and the user must click on it. It works fine when its in its own separate class file, but when I add the code to my main program, it's no longer working. I don't even really understand why repaint() calls my paint() function — as far as I'm concerned, it's magic, but I've noticed that repaint() calls paint() in my test program, but not in the more complicated actual program, and I assume that's why the circle is no longer painting on my program. Entire code is below: import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Rectangle; import javax.swing.*; import java.awt.event.*; import java.awt.geom.Ellipse2D; import java.io.FileReader; import java.io.IOException; import java.util.Calendar; public class Reflexology1 extends JFrame{ private static final long serialVersionUID = -1295261024563143679L; private Ellipse2D ball = new Ellipse2D.Double(0, 0, 25, 25); private Timer moveBallTimer; int _ballXpos, _ballYpos; JButton button1, button2; JButton movingButton; JTextArea textArea1; int buttonAClicked, buttonDClicked; private long _openTime = 0; private long _closeTime = 0; JPanel thePanel = new JPanel(); JPanel thePlacebo = new JPanel(); final JFrame frame = new JFrame("Reflexology"); final JFrame frame2 = new JFrame("The Test"); JLabel label1 = new JLabel("Press X and then click the moving dot as fast as you can."); public static void main(String[] args){ new Reflexology1(); } public Reflexology1(){ frame.setSize(600, 475); frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setTitle("Reflexology 1.0"); frame.setResizable(false); frame2.setSize(600, 475); frame2.setLocationRelativeTo(null); frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame2.setTitle("Reflexology 1.0"); frame2.setResizable(false); button1 = new JButton("Accept"); button2 = new JButton("Decline"); //movingButton = new JButton("Click Me"); ListenForAcceptButton lForAButton = new ListenForAcceptButton(); ListenForDeclineButton lForDButton = new ListenForDeclineButton(); button1.addActionListener(lForAButton); button2.addActionListener(lForDButton); //movingButton.addActionListener(lForMButton); JTextArea textArea1 = new JTextArea(24, 50); textArea1.setText("Tracking Events\n"); textArea1.setLineWrap(true); textArea1.setWrapStyleWord(true); textArea1.setSize(15, 50); textArea1.setEditable(false); FileReader reader = null; try { reader = new FileReader("EULA.txt"); textArea1.read(reader, "EULA.txt"); } catch (IOException exception) { System.err.println("Problem loading file"); exception.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException exception) { System.err.println("Error closing reader"); exception.printStackTrace(); } } } JScrollPane scrollBar1 = new JScrollPane(textArea1, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); AdjustmentListener listener = new MyAdjustmentListener(); thePanel.add(scrollBar1); thePanel.add(button1); thePanel.add(button2); frame.add(thePanel); ListenForMouse lForMouse = new ListenForMouse(); thePlacebo.addMouseListener(lForMouse); thePlacebo.add(label1); frame2.add(thePlacebo); ListenForWindow lForWindow = new ListenForWindow(); frame.addWindowListener(lForWindow); frame2.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent e){ if(e.getKeyChar() == 'X' || e.getKeyChar() == 'x') {moveBallTimer.start();} } }); frame.setVisible(true); moveBallTimer = new Timer(1000, new ActionListener() { public void actionPerformed(ActionEvent e) { moveBall(); System.out.println("Timer started!"); repaint(); } }); addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent e) { if(frame2.isVisible()){ moveBallTimer.start(); } } }); } private class ListenForAcceptButton implements ActionListener{ public void actionPerformed(ActionEvent e){ if (e.getSource() == button1){ Calendar ClCDateTime = Calendar.getInstance(); System.out.println(ClCDateTime.getTimeInMillis() - _openTime); _closeTime = ClCDateTime.getTimeInMillis() - _openTime; //frame.getContentPane().remove(thePanel); //thePlacebo.addKeyListener(lForKeys); //frame.getContentPane().add(thePlacebo); //frame.repaint(); //moveBallTimer.start(); frame.setVisible(false); frame2.setVisible(true); frame2.revalidate(); frame2.repaint(); } } } private class ListenForDeclineButton implements ActionListener{ public void actionPerformed(ActionEvent e){ if (e.getSource() == button2){ JOptionPane.showMessageDialog(Reflexology1.this, "You've declined the license agreement. DO NOT RESTART the program. Please go inform a researcher that you have declined the agreement.", "WARNING", JOptionPane.INFORMATION_MESSAGE); System.exit(0); } } } private class ListenForWindow implements WindowListener{ public void windowActivated(WindowEvent e) { //textArea1.append("Window is active"); } // if this.dispose() is called, this is called: public void windowClosed(WindowEvent arg0) { } // When a window is closed from a menu, this is called: public void windowClosing(WindowEvent arg0) { } // Called when the window is no longer the active window: public void windowDeactivated(WindowEvent arg0) { //textArea1.append("Window is NOT active"); } // Window gone from minimized to normal state public void windowDeiconified(WindowEvent arg0) { //textArea1.append("Window is in normal state"); } // Window has been minimized public void windowIconified(WindowEvent arg0) { //textArea1.append("Window is minimized"); } // Called when the Window is originally created public void windowOpened(WindowEvent arg0) { //textArea1.append("Let there be Window!"); Calendar OlCDateTime = Calendar.getInstance(); _openTime = OlCDateTime.getTimeInMillis(); //System.out.println(_openTime); } } private class MyAdjustmentListener implements AdjustmentListener { public void adjustmentValueChanged(AdjustmentEvent arg0) { AdjustmentEvent scrollBar1; //System.out.println(scrollBar1.getValue())); } } public void paint(Graphics g) { //super.paint(g); frame2.paint(g); Graphics2D g2d = (Graphics2D) g; g2d.setColor(Color.RED); g2d.fill(ball); System.out.println("Calling fill()"); } protected void moveBall() { //System.out.println("I'm in the moveBall() function!"); int width = getWidth(); int height = getHeight(); int min, max, randomX, randomY; min =200; max = -200; randomX = min + (int)(Math.random() * ((max - min)+1)); randomY = min + (int)(Math.random() * ((max - min)+1)); //System.out.println(randomX + ", " + randomY); Rectangle ballBounds = ball.getBounds(); //System.out.println(ballBounds.x + ", " + ballBounds.y); if (ballBounds.x + randomX < 0) { randomX = 200; } else if (ballBounds.x + ballBounds.width + randomX > width) { randomX = -200; } if (ballBounds.y + randomY < 0) { randomY = 200; } else if (ballBounds.y + ballBounds.height + randomY > height) { randomY = -200; } ballBounds.x += randomX; ballBounds.y += randomY; _ballXpos = ballBounds.x; _ballYpos = ballBounds.y; ball.setFrame(ballBounds); } public void start() { moveBallTimer.start(); } public void stop() { moveBallTimer.stop(); } private class ListenForMouse implements MouseListener{ // Called when the mouse is clicked public void mouseClicked(MouseEvent e) { //System.out.println("Mouse Panel pos: " + e.getX() + " " + e.getY() + "\n"); if (e.getX() >=_ballXpos && e.getX() <= _ballXpos + 25 && e.getY() <=_ballYpos && e.getY() >= _ballYpos - 25 ) { System.out.println("TRUE"); } System.out.println("{e.getX(): " + e.getX() + " / " + "_ballXpos: " + _ballXpos + " | " + "{e.getY(): " + e.getY() + " / " + "_ballYpos: " + _ballYpos); } public void mouseEntered(MouseEvent arg0) { // TODO Auto-generated method stub } public void mouseExited(MouseEvent arg0) { // TODO Auto-generated method stub } public void mousePressed(MouseEvent arg0) { // TODO Auto-generated method stub } public void mouseReleased(MouseEvent arg0) { // TODO Auto-generated method stub } } // System.out.println("e.getX(): " + e.getX() + " / " + "_ballXpos: " + _ballXpos); // Mouse over public void mouseEntered(MouseEvent arg0) { // TODO Auto-generated method stub } // Mouse left the mouseover area: public void mouseExited(MouseEvent arg0) { // TODO Auto-generated method stub } public void mousePressed(MouseEvent arg0) { // TODO Auto-generated method stub } public void mouseReleased(MouseEvent arg0) { // TODO Auto-generated method stub } } Could anyone tell me what I need to do to get repaint() to call the paint() method in the above program? I'm assuming the multiple frames is causing the problem, but that's just a guess. Thanks.

    Read the article

  • Outer class jframe is not hiding when calling the inner class jframe

    - by user2909960
    When i am calling the inner jframe, it is called, but outer jframe is not hiding. instead it gets overlapped. so what will be the solution for this. Is there any way to get out of this. As i tried when i am calling the inner class frame, the outer class frame is also called, and it is not hidden. package com.exp.example; import java.awt.Color; import java.awt.Container; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JTextField; @SuppressWarnings("serial") public class A extends JFrame implements ActionListener { JFrame rframe = new JFrame(); JLabel CFirstName; JTextField Cfname; JButton jbsubmit; Container cp; public A() { rframe.setSize(500, 200); rframe.setLocationRelativeTo(null); cp = getContentPane(); cp.setLayout(null); setSize(550, 300); rframe.setTitle("Outer Frame"); cp.setBackground(new Color(140, 180, 180)); CFirstName = new JLabel("First Name"); Cfname = new JTextField(10); jbsubmit = new JButton("PREVIEW"); CFirstName.setBounds(10, 20, 100, 35); Cfname.setBounds(150, 20, 150, 25); jbsubmit.setBounds(190, 110, 92, 25); cp.add(CFirstName); cp.add(Cfname); cp.add(jbsubmit); jbsubmit.addActionListener(this); rframe.add(cp); rframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); rframe.setVisible(true); } public void actionPerformed(ActionEvent ae) { String action = ae.getActionCommand(); if (action == "PREVIEW") { /* Write the code here * When we click on preview button the frame of outer class(class A) gets * deactivated(closed) and inner frame, frame of inner class(class B) gets visible. * it should not be overlapped. */ /* My Code */ new B(); rframe.setVisible(false); } } public class B { JFrame frm = new JFrame(); Container cp; public B() { frm.setSize(500, 200); frm.setLocationRelativeTo(null); cp = getContentPane(); cp.setLayout(null); setSize(550, 300); frm.setTitle("Inner Frame"); cp.setBackground(new Color(140, 180, 180)); JLabel cpn = new JLabel("hello"); cpn.setBounds(10, 20, 100, 35); cp.add(cpn); frm.add(cp); frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frm.setVisible(true); } } public static void main(String[] args) { new A(); } }

    Read the article

  • InputText inside Primefaces dataTable is not refreshed

    - by robson
    I need to have inputTexts inside datatable when form is in editable mode. Everything works properly except form cleaning with immediate="true" (without form validation). Then primefaces datatable behaves unpredictable. After filling in datatable with new data - it still stores old values. Short example: test.xhtml <h:body> <h:form id="form"> <p:dataTable var="v" value="#{test.list}" id="testTable"> <p:column headerText="Test value"> <p:inputText value="#{v}"/> </p:column> </p:dataTable> <h:dataTable var="v" value="#{test.list}" id="testTable1"> <h:column> <f:facet name="header"> <h:outputText value="Test value" /> </f:facet> <p:inputText value="#{v}" /> </h:column> </h:dataTable> <p:dataTable var="v" value="#{test.list}" id="testTable2"> <p:column headerText="Test value"> <h:outputText value="#{v}" /> </p:column> </p:dataTable> <p:commandButton value="Clear" actionListener="#{test.clear()}" immediate="true" update=":form:testTable :form:testTable1 :form:testTable2"/> <p:commandButton value="Update" actionListener="#{test.update()}" update=":form:testTable :form:testTable1 :form:testTable2"/> </h:form> </h:body> And java: import java.io.Serializable; import java.util.ArrayList; import java.util.List; import javax.annotation.PostConstruct; import javax.faces.bean.ViewScoped; import javax.inject.Inject; import javax.inject.Named; @Named @ViewScoped public class Test implements Serializable { private static final long serialVersionUID = 1L; private List<String> list; @PostConstruct private void init(){ update(); } public List<String> getList() { return list; } public void setList(List<String> list) { this.list = list; } public void clear() { list = new ArrayList<String>(); } public void update() { list = new ArrayList<String>(); list.add("Item 1"); list.add("Item 2"); } } In the example above I have 3 configurations: 1. p:dataTable with p:inputText 2. h:dataTable with p:inputText 3. p:dataTable with h:outputText And 2 buttons: first clears data, second applies data Workflow: 1. Try to change data in inputTexts in p:dataTable and h:dataTable 2. Clear data of list (arrayList of string) - click "clear" button (imagine that you click cancel on form because you don't want to store data to database) 3. Load new data - click "update" button (imagine that you are openning new form with new data) Question: Why p:dataTable with p:inputText still stores manually changed data, not the loaded ones? Is there any way to force p:dataTable to behaving like h:dataTable in this case?

    Read the article

  • How can I Implement KeyListeners/ActionListeners into the JFrame?

    - by A.K.
    I'll get to the point: I have a player in my game that you control with the keyboard yet the key methods in the player class and ActionListener w/ KeyAdapter in the Board class don't seem to fire. So far I've tried adding these key methods into the JFrame, doesn't seem to let me move him even though other objects that I have (enemies) can move fine. Here's part of the JFrame class with the event listeners: frm.addKeyListener(KeyBoardListener); public void mouseClicked(MouseEvent e) { nSound.play(); StartB.setContentAreaFilled(false); cards.remove(StartB); frm.remove(TitleL); frm.remove(cards); frm.setLayout(new GridLayout(1, 1)); frm.add(nBoard); //Add Game "Tiles" Or Content. x = 1200 nBoard.setPreferredSize(new Dimension(1200, 420)); cards.revalidate(); frm.validate(); } public KeyListener KeyBoardListener = new KeyListener() { @Override public void keyPressed(KeyEvent args0) { int key = args0.getKeyCode(); if(key == KeyEvent.VK_LEFT) { nBoard.S.vx = -4; } if(key == KeyEvent.VK_RIGHT) { nBoard.S.vx = 4; } if(key == KeyEvent.VK_UP) { nBoard.S.vy = -4; } if(key == KeyEvent.VK_DOWN) { nBoard.S.vy = 4; } if(key == KeyEvent.VK_SPACE) { nBoard.S.fire(); } } @Override public void keyReleased(KeyEvent args0) { int key = args0.getKeyCode(); if(key == KeyEvent.VK_LEFT) { nBoard.S.vx = 0; } if(key == KeyEvent.VK_RIGHT) { nBoard.S.vx = 0; } if(key == KeyEvent.VK_UP) { nBoard.S.vy = 0; } if(key == KeyEvent.VK_DOWN) { nBoard.S.vy = 0; } } @Override public void keyTyped(KeyEvent args0) { // TODO Auto-generated method stub } };

    Read the article

  • How to code a time delay between plotting points in JFreeCharts?

    - by Javajava
    Is there a way to animate the plotting process of an xy-line chart using JFreeCharts? I want to be able to watch the program draw each line segment and connect them. For example, if I paste this into the TextArea, "gtgtaaacaatatatggcg," I want to watch it graph each line segment one by one. Thanks in advance! :) My code is below: import java.util.Scanner; import java.applet.Applet; import java.awt.; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import org.jfree.chart.; import org.jfree.chart.plot.PlotOrientation; import org.jfree.data.xy.*; public class RandomWalkComplete extends Applet implements ActionListener { Panel panel; TextArea textarea, outputArea; Button move,exit; String thetext; Scanner reader = new Scanner(System.in); String thetext2; Label instructions; int x,y; public void init() { setSize(500,250); //set size of applet instructions=new Label("Paste the gene sequences in the " + "text field and press the graph button."); add(instructions); panel = new Panel(); add(panel); setVisible(true); textarea= new TextArea(10,20); add(textarea); move=new Button("Graph"); move.addActionListener(this); add(move); exit=new Button("Exit"); exit.addActionListener(this); add(exit); } public void actionPerformed(ActionEvent e) { XYSeries series = new XYSeries("DNA Walk",false,true); x= 0; y = 0; series.add(x,y); if(e.getSource() == move) { thetext=textarea.getText(); //the text is the DNA bases pasted thetext=thetext.replaceAll(" ",""); //removes spaces thetext2 = ""; for(int i=0; i<thetext.length(); i++) { char a = thetext.charAt(i); switch (a) { case 'A': case 'a'://moves right x+=1; y+=0; series.add(x,y); break; case 'C': case 'c': //moves up x+=0; y+=1; series.add(x,y); break; case 'G': case 'g': //move left x-=1; y+=0; series.add(x,y); break; case 'T': case 't'://move down x+=0; y-=1; series.add(x,y); break; default: // series.add(0,0); break; } } XYDataset xyDataset = new XYSeriesCollection(series); JFreeChart chart = ChartFactory.createXYLineChart ("DNA Random Walk", "", "", xyDataset, PlotOrientation.VERTICAL, true, true, false); ChartFrame frame1=new ChartFrame("DNA Random Walk",chart); frame1.setVisible(true); frame1.setSize(300,300); } if(e.getSource()==exit) {System.exit(0);} } public void stop(){} }

    Read the article

  • HTML Tidy in NetBeans IDE

    - by Geertjan
    First step in integrating HTML Tidy (via its JTidy implementation) into NetBeans IDE: The reason why I started doing this is because I want to integrate this into the pluggable analyzer functionality of NetBeans IDE that I recently blogged about, i.e., where the FindBugs functionality is found. So a logical first step is to get it working in an Action class, after which I can port it into the analyzer infrastructure: import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import org.openide.awt.ActionID; import org.openide.awt.ActionReference; import org.openide.awt.ActionReferences; import org.openide.awt.ActionRegistration; import org.openide.cookies.EditorCookie; import org.openide.cookies.LineCookie; import org.openide.loaders.DataObject; import org.openide.text.Line; import org.openide.text.Line.ShowOpenType; import org.openide.util.Exceptions; import org.openide.util.NbBundle.Messages; import org.openide.windows.IOProvider; import org.openide.windows.InputOutput; import org.openide.windows.OutputEvent; import org.openide.windows.OutputListener; import org.openide.windows.OutputWriter; import org.w3c.tidy.Tidy; @ActionID(     category = "Tools", id = "org.jtidy.TidyAction") @ActionRegistration(     displayName = "#CTL_TidyAction") @ActionReferences({     @ActionReference(path = "Loaders/text/html/Actions", position = 150),     @ActionReference(path = "Editors/text/html/Popup", position = 750) }) @Messages("CTL_TidyAction=Run HTML Tidy") public final class TidyAction implements ActionListener {     private final DataObject context;     private final OutputWriter writer;     private EditorCookie ec = null;     public TidyAction(DataObject context) {         this.context = context;         ec = context.getLookup().lookup(org.openide.cookies.EditorCookie.class);         InputOutput io = IOProvider.getDefault().getIO("HTML Tidy", false);         io.select();         writer = io.getOut();     }     @Override     public void actionPerformed(ActionEvent ev) {         Tidy tidy = new Tidy();         try {             writer.reset();             StringWriter stringWriter = new StringWriter();             PrintWriter errorWriter = new PrintWriter(stringWriter);             tidy.setErrout(errorWriter);             tidy.parse(context.getPrimaryFile().getInputStream(), System.out);             String[] split = stringWriter.toString().split("\n");             for (final String string : split) {                 final int end = string.indexOf(" c");                 if (string.startsWith("line")) {                     writer.println(string, new OutputListener() {                         @Override                         public void outputLineAction(OutputEvent oe) {                             LineCookie lc = context.getLookup().lookup(LineCookie.class);                             int lineNumber = Integer.parseInt(string.substring(0, end).replace("line ", ""));                             Line line = lc.getLineSet().getOriginal(lineNumber - 1);                             line.show(ShowOpenType.OPEN, Line.ShowVisibilityType.FOCUS);                         }                         @Override                         public void outputLineSelected(OutputEvent oe) {}                         @Override                         public void outputLineCleared(OutputEvent oe) {}                     });                 }             }         } catch (IOException ex) {             Exceptions.printStackTrace(ex);         }     } } The string parsing above is ugly but gets the job done for now. A problem integrating this into the pluggable analyzer functionality is the limitation of its scope. The analyzer lets you select one or more projects, or individual files, but not a folder. So it doesn't work on folders in the Favorites window, for example, which is where I'd like to apply HTML Tidy, across multiple folders via the analyzer functionality. That's a bit of a bummer that I'm hoping to get around somehow.

    Read the article

  • How to make a character jump, both on objects and just normal jump.

    - by haxerflaxer
    Hi, I'm kind of a beginner when it comes to java programming, and I have a project in school where I'm going to create a game much like Icy Tower. And my question is, how am I going to write to make the character stand on the ground and be able to jump up on objects? Here's my code so far: Part one package Sprites; import java.awt.Image; import java.awt.event.KeyEvent; import javax.swing.ImageIcon; public class jumper { private String jump = "oka.png"; private int dx; private int dy; private int x; private int y; private Image image; public jumper() { ImageIcon ii = new ImageIcon(this.getClass().getResource(jump)); image = ii.getImage(); x = 50; y = 100; } public void move() { x += dx; y += dy; } public int getX() { return x; } public int getY() { return y; } public Image getImage() { return image; } public void keyPressed(KeyEvent e) { int key = e.getKeyCode(); if (key == KeyEvent.VK_LEFT) { dx = -5; ImageIcon ii = new ImageIcon(this.getClass().getResource("oki.png")); image = ii.getImage(); } if (key == KeyEvent.VK_RIGHT){ dx = 5; ImageIcon ii = new ImageIcon(this.getClass().getResource("oka.png")); image = ii.getImage(); } if (key == KeyEvent.VK_SPACE) { dy = -5; } if (key == KeyEvent.VK_DOWN) { dy = 5; } } public void keyReleased(KeyEvent e) { int key = e.getKeyCode(); if (key == KeyEvent.VK_LEFT) { dx = 0; } if (key == KeyEvent.VK_RIGHT){ dx = 0; } if (key == KeyEvent.VK_SPACE) { dy = 0; } if (key == KeyEvent.VK_DOWN) { dy = 0; } } } Part two package Sprites; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import javax.swing.JPanel; import javax.swing.Timer; public class board extends JPanel implements ActionListener { private Timer klocka; private jumper jumper; public board() { addKeyListener(new TAdapter()); setFocusable(true); setBackground(Color.WHITE); setDoubleBuffered(true); jumper = new jumper(); klocka = new Timer(5, this); klocka.start(); } public void paint(Graphics g) { super.paint(g); Graphics2D g2d = (Graphics2D)g; g2d.drawImage(jumper.getImage(), jumper.getX(), jumper.getY(), this); Toolkit.getDefaultToolkit().sync(); g.dispose(); } public void actionPerformed(ActionEvent e) { jumper.move(); repaint(); } private class TAdapter extends KeyAdapter { public void keyReleased(KeyEvent e) { jumper.keyReleased(e); } public void keyPressed(KeyEvent e) { jumper.keyPressed(e); } } } Part three package Sprites; import javax.swing.JFrame; public class RType extends JFrame { public RType() { add(new board()); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(800, 600); setLocationRelativeTo(null); setTitle("R - type"); setResizable(false); setVisible(true); } public static void main(String[] args) { new RType(); } } I really appreciate all the help I can get!

    Read the article

  • How do you make a character jump, both on objects and just normal jump?

    - by haxerflaxer
    Hi, I'm kind of a beginner when it comes to java programming, and I have a project in school where I'm going to create a game much like Icy Tower. And my question is, how am I going to write to make the character stand on the ground and be able to jump up on objects? Here's my code so far: Part one package Sprites; import java.awt.Image; import java.awt.event.KeyEvent; import javax.swing.ImageIcon; public class jumper { private String jump = "oka.png"; private int dx; private int dy; private int x; private int y; private Image image; public jumper() { ImageIcon ii = new ImageIcon(this.getClass().getResource(jump)); image = ii.getImage(); x = 50; y = 100; } public void move() { x += dx; y += dy; } public int getX() { return x; } public int getY() { return y; } public Image getImage() { return image; } public void keyPressed(KeyEvent e) { int key = e.getKeyCode(); if (key == KeyEvent.VK_LEFT) { dx = -5; ImageIcon ii = new ImageIcon(this.getClass().getResource("oki.png")); image = ii.getImage(); } if (key == KeyEvent.VK_RIGHT){ dx = 5; ImageIcon ii = new ImageIcon(this.getClass().getResource("oka.png")); image = ii.getImage(); } if (key == KeyEvent.VK_SPACE) { dy = -5; } if (key == KeyEvent.VK_DOWN) { dy = 5; } } public void keyReleased(KeyEvent e) { int key = e.getKeyCode(); if (key == KeyEvent.VK_LEFT) { dx = 0; } if (key == KeyEvent.VK_RIGHT){ dx = 0; } if (key == KeyEvent.VK_SPACE) { dy = 0; } if (key == KeyEvent.VK_DOWN) { dy = 0; } } } Part two package Sprites; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import javax.swing.JPanel; import javax.swing.Timer; public class board extends JPanel implements ActionListener { private Timer klocka; private jumper jumper; public board() { addKeyListener(new TAdapter()); setFocusable(true); setBackground(Color.WHITE); setDoubleBuffered(true); jumper = new jumper(); klocka = new Timer(5, this); klocka.start(); } public void paint(Graphics g) { super.paint(g); Graphics2D g2d = (Graphics2D)g; g2d.drawImage(jumper.getImage(), jumper.getX(), jumper.getY(), this); Toolkit.getDefaultToolkit().sync(); g.dispose(); } public void actionPerformed(ActionEvent e) { jumper.move(); repaint(); } private class TAdapter extends KeyAdapter { public void keyReleased(KeyEvent e) { jumper.keyReleased(e); } public void keyPressed(KeyEvent e) { jumper.keyPressed(e); } } } Part three package Sprites; import javax.swing.JFrame; public class RType extends JFrame { public RType() { add(new board()); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(800, 600); setLocationRelativeTo(null); setTitle("R - type"); setResizable(false); setVisible(true); } public static void main(String[] args) { new RType(); } } I really appreciate all the help I can get!

    Read the article

  • won't repaint a different Month after pressing button in my calendar

    - by DarkStar123
    I'm trying to build a Calendar in Java as a little project I thought of, But I can't seem to change the name of the Month every time I click the Next button. here's my code! package drawing; import javax.swing.*; import java.awt.*; import java.awt.event.*; public class Drawing_something extends JPanel{ int[] calender_squares = {1, 2, 3, 4, 5, 6, 7}; String[] Month = {"January", "February", "March", "April","May","June","July", "August","September","October","November","December"}; int i = 0; Graphics c; @Override public void paintComponent(Graphics c){ super.paintComponent(c); this.setBackground(Color.WHITE); int WIDTH = 55, HEIGHT = 65; for (int in: calender_squares) { for (int counter = 0; counter < 7; counter++){ c.drawRect(50, 50, 100, 100); c.drawRect(50, 50, 700, 500); c.copyArea(50, 50, 600, 500, 100, 0); c.copyArea(50, 50, 600, 400, 0, 100); } } for (int date = 1; date <= 30; date++) { String s = String.valueOf(date); c.drawString(s, WIDTH, HEIGHT); if (date <= 6){ WIDTH += 100; } else if (date == 7){ WIDTH = 55; HEIGHT = 165; }else if (date <= 13){ WIDTH += 100; }else if (date == 14){ WIDTH = 55; HEIGHT = 265; }else if (date <= 20){ WIDTH += 100; }else if (date == 21){ WIDTH = 55; HEIGHT = 365; }else if (date <= 27){ WIDTH += 100; }else if (date == 28){ WIDTH = 55; HEIGHT = 465; }else if (date <= 30){ WIDTH += 100; } } c.setFont(new Font("default", Font.BOLD, 40)); c.drawString(Month[i], 320, 45); } public Drawing_something(){ setLayout(new BorderLayout()); JButton N = new JButton("NEXT"); JButton B = new JButton("BACK"); JPanel P = new JPanel(); P.add(B); P.add(N); add(P, BorderLayout.SOUTH); B.addActionListener(new HandlerClass()); N.addActionListener(new NextClass()); } public class HandlerClass implements ActionListener{ public void actionPerformed(ActionEvent e){ } } public class NextClass implements ActionListener{ public void actionPerformed(ActionEvent e){ if (i == 11){ i = 0; } i = i + 1; c.drawString(Month[i], 320, 45); } } public static void main(String[] args){ JFrame mainFrame = new JFrame("Calender"); mainFrame.add(new Drawing_something()); mainFrame.setSize(850, 650); mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); mainFrame.setVisible(true); } } if anyone could help that would be much appreciated!! Thanks in advance!!

    Read the article

  • Server-side DataTable Sorting in RichFaces

    - by sblundy
    I have a data table with a variable number of columns and a data scroller. How can I enable server side sorting? I prefer that it be fired by the user clicking the column header. <rich:datascroller for="instanceList" actionListener="#{pageDataModel.pageChange}"/> <rich:dataTable id="instanceList" rows="10" value="#{pageDataModel}" var="fieldValues" rowKeyVar="rowKey"> <rich:columns value="#{pageDataModel.columnNames}" var="column" index="idx"> <f:facet name="header"> <h:outputText value="#{column}"/> </f:facet> <h:outputText value="#{classFieldValues[idx]}" /> </rich:columns> </rich:dataTable> I already have a method on the bean for executing the sort. public void sort(int column)

    Read the article

  • Java Swing GUI Question: Open new panel with button clicked.

    - by bat
    Java Swing GUI: I am using ActionListener to preform the action when a button is clicked. What i want to do is when a button is clicked, open a new panel, but load/get the new panel from a different file. This is what i have so far but i rather just link to another file. THANKS! =] public void actionPerformed(java.awt.event.ActionEvent e) { //LINK TO NEW FILE INSEAD OF... JFrame frame2 = new JFrame("Clicked"); frame2.setVisible(true); frame2.setSize(200,200); }

    Read the article

  • Check if thread is EDT is necessary?

    - by YuppieNetworking
    Hello, I have an UI implemented with Swing. One component does some work that may take some time, so I use SwingUtilities.invokeLater. However, I was reading some old code and found this in an ActionListener: if (!SwingUtilities.isEventDispatchThread()) { SwingUtilities.invokeLater(new Runnable() { public void run() { // code X } }); } else { // code X } I thought that it made sense since it separates code X from the EDT. However, I found it error-prone since I have used it a couple of times and both times I forgot the else part. The question is: is the SwingUtilities.isEventDispatchThread() checking necessary? Or could I assume that I am not in the EDT and always use invokeLater? Thanks a lot.

    Read the article

  • Stop a stopwatch

    - by James Morgan
    I have the following code in a JPanel class which is added to a another class (JFrame). What I'm trying to implement is some sort of a stopwatch program. startBtn.addActionListener(new startListener()); class startListener implements ActionListener { public void actionPerformed(ActionEvent e) { Timer time = new Timer(); time.scheduleAtFixedRate(new Stopwatch(), 1000, 1000); } } This is another class which basically the task. public class Stopwatch extends TimerTask { private final double start = System.currentTimeMillis(); public void run() { double curr = System.currentTimeMillis(); System.out.println((curr - start) / 1000); } } The timer works fine and this is definitely far from complete but I'm not sure how to code the stop button which should stop the timer. Any advice on this? BTW I'm using java.util.timer

    Read the article

  • o display an image

    - by Vimal Basdeo
    I want to display an image from the web to a panel in another Jframe at the click of a button but whenever I click the button first the image loads and during this time the current form potentially freezes and once the image has loaded the form is displayed with the image.. How can I avoid the situation where my form freezes since it is very irritating My codes :: My current class private void btn_TrackbusActionPerformed(java.awt.event.ActionEvent evt) { try { sendMessage("Query,map,$,start,211,Arsenal,!"); System.out.println(receiveMessage()); } catch (UnknownHostException ex) { Logger.getLogger(client_Trackbus.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(client_Trackbus.class.getName()).log(Level.SEVERE, null, ex); } catch (Exception ex) { Logger.getLogger(client_Trackbus.class.getName()).log(Level.SEVERE, null, ex); } client_trackedbus nextform=new client_trackedbus(planform,connection,packet_receive,packet_send); this.setVisible(false); this.dispose(); nextform.setVisible(true); // TODO add your handling code here: } My next class that displays the image public class client_trackedbus extends javax.swing.JFrame { client_planform planform=null; DatagramSocket connection=null; DatagramPacket packet_receive=null; DatagramPacket packet_send=null; JLabel label=null; /** Creates new form client_trackedbus */ public client_trackedbus(client_planform planform,DatagramSocket connection,DatagramPacket packet_receive,DatagramPacket packet_send) { initComponents(); this.planform=planform; this.connection=connection; this.packet_receive=packet_receive; this.packet_send=packet_send; try { displayMap("http://www.huddletogether.com/projects/lightbox2/images/image-2.jpg", jPanel1, new JLabel()); } catch (MalformedURLException ex) { Logger.getLogger(client_trackedbus.class.getName()).log(Level.SEVERE, null, ex); } } private void displayMap(String url,JPanel panel,JLabel label) throws MalformedURLException{ URL imageurl=new URL(url); Image image=(Toolkit.getDefaultToolkit().createImage(imageurl)); ImageIcon icon = new ImageIcon(image); label.setIcon(icon); panel.add(label); // System.out.println(panel.getSize().width); this.getContentPane().add(panel); } /** 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() { jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); btn_Exit = new javax.swing.JButton(); btn_Plan = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Public Transport Journey Planner"); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 368, Short.MAX_VALUE) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 172, Short.MAX_VALUE) ); jLabel1.setFont(new java.awt.Font("Arial", 1, 18)); jLabel1.setText("Your tracked bus"); btn_Exit.setText("Exit"); btn_Exit.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btn_ExitActionPerformed(evt); } }); btn_Plan.setText("Plan journey"); btn_Plan.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btn_PlanActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(104, 104, 104) .addComponent(jLabel1)) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addGap(65, 65, 65) .addComponent(btn_Plan) .addGap(65, 65, 65) .addComponent(btn_Exit, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(20, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(35, 35, 35) .addComponent(jLabel1) .addGap(18, 18, 18) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btn_Exit) .addComponent(btn_Plan)) .addContainerGap(12, Short.MAX_VALUE)) ); pack(); }// </editor-fold> private void btn_ExitActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: Exitform(); } private void btn_PlanActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: this.setVisible(false); this.dispose(); this.planform.setVisible(true); } private void Exitform(){ this.setVisible(false); this.dispose(); } /** * @param args the command line arguments */ public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { // new client_trackedbus().setVisible(true); } }); } // Variables declaration - do not modify private javax.swing.JButton btn_Exit; private javax.swing.JButton btn_Plan; private javax.swing.JLabel jLabel1; private javax.swing.JPanel jPanel1; // End of variables declaration }

    Read the article

  • Java MVC - How to divide a done text game into MVC?

    - by Zopyrus
    Been sitting here for hours now trying to figure this out, so a bit sympathy for this large question. :) The Goal: I simply want to divide my done code into MVC (Model View Controller) parts. I have the game logics done and text based - the code works fine. The Problem: Well, I want to implement this code into MVC, but where do explain for the MODEL that it should use text-based? Because the VIEW is only for the layout (graphically) correct? I am having a REALLY hard time figuring out where to begin at all. Any pointers would be so nice! Here is my game logics code: import mind.*; import javax.swing.*; import java.util.*; import java.lang.*; import java.awt.*; public class Drive { String[] mellan; boolean gameEnd, checkempty, checkempty2, enemy, enemy2; String gr,rd,tom; int digits; public Drive() { // Gamepieces in textform gr="G"; rd="R"; tom=" "; mellan = new String[7]; String[] begin = {gr,gr,gr,tom,rd,rd,rd}; String[] end = {rd,rd,rd,tom,gr,gr,gr}; //input Scanner in = new Scanner(System.in); mellan=begin; gameEnd=false; while (gameEnd == false) { for(int i=0; i<mellan.length; i++) { System.out.print(mellan[i]); } System.out.print(" Choose 0-6: "); digits = in.nextInt(); move(); checkWin(); } } void move() { //BOOLEAN for gameruls!!! checkempty = digits<6 && mellan[digits+1]==tom; checkempty2 = digits>0 && mellan[digits-1]==tom; enemy = (mellan[digits]==gr && mellan[digits+1]==rd && mellan[digits+2]==tom); enemy2 = (mellan[digits]==rd && mellan[digits-1]==gr && mellan[digits-2]==tom); if(checkempty) { mellan[digits+1]=mellan[digits]; mellan[digits]=tom; } else if (checkempty2) { mellan[digits-1]=mellan[digits]; mellan[digits]=tom; } else if (enemy) { mellan[digits+2]=mellan[digits]; mellan[digits]=tom; } else if (enemy2) { mellan[digits-2]=mellan[digits]; mellan[digits]=tom; } } void checkWin() { String[] end = {rd,rd,rd,tom,gr,gr,gr}; for (int i=0; i<mellan.length; i++){ } if (Arrays.equals(mellan,end)) { for (int j=0; j<mellan.length; j++) { System.out.print(mellan[j]); } displayWin(); } } void displayWin() { gameEnd = true; System.out.println("\nNicely Done!"); return; } // Kör Drive! public static void main(String args[]) { new Drive(); } } Here is how I defined my DriveView thus far: (just trying to make one button to work) import mind.*; import javax.swing.*; import java.util.*; import java.lang.*; import java.awt.*; import java.awt.event.*; public class DriveView extends JFrame { JButton ruta1 = new JButton("Green"); JButton ruta2 = new JButton("Green"); JButton rutatom = new JButton(""); JButton ruta6 = new JButton("Red"); private DriveModel m_model; public DriveView(DriveModel model) { m_model = model; //Layout for View JPanel myPanel = new JPanel(); myPanel.setLayout(new FlowLayout()); myPanel.add(ruta1); myPanel.add(ruta2); myPanel.add(rutatom); myPanel.add(ruta6); this.setContentPane(myPanel); this.pack(); this.setTitle("Drive"); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } void addMouseListener(ActionListener mol) { ruta2.addActionListener(mol); } } And DriveController which gives me error at compile import mind.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.lang.*; public class DriveController { private DriveModel m_model; private DriveView m_view; public DriveController(DriveModel model, DriveView view) { m_model = model; m_view = view; view.addMouseListener(new MouseListener()); } class MouseListener implements ActionListener { public void actionPerformed(ActionEvent e) { String mening; mening = e.getActionCommand(); if (mening.equals("Green")) { setForeground(Color.red); } } } }

    Read the article

  • How to launch standard browser out of Java application?

    - by Peter
    Hi there how to I open a URL with the systems standard browser with Java? I currently use this code for opening a specific URL (locally stored html file), which works fine when I run the application with my IDE (Eclipse), but after bundling the software, it doesn't work any more. url = MainWindow.class.getResource("mySite.html"); helpMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { java.awt.Desktop.getDesktop().browse(url.toURI()); } catch (URISyntaxException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } } }); Any suggestsions? Thank you very much!

    Read the article

  • how to ignore the event onchange of a4j:support when clicking button

    - by bakkujp
    Hi All, I have a textbox like below <h:inputText value="#{bean.strQuantite}"> <a4j:support actionListener="#{tabacListCommandeAltadisDetailBean.actionListenerQuantity}" event="onchange" /> </h:inputText> I input some value into the textbox above and don't click outside the textbox yet. After that, I click a other button, then click event of button is not trigger. Instead of this, the event onchange of the inputtext above is trigger. I want to when clicking the button, the click event is trigged before. Can anyone help me to solve this problem ?

    Read the article

  • JPanel Layout Image Cutoff

    - by Trizicus
    I am adding images to a JPanel but the images are getting cut off. I was originally trying BorderLayout but that only worked for one image and adding others added image cut-off. So I switched to other layouts and the best and closest I could get was BoxLayout however that adds a very large cut-off which is not acceptable either. So basically; How can I add images (from a custom JComponent) to a custom JPanel without bad effects such as the one present in the code. Custom JPanel: import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.BoxLayout; import javax.swing.JPanel; import javax.swing.Timer; public class GraphicsPanel extends JPanel implements MouseListener { private Entity test; private Timer timer; private long startTime = 0; private int numFrames = 0; private float fps = 0.0f; GraphicsPanel() { test = new Entity("test.png"); Thread t1 = new Thread(test); t1.start(); Entity ent2 = new Entity("images.jpg"); ent2.setX(150); ent2.setY(150); Thread t2 = new Thread(ent2); t2.start(); Entity ent3 = new Entity("test.png"); ent3.setX(0); ent3.setY(150); Thread t3 = new Thread(ent3); t3.start(); //ESSENTIAL setLayout(new BoxLayout(this, BoxLayout.X_AXIS)); add(test); add(ent2); add(ent3); //GAMELOOP timer = new Timer(30, new Gameloop(this)); timer.start(); addMouseListener(this); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D) g.create(); g2.setClip(0, 0, getWidth(), getHeight()); g2.setColor(Color.BLACK); g2.drawString("FPS: " + fps, 1, 15); } public void getFPS() { ++numFrames; if (startTime == 0) { startTime = System.currentTimeMillis(); } else { long currentTime = System.currentTimeMillis(); long delta = (currentTime - startTime); if (delta > 1000) { fps = (numFrames * 1000) / delta; numFrames = 0; startTime = currentTime; } } } public void mouseClicked(MouseEvent e) {} public void mousePressed(MouseEvent e) {} public void mouseReleased(MouseEvent e) {} public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } class Gameloop implements ActionListener { private GraphicsPanel gp; Gameloop(GraphicsPanel gp) { this.gp = gp; } public void actionPerformed(ActionEvent e) { try { gp.getFPS(); gp.repaint(); } catch (Exception ez) { } } } } Main class: import java.awt.EventQueue; import javax.swing.JFrame; public class MainWindow { public static void main(String[] args) { new MainWindow(); } private JFrame frame; private GraphicsPanel gp = new GraphicsPanel(); MainWindow() { EventQueue.invokeLater(new Runnable() { public void run() { frame = new JFrame("Graphics Practice"); frame.setSize(680, 420); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(gp); } }); } } Custom JComponent import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import javax.imageio.ImageIO; import javax.swing.JComponent; public class Entity extends JComponent implements Runnable { private BufferedImage bImg; private int x = 0; private int y = 0; private int entityWidth, entityHeight; private String filename; Entity(String filename) { this.filename = filename; } public void run() { bImg = loadBImage(filename); entityWidth = bImg.getWidth(); entityHeight = bImg.getHeight(); setPreferredSize(new Dimension(entityWidth, entityHeight)); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2d = (Graphics2D) g.create(); g2d.drawImage(bImg, x, y, null); g2d.dispose(); } public BufferedImage loadBImage(String filename) { try { bImg = ImageIO.read(getClass().getResource(filename)); } catch (Exception e) { } return bImg; } public int getEntityWidth() { return entityWidth; } public int getEntityHeight() { return entityHeight; } public int getX() { return x; } public int getY() { return y; } public void setX(int x) { this.x = x; } public void setY(int y) { this.y = y; } }

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11  | Next Page >