Search Results

Search found 118 results on 5 pages for 'jtextfield'.

Page 5/5 | < Previous Page | 1 2 3 4 5 

  • how do you find the exact variable of a null pointer exception

    - by OVERTONE
    I've been at this one for a bit now. I've got a null pointer exception so im guessing somethings not been initialized. AdminMessages.inbox1.setText(messageRsetArray[0]); thats my code where its targetting. but i cant find what inside it hasnt been initiazed. AdminMessages is a class which contains a JTextField called inbox1, messageRsetArray is an array which has taken variables from an array. also inbox1 is static. i coulndt get the getters and setter to work. i know its bad practice though.

    Read the article

  • Add other components to JFrame with background

    - by bnabilos
    Hello, I want to add a background image to my JFrame but when I do it using the code below, I'm unable to add other elements like JLabel or JTextField. ImageIcon icon = new ImageIcon("src/images/back.jpg"); backImage = icon.getImage(); BackgroundImagePanel contentPane = new BackgroundImagePanel(); contentPane.setBackgroundImage(backImage); this.setContentPane(contentPane); Can you tell me please if there is another way to add JTabbedPane to a JFrame with a background ? Thank you.

    Read the article

  • Calling class in Java after editing file used in as source for table

    - by user2892290
    I'm currently working on a project, I'll try to subrscibe first. I save data into text file, that I use as a source for browser of that data. The browser is based on table that contains the data. I have to rewrite the source file everytime I delete or edit data. That's where the problem comes in. After deleting or editing data I call a method to create the table again, but the table never creates. Is it possibly made by editing the file and calling the method right after that? If I restart my app the table is successfully created with right data. Take in note that I don't get any error message. This is the method I use for loading data from source file: try (BufferedReader input1 = new BufferedReader(new FileReader("./src/data.src"))) { int lines = 0; while (input1.read() != -1) { if (!(input1.readLine()).equals("")) { lines++; } } input1.close(); if (lines == 0) { JOptionPane.showMessageDialog(null, "No data to load, create a note first!"); new Writer().build(frame); } else { try (BufferedReader input = new BufferedReader(new FileReader("./src/data.src"))) { Game[] g = new Game[lines]; String currentLine; String[] help; int counter = 0; while (lines > 0) { currentLine = input.readLine(); help = currentLine.split("#"); g[counter] = new Game(help[0],help[1], help[2], help[3], help[4], help[5], help[6], help[7], help[8], help[9]); counter++; lines--; } input.close(); final JButton bButton = new backButton().create(frame, mPanel); build(g, frame, bButton); mPanel.add(panel); mPanel.add(panel2); mPanel.add(searchPanel); mPanel.add(bButton); bButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { frame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); panel.removeAll(); frame.setCursor(Cursor.getDefaultCursor()); } }); mPanel.setPreferredSize(new Dimension(1000, 750)); panel.setBorder(new EmptyBorder(10, 10, 10, 10)); frame.setLayout(new FlowLayout()); frame.add(mPanel); frame.pack(); JMenuBar menuBar = new Menu().create(frame, mPanel); frame.setJMenuBar(menuBar); frame.setVisible(true); Rectangle rec = GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds(); int width = (int) rec.getWidth(); int height = (int) rec.getHeight(); frame.setBounds(1, 3, width, height); frame.addComponentListener(new ComponentAdapter() { @Override public void componentMoved(ComponentEvent e) { frame.setLocation(1, 3); } }); And this is the method I use for creating the table: String[][] tableData = new String[g.length][9]; for (int i = 0; i < tableData.length; i++) { tableData[i][0] = g[i].getChampion(); tableData[i][1] = g[i].getRole(); tableData[i][2] = g[i].getEnemy(); tableData[i][3] = g[i].getDifficulty(); tableData[i][4] = g[i].getResult(); tableData[i][5] = g[i].getScore(); tableData[i][6] = g[i].getGameType(); tableData[i][7] = g[i].getPoints(); tableData[i][8] = g[i].getLeague(); } final JLabel searchLabel = new JLabel("Search for champion played."); final JButton searchButton = new JButton("Search"); final JTextField searchText = new JTextField(20); frame.setTitle("LoL Notepad - reading your notes"); JTable table = new JTable(tableData, columnNames); final JScrollPane scrollPane = new JScrollPane(table); scrollPane.setPreferredSize(new Dimension(980, 500)); panel2.setPreferredSize(new Dimension(1000, 550)); panel2.setVisible(false); panel2.setBorder(new EmptyBorder(10, 10, 10, 10)); panel3.setVisible(false); panel.setLayout(new FlowLayout()); panel.add(scrollPane); searchPanel.add(searchLabel); searchPanel.add(searchText); searchPanel.add(searchButton); searchButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { frame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); search(g, searchText.getText(), frame, bButton); frame.setCursor(Cursor.getDefaultCursor()); } catch (IOException ex) { Logger.getLogger(Reader.class.getName()).log(Level.SEVERE, null, ex); } } }); table.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { if (e.getClickCount() == 1) { JTable target = (JTable) e.getSource(); panel.setVisible(false); searchPanel.setVisible(false); bButton.setVisible(false); int row = target.getSelectedRow(); specific(row, g, frame, bButton); } } });

    Read the article

  • problem in login in yahoo massanger

    - by khoyendra
    package session; import java.io.FileWriter; import java.text.DateFormat; import java.text.SimpleDateFormat; import javax.swing.JOptionPane; import org.openymsg.network.FireEvent; import org.openymsg.network.Session; import org.openymsg.network.SessionState; import org.openymsg.network.event.SessionListener; public class BotGUI extends javax.swing.JFrame implements SessionListener{ /** Creates new form BotGUI */ FileWriter fw; DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); public BotGUI() { initComponents(); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code"> private void initComponents() { jPanel1 = new javax.swing.JPanel(); jPanel2 = new javax.swing.JPanel(); jPanel3 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jPanel4 = new javax.swing.JPanel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); uNameTextField = new javax.swing.JTextField(); uPassPasswordField = new javax.swing.JPasswordField(); jButton1 = new javax.swing.JButton(); jMenuBar1 = new javax.swing.JMenuBar(); jMenu1 = new javax.swing.JMenu(); jMenuItem1 = new javax.swing.JMenuItem(); jMenuItem2 = new javax.swing.JMenuItem(); jMenuItem3 = new javax.swing.JMenuItem(); jMenu2 = new javax.swing.JMenu(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jPanel2.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jPanel3.setBackground(new java.awt.Color(51, 51, 51)); jLabel1.setBackground(new java.awt.Color(0, 0, 255)); jLabel1.setFont(new java.awt.Font("Tahoma", 1, 12)); jLabel1.setForeground(new java.awt.Color(255, 255, 255)); jLabel1.setText("Yahoo Login Panel"); javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addGap(38, 38, 38) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(532, Short.MAX_VALUE)) ); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 30, Short.MAX_VALUE) ); jPanel2.add(jPanel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 710, 30)); jPanel4.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jLabel2.setText("Username"); jPanel4.add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 20, 60, 20)); jLabel3.setText("Password"); jPanel4.add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(270, 20, 60, 20)); jPanel4.add(uNameTextField, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 20, 140, 20)); jPanel4.add(uPassPasswordField, new org.netbeans.lib.awtextra.AbsoluteConstraints(330, 20, 140, -1)); jButton1.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jButton1.setText("Login"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jPanel4.add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(490, 15, 90, -1)); jPanel2.add(jPanel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 30, 710, 60)); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(293, Short.MAX_VALUE)) ); jMenu1.setText("Option"); jMenuItem1.setText("Logout"); jMenu1.add(jMenuItem1); jMenuItem2.setText("Load CSV"); jMenu1.add(jMenuItem2); jMenuItem3.setText("Exit"); jMenu1.add(jMenuItem3); jMenuBar1.add(jMenu1); jMenu2.setText("Help"); jMenuBar1.add(jMenu2); setJMenuBar(jMenuBar1); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); pack(); }// </editor-fold> public void handleConnectionClosed() { connectionClosed = true; loggedIn = false; } private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { if(!uNameTextField.getText().equals("") && !uPassPasswordField.getText().equals("")){ Yahoo_login(uNameTextField.getText(),uPassPasswordField.getText()); }else{ JOptionPane.showMessageDialog(null, "Plese Enter User Id and Password"); } } Session yahooMessengerSession; MySessionListener mySessionListener; boolean loggedIn = false; boolean connectionClosed = false; public void Yahoo_login(String uName, String pass) { connectionClosed = false; if (loggedIn == false) { yahooMessengerSession = new Session(); mySessionListener = new MySessionListener(this); yahooMessengerSession.addSessionListener(mySessionListener); try { if ((uName.equals("")) || (pass.equals(""))) { System.out.println("User name/password is blank"); } else{ //initialized a file writer for log file System.out.println("Login start........"); yahooMessengerSession.login(uName, pass, true); //checks whether user was succesful in login in if (yahooMessengerSession!=null && yahooMessengerSession.getSessionStatus()== SessionState.LOGGED_ON) { //this loop is reached when the user has been successfully logined System.out.println("Login Success"); fw.write("User (" + uName + ") logged in at : " + dateFormat.format("09.05.10") + " \n"); fw.close(); } else { yahooMessengerSession.reset(); } } } catch(Exception e){ } } } public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new BotGUI().setVisible(true); } }); } // Variables declaration - do not modify private javax.swing.JButton jButton1; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JMenu jMenu1; private javax.swing.JMenu jMenu2; private javax.swing.JMenuBar jMenuBar1; private javax.swing.JMenuItem jMenuItem1; private javax.swing.JMenuItem jMenuItem2; private javax.swing.JMenuItem jMenuItem3; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JPanel jPanel4; private javax.swing.JTextField uNameTextField; private javax.swing.JPasswordField uPassPasswordField; // End of variables declaration public void dispatch(FireEvent fe) { throw new UnsupportedOperationException("Not supported yet."); } } i have to find the error SEVERE: error during the dispatch of event: FireEvent [org.openymsg.network.event.SessionListEvent to:null from:null message:null timestamp:0 status:0 list type:Friends size:2 LIST] java.lang.UnsupportedOperationException: Not supported yet. at yahoomessangerbot.MySessionListener.dispatch(MySessionListener.java:131) at org.openymsg.network.EventDispatcher.runEventNOW(EventDispatcher.java:133) at org.openymsg.network.EventDispatcher.run(EventDispatcher.java:114)

    Read the article

  • login form with java/sqlite

    - by tuxou
    hi I would like to create a login form for my application with the possibility to add or remove users for an sqlite database, i have created the table users(nam, pass) but i can't unclud it in my login form, it someone could help me this is my login code: import java.awt.*; import java.awt.event.*; import javax.swing.*; public class login extends JFrame{ // Variables declaration private JLabel jLabel1; private JLabel jLabel2; private JTextField jTextField1; private JPasswordField jPasswordField1; private JButton jButton1; private JPanel contentPane; // End of variables declaration public login(){ super(); create(); this.setVisible(true); } private void create(){ jLabel1 = new JLabel(); jLabel2 = new JLabel(); jTextField1 = new JTextField(); jPasswordField1 = new JPasswordField(); jButton1 = new JButton(); contentPane = (JPanel)this.getContentPane(); // // jLabel1 // jLabel1.setHorizontalAlignment(SwingConstants.LEFT); jLabel1.setForeground(new Color(0, 0, 255)); jLabel1.setText("username:"); // // jLabel2 // jLabel2.setHorizontalAlignment(SwingConstants.LEFT); jLabel2.setForeground(new Color(0, 0, 255)); jLabel2.setText("password:"); // // jTextField1 // jTextField1.setForeground(new Color(0, 0, 255)); jTextField1.setSelectedTextColor(new Color(0, 0, 255)); jTextField1.setToolTipText("Enter your username"); jTextField1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e){ jTextField1_actionPerformed(e); } }); // // jPasswordField1 // jPasswordField1.setForeground(new Color(0, 0, 255)); jPasswordField1.setToolTipText("Enter your password"); jPasswordField1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e){ jPasswordField1_actionPerformed(e); } }); // // jButton1 // jButton1.setBackground(new Color(204, 204, 204)); jButton1.setForeground(new Color(0, 0, 255)); jButton1.setText("Login"); jButton1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e){ jButton1_actionPerformed(e); } }); // // contentPane // contentPane.setLayout(null); contentPane.setBorder(BorderFactory.createEtchedBorder()); contentPane.setBackground(new Color(204, 204, 204)); addComponent(contentPane, jLabel1, 5,10,106,18); addComponent(contentPane, jLabel2, 5,47,97,18); addComponent(contentPane, jTextField1, 110,10,183,22); addComponent(contentPane, jPasswordField1, 110,45,183,22); addComponent(contentPane, jButton1, 150,75,83,28); // // login // this.setTitle("Login To Members Area"); this.setLocation(new Point(76, 182)); this.setSize(new Dimension(335, 141)); this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); this.setResizable(false); } /** Add Component Without a Layout Manager (Absolute Positioning) */ private void addComponent(Container container,Component c,int x,int y,int width,int height){ c.setBounds(x,y,width,height); container.add(c); } private void jTextField1_actionPerformed(ActionEvent e){ } private void jPasswordField1_actionPerformed(ActionEvent e){ } private void jButton1_actionPerformed(ActionEvent e){ System.out.println("\njButton1_actionPerformed(ActionEvent e) called."); String username = new String(jTextField1.getText()); String password = new String(jPasswordField1.getText()); if(username.equals("") || password.equals("")){// If password and username is empty > Do this >>> jButton1.setEnabled(false); JLabel errorFields = new JLabel("<HTML><FONT COLOR = Blue>You must enter a username and password to login.</FONT></HTML>"); JOptionPane.showMessageDialog(null,errorFields); jTextField1.setText(""); jPasswordField1.setText(""); jButton1.setEnabled(true); this.setVisible(true); } else{ JLabel optionLabel = new JLabel("<HTML><FONT COLOR = Blue>You entered</FONT><FONT COLOR = RED> <B>"+username+"</B></FONT> <FONT COLOR = Blue>as your username.<BR> Is this correct?</FONT></HTML>"); int confirm =JOptionPane.showConfirmDialog(null,optionLabel); switch(confirm){ // Switch > Case case JOptionPane.YES_OPTION: // Attempt to Login user jButton1.setEnabled(false); // Set button enable to false to prevent 2 login attempts break; case JOptionPane.NO_OPTION: // No Case.(Go back. Set text to 0) jButton1.setEnabled(false); jTextField1.setText(""); jPasswordField1.setText(""); jButton1.setEnabled(true); break; case JOptionPane.CANCEL_OPTION: // Cancel Case.(Go back. Set text to 0) jButton1.setEnabled(false); jTextField1.setText(""); jPasswordField1.setText(""); jButton1.setEnabled(true); break; } // End Switch > Case } } public static void main(String[] args){ JFrame.setDefaultLookAndFeelDecorated(true); JDialog.setDefaultLookAndFeelDecorated(true); try{ UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); }catch (Exception ex){ System.out.println("Failed loading L&F: "); System.out.println(ex); } new login(); }; } my connectDb class : public class Connectdb { private static Connection connect; private static String url ="jdbc:sqlite:data.db"; private static Statement st; private static ResultSet rs; /** * Constructeur privé d'une connection à la bd unique */ private ConnectionBd(){ try { Class.forName("org.sqlite.JDBC"); connect = DriverManager.getConnection(url); } catch (ClassNotFoundException ex) { Logger.getLogger(ex.getName()).log(Level.SEVERE, null, ex); } catch (SQLException e) { System.exit(e.getErrorCode()); } } public static Connection getInstance(){ if(connect == null){ new Connectdb(); }else{ } return connect; } /** * @return */ public static void initTable(String query){ try { Statement state = getInstance().createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); ResultSet res = state.executeQuery(query); res.close(); state.close(); } catch (SQLException e) { JOptionPane.showMessageDialog(null, e.getMessage(), "ERROR ! ", JOptionPane.ERROR_MESSAGE); } }

    Read the article

  • Retrieve input entered in a JDialog

    - by Jules Olléon
    I extended JDialog to create a custom dialog where the user must fill some fields : How should I retrieve the data entered ? I came up with a solution that works. It mimics JOptionPane but the way I do it looks ugly to me because of the static fields involved... Here is roughly my code : public class FObjectDialog extends JDialog implements ActionListener { private static String name; private static String text; private JTextField fName; private JTextArea fText; private JButton bAdd; private JButton bCancel; private FObjectDialog(Frame parentFrame) { super(parentFrame,"Add an object",true); // build the whole dialog buildNewObjectDialog(); setVisible(true); } @Override public void actionPerformed(ActionEvent ae) { if(ae.getSource()==bAdd){ name=fName.getText(); text=fText.getText(); } else { name=null; text=null; } setVisible(false); dispose(); } public static String[] showCreateDialog(Frame parentFrame){ new FObjectDialog(parentFrame); String[] res={name,text}; if((name==null)||(text==null)) res=null; return res; } } As I said, that works properly, but I guess that might raise serious concurrency issues... Is there a cleaner way to do that ? How is it done in JOptionPane ?

    Read the article

  • Advice welcomed on creating my own Swing component

    - by Toto
    Recently I asked which was the best Swing component to bind to a BigDecimal variable (with some particular editing properties). It turns out that none of the standard Swing components suit me completely, nor did the third-party Swing component libraries I've found out there. So I’ve decided to create my own Swing component. Component description: I want to extend JTextField or JFormattedTextField, so my new component can be easily bound to a BigDecimal variable. The component will have customizable scale and length properties. Behavior: When the component is drawn, it shows only the decimal point and space for scale digits to its right. When the component receives focus the caret should be positioned left to the decimal point. As the user types numbers (any other character is ignored) they appear to the left of the caret, only length – scale numbers are accepted, any other number typed is ignored as the integer portion is full. Any time the user types the decimal point the caret moves to the right side of the decimal point. The following numbers typed are shown in the decimal part, only scale numbers are considered any other number typed is ignored as the decimal portion is full. Additionally, thousand separators should appear as the user types numbers left to the decimal point. Invoking a getValue() method on the component should yield the BigDecimal representing the number just entered. I’ve never created my own Swing component; I’ve barely used the standard ones. So I would appreciate any good tutorial/info/tip on creating the component described. This is the only thing I've got so far. Thanks in advance.

    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

  • Stuck on Object scope in Java

    - by ivor
    Hello, I'm working my way through an exercise to understand Java, and basically I need to merge the functionality of two classes into one app. I'm stuck on one area though - the referencing of objects across classes. What I have done is set up a gui in one class (test1), and this has a textfield in ie. chatLine = new JTextField(); in another class(test2), I was planning on leaving all the functionality in there and referencing the various gui elements set up in test1 - like this test1.chatLine I understand this level of referencing, I tested this by setting up a test method in the test2 class public static void testpass() { test1.testfield.setText("hello"); } I'm trying to understand how to implement the more complex functionality in test2 class though, specifically this existing code; test1.chatLine.addActionListener(new ActionAdapter() { public void actionPerformed(ActionEvent e) { String s = Game.chatLine.getText(); if (!s.equals("")) { appendToChatBox("OUTGOING: " + s + "\n"); Game.chatLine.selectAll(); // Send the string sendString(s); } } }); This is the bit I'm stuck on, if I should be able to do this - as it's failing on the compile, can I add the actionadapter stuff to the gui element thats sat in test1, but do this from test2 - I'm wondering if I'm trying to do something that's not possible. Hope this makes sense, I'm pretty confused over this - I'm trying to understand how the scope and referencing works. Ideally what i'm trying to achieve is one class that has all the main stuff in, the gui etc, then all the related functionality in the other class, and target the first class's gui elements with the results etc. Any thoughts greatly appreciated.

    Read the article

  • Changing JTextArea to JScrollPane Causes it to not be visible

    - by user1806716
    I am having an issue with JScrollPanes and JTextArea objects and getting them to work together. If I just add a JTextArea to my JPanel, it works fine and shows up where I tell it to. However, if I change the contentPane.add(textArea) to contentPane.add(new JScrollPane(textArea)), the textArea is not longer visible and there is no sign of the textarea either. Here is my code: public docToolGUI() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 611, 487); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); textField = new JTextField(); textField.setBounds(253, 323, 86, 20); contentPane.add(textField); textField.setColumns(10); JLabel lblEnterRootDirectory = new JLabel("Enter Root Directory"); lblEnterRootDirectory.setBounds(253, 293, 127, 20); contentPane.add(lblEnterRootDirectory); JButton btnGo = new JButton("Go"); btnGo.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent arg0) { new ToolWorker().execute(); } }); btnGo.setBounds(253, 361, 89, 23); contentPane.add(btnGo); textArea = new JTextArea(); textArea.setWrapStyleWord(true); textArea.setEditable(false); textArea.setBounds(25, 11, 560, 276); contentPane.add(new JScrollPane(textArea)); }

    Read the article

  • Need Help: adding MouseListeners to JComponents (Drawing a JComponent and then attaching a MouseListener)

    - by user1074574
    Drawing a JComponent and then attaching a MouseListener seems very simple to me, but not in this case: I'm having a problem with a MouseListener attached to a child JComponent; here's some brief code to help describe it: Note: The BGT class has implemented ActionListers/MouseListeners that do not have any code in them, and 'figures' is an array of SwingThings. public class GC extends BGT{ public GC(){ super(); buildJMenu(); drawPanel.addMouseListener(this); //drawPanel being the panel that draws the JComponents (it is a public variable in the BGT class) drawPanel.addMouseMotionListener(this); this.addMouseListener(this); } public static void main(String[] args){ GC a = new GC(); }... public void mouseClicked(MouseEvent e) { System.out.println(e.getSource()); //This only seems to print out the DrawPanel's information }... public void mouseReleased(MouseEvent e) { repaint(); ... tempMyJTextField = new MyJTextField(startX, startY, width, height); tempMyJTextField.addMouseListener(this); tempMyJTextField.addMouseMotionListener(this); figures.add(tempMyJTextField); for(int i = 0; i < figures.size(); i++) figures.get(i).addTo(drawPanel); } This is the addTo method in the MyJTextField class: public class MyJTextField extends JTextField implements SwingThing{ ... public void addTo(JPanel p) { p.add(myTextField); } ... } In the MouseClicked event it never registers that the JComponent was clicked. (The drawing/painting works fine) Thanks.

    Read the article

  • java regex for alpha and spaces is including [ ] \

    - by JayAvon
    This is my regex for my JTextField to not be longer than x characters and to not include anything other than letters or spaces. For some reason it is allowing [ ] and \ characters. This is driving me crazy. Is my regex wrong?? package com.jayavon.game.helper; import java.awt.Toolkit; import javax.swing.text.AttributeSet; import javax.swing.text.BadLocationException; import javax.swing.text.PlainDocument; public class CharacterNameCreationDocument extends PlainDocument { private static final long serialVersionUID = 1L; private int limit; public CharacterNameCreationDocument(int limit) { super(); this.limit = limit; } public void insertString(int offset, String str, AttributeSet attr) throws BadLocationException { if (str == null || (getLength() + str.length()) > limit || !str.matches("[a-zA-z\\s]*")){ Toolkit.getDefaultToolkit().beep(); return; } else { super.insertString(offset, str, attr); } } }

    Read the article

  • BeansBinding Across Modules in a NetBeans Platform Application

    - by Geertjan
    Here's two TopComponents, each in a different NetBeans module. Let's use BeansBinding to synchronize the JTextField in TC2TopComponent with the data published by TC1TopComponent and received in TC2TopComponent by listening to the Lookup. The key to getting to the solution is to have the following in TC2TopComponent, which implements LookupListener: private BindingGroup bindingGroup = null; private AutoBinding binding = null; @Override public void resultChanged(LookupEvent le) { if (bindingGroup != null && binding != null) { bindingGroup.getBinding("customerNameBinding").unbind(); } if (!result.allInstances().isEmpty()){ Customer c = result.allInstances().iterator().next(); // put the customer into the lookup of this topcomponent, // so that it will remain in the lookup when focus changes // to this topcomponent: ic.set(Collections.singleton(c), null); bindingGroup = new BindingGroup(); binding = Bindings.createAutoBinding( // a two-way binding, i.e., a change in // one will cause a change in the other: AutoBinding.UpdateStrategy.READ_WRITE, // source: c, BeanProperty.create("name"), // target: jTextField1, BeanProperty.create("text"), // binding name: "customerNameBinding"); bindingGroup.addBinding(binding); bindingGroup.bind(); } } I must say that this solution is preferable over what I've been doing prior to getting to this solution: I would get the customer from the resultChanged, set a class-level field to that customer, add a document listener (or action listener, which is invoked when Enter is pressed) on the text field and, when a change is detected, set the new value on the customer. All that is not needed with the above bit of code. Then, in the node, make sure to use canRename, setName, and getDisplayName, so that when the user presses F2 on a node, the display name can be changed. In other words, when the user types something different in the node display name after pressing F2, the underlying customer name is changed, which happens, in the first place, because the customer name is bound to the text field's value, so that the text field's value will also change once enter is pressed on the changed node display name. Also set a PropertyChangeListener on the node (which implies you need to add property change support to the customer object), so that when the customer object changes (which happens, in the second place, via a change in the value of the text field, as defined in the binding defined above), the node display name is updated. In other words, there's still a bit of plumbing you need to include. But less than before and the nasty class-level field for storing the customer in the TC2TopComponent is no longer needed. And a listener on the text field, with a property change listener implented on the TC2TopComponent, isn't needed either. On the other hand, it's more code than I was using before and I've had to include the BeansBinding JAR, which adds a bit of overhead to my application, without much additional functionality over what I was doing originally. I'd lean towards not doing things this way. Seems quite expensive for essentially replacing a listener on a text field and a property change listener implemented on the TC2TopComponent for being notified of changes to the customer so that the text field can be updated. On the other other hand, it's kind of nice that all this listening-related code is centralized in one place now. So, here's a nice improvement over the above. Instead of listening for a customer, listen for a node, from which the customer can be obtained. Then, bind the node display name to the text field's value, so that when the user types in the text field, the node display name is updated. That saves you from having to listen in the node for changes to the customer's name. In addition to that binding, keep the previous binding, because the previous binding connects the customer name to the text field, so that when the customer display name is changed via F2 on the node, the text field will be updated. private BindingGroup bindingGroup = null; private AutoBinding nodeUpdateBinding; private AutoBinding textFieldUpdateBinding; @Override public void resultChanged(LookupEvent le) { if (bindingGroup != null && textFieldUpdateBinding != null) { bindingGroup.getBinding("textFieldUpdateBinding").unbind(); } if (bindingGroup != null && nodeUpdateBinding != null) { bindingGroup.getBinding("nodeUpdateBinding").unbind(); } if (!result.allInstances().isEmpty()) { Node n = result.allInstances().iterator().next(); Customer c = n.getLookup().lookup(Customer.class); ic.set(Collections.singleton(n), null); bindingGroup = new BindingGroup(); nodeUpdateBinding = Bindings.createAutoBinding( AutoBinding.UpdateStrategy.READ_WRITE, n, BeanProperty.create("name"), jTextField1, BeanProperty.create("text"), "nodeUpdateBinding"); bindingGroup.addBinding(nodeUpdateBinding); textFieldUpdateBinding = Bindings.createAutoBinding( AutoBinding.UpdateStrategy.READ_WRITE, c, BeanProperty.create("name"), jTextField1, BeanProperty.create("text"), "textFieldUpdateBinding"); bindingGroup.addBinding(textFieldUpdateBinding); bindingGroup.bind(); } } Now my node has no property change listener, while the customer has no property change support. As in the first bit of code, the text field doesn't have a listener either. All that listening is taken care of by the BeansBinding code.  Thanks to Toni for help with this, though he can't be blamed for anything that is wrong with it, only thanked for anything that is right with it. 

    Read the article

  • Java JPanel not showing up....

    - by user69514
    I'm not sure what I am doing wrong, but the text for my JPanels is not showing up. I just get the question number text, but the question is not showing up. Any ideas what I am doing wrong? import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; class NewFrame extends JFrame { JPanel centerpanel; // For the questions. CardLayout card; // For the centerpanel. JTextField tf; // Used in question 1. boolean // Store selections for Q2. q2Option1, q2Option2, q2Option3, q2Option4; JList q4List; // For question 4. double // Score on each question. q1Score = 0, q2Score = 0, q3Score = 0, q4Score = 0; // Constructor. public NewFrame (int width, int height) { this.setTitle ("Snoot Club Membership Test"); this.setResizable (true); this.setSize (width, height); Container cPane = this.getContentPane(); // cPane.setLayout (new BorderLayout()); // First, a welcome message, as a Label. JLabel L = new JLabel ("<html><b>Are you elitist enough for our exclusive club?" + " <br>Fill out the form and find out</b></html>"); L.setForeground (Color.blue); cPane.add (L, BorderLayout.NORTH); // Now the center panel with the questions. card = new CardLayout (); centerpanel = new JPanel (); centerpanel.setLayout (card); centerpanel.setOpaque (false); // Each question will be created in a separate method. // The cardlayout requires a label as second parameter. centerpanel.add (firstQuestion (), "1"); centerpanel.add (secondQuestion(), "2"); centerpanel.add (thirdQuestion(), "3"); centerpanel.add (fourthQuestion(), "4"); cPane.add (centerpanel, BorderLayout.CENTER); // Next, a panel of four buttons at the bottom. // The four buttons: quit, submit, next-question, previous-question. JPanel bottomPanel = getBottomPanel (); cPane.add (bottomPanel, BorderLayout.SOUTH); // Finally, show the frame. this.setVisible (true); } // No-parameter constructor. public NewFrame () { this (500, 300); } // The first question uses labels for the question and // gets input via a textfield. A panel containing all // these things is returned. The question asks for // a vacation destination: the more exotic the location, // the higher the score. JPanel firstQuestion () { // We will package everything into a panel and return the panel. JPanel subpanel = new JPanel (); // We will place things in a single column, so // a GridLayout with one column is appropriate. subpanel.setLayout (new GridLayout (8,1)); JLabel L1 = new JLabel ("Question 1:"); L1.setFont (new Font ("SansSerif", Font.ITALIC, 15)); subpanel.add (L1); JLabel L2 = new JLabel (" Select a vacation destination"); L2.setFont (new Font ("SansSerif", Font.ITALIC, 15)); subpanel.add (L2); JLabel L3 = new JLabel (" 1. Baltimore"); L3.setFont (new Font ("SansSerif", Font.ITALIC, 15)); subpanel.add (L3); JLabel L4 = new JLabel (" 2. Disneyland"); L4.setFont (new Font ("SansSerif", Font.ITALIC, 15)); subpanel.add (L4); JLabel L5 = new JLabel (" 3. Grand Canyon"); L5.setFont (new Font ("SansSerif", Font.ITALIC, 15)); subpanel.add (L5); JLabel L6 = new JLabel (" 4. French Riviera"); L6.setFont (new Font ("SansSerif", Font.ITALIC, 15)); subpanel.add (L6); JLabel L7 = new JLabel ("Enter 1,2,3 or 4 below:"); L7.setFont (new Font ("SansSerif", Font.ITALIC, 15)); subpanel.add (L7); // Here's the textfield to get user-input. tf = new JTextField (); tf.addActionListener ( new ActionListener () { // This interface has only one method. public void actionPerformed (ActionEvent a) { String q1String = a.getActionCommand(); if (q1String.equals ("2")) q1Score = 2; else if (q1String.equals ("3")) q1Score = 3; else if (q1String.equals ("4")) q1Score = 4; else q1Score = 1; } } ); subpanel.add (tf); return subpanel; } // For the second question, a collection of checkboxes // will be used. More than one selection can be made. // A listener is required for each checkbox. The state // of each checkbox is recorded. JPanel secondQuestion () { JPanel subpanel = new JPanel (); subpanel.setLayout (new GridLayout (7,1)); JLabel L1 = new JLabel ("Question 2:"); L1.setFont (new Font ("SansSerif", Font.ITALIC, 15)); subpanel.add (L1); JLabel L2 = new JLabel (" Select ONE OR MORE things that "); L2.setFont (new Font ("SansSerif", Font.ITALIC, 15)); subpanel.add (L2); JLabel L3 = new JLabel (" you put into your lunch sandwich"); L3.setFont (new Font ("SansSerif", Font.ITALIC, 15)); subpanel.add (L3); // Initialize the selections to false. q2Option1 = q2Option2 = q2Option3 = q2Option4 = false; // First checkbox. JCheckBox c1 = new JCheckBox ("Ham, beef or turkey"); c1.addItemListener ( new ItemListener () { public void itemStateChanged (ItemEvent i) { JCheckBox c = (JCheckBox) i.getSource(); q2Option1 = c.isSelected(); } } ); subpanel.add (c1); // Second checkbox. JCheckBox c2 = new JCheckBox ("Cheese"); c2.addItemListener ( new ItemListener () { // This is where we will react to a change in checkbox. public void itemStateChanged (ItemEvent i) { JCheckBox c = (JCheckBox) i.getSource(); q2Option2 = c.isSelected(); } } ); subpanel.add (c2); // Third checkbox. JCheckBox c3 = new JCheckBox ("Sun-dried Arugula leaves"); c3.addItemListener ( new ItemListener () { public void itemStateChanged (ItemEvent i) { JCheckBox c = (JCheckBox) i.getSource(); q2Option3 = c.isSelected(); } } ); subpanel.add (c3); // Fourth checkbox. JCheckBox c4 = new JCheckBox ("Lemon-enhanced smoked Siberian caviar"); c4.addItemListener ( new ItemListener () { public void itemStateChanged (ItemEvent i) { JCheckBox c = (JCheckBox) i.getSource(); q2Option4 = c.isSelected(); } } ); subpanel.add (c4); return subpanel; } // The third question allows only one among four choices // to be selected. We will use radio buttons. JPanel thirdQuestion () { JPanel subpanel = new JPanel (); subpanel.setLayout (new GridLayout (6,1)); JLabel L1 = new JLabel ("Question 3:"); L1.setFont (new Font ("SansSerif", Font.ITALIC, 15)); subpanel.add (L1); JLabel L2 = new JLabel (" And which mustard do you use?"); L2.setFont (new Font ("SansSerif", Font.ITALIC, 15)); subpanel.add (L2); // First, create the ButtonGroup instance. // We will add radio buttons to this group. ButtonGroup bGroup = new ButtonGroup(); // First checkbox. JRadioButton r1 = new JRadioButton ("Who cares?"); r1.addItemListener ( new ItemListener () { public void itemStateChanged (ItemEvent i) { JRadioButton r = (JRadioButton) i.getSource(); if (r.isSelected()) q3Score = 1; } } ); bGroup.add (r1); subpanel.add (r1); // Second checkbox. JRadioButton r2 = new JRadioButton ("Safeway Brand"); r2.addItemListener ( new ItemListener () { public void itemStateChanged (ItemEvent i) { JRadioButton r = (JRadioButton) i.getSource(); if (r.isSelected()) q3Score = 2; } } ); bGroup.add (r2); subpanel.add (r2); // Third checkbox. JRadioButton r3 = new JRadioButton ("Fleishman's"); r3.addItemListener ( new ItemListener () { public void itemStateChanged (ItemEvent i) { JRadioButton r = (JRadioButton) i.getSource(); if (r.isSelected()) q3Score = 3; } } ); bGroup.add (r3); subpanel.add (r3); // Fourth checkbox. JRadioButton r4 = new JRadioButton ("Grey Poupon"); r4.addItemListener ( new ItemListener () { public void itemStateChanged (ItemEvent i) { JRadioButton r = (JRadioButton) i.getSource(); if (r.isSelected()) q3Score = 4; } } ); bGroup.add (r4); subpanel.add (r4); return subpanel; } // For the fourth question we will use a drop-down Choice. JPanel fourthQuestion () { JPanel subpanel = new JPanel (); subpanel.setLayout (new GridLayout (3,1)); JLabel L1 = new JLabel ("Question 4:"); L1.setFont (new Font ("SansSerif", Font.ITALIC, 15)); subpanel.add (L1); JLabel L2 = new JLabel (" Your movie preference, among these:"); L2.setFont (new Font ("SansSerif", Font.ITALIC, 15)); subpanel.add (L2); // Create a JList with options. String[] movies = { "Lethal Weapon IV", "Titanic", "Saving Private Ryan", "Le Art Movie avec subtitles"}; q4List = new JList (movies); q4Score = 1; q4List.addListSelectionListener ( new ListSelectionListener () { public void valueChanged (ListSelectionEvent e) { q4Score = 1 + q4List.getSelectedIndex(); } } ); subpanel.add (q4List); return subpanel; } void computeResult () { // Clear the center panel. centerpanel.removeAll(); // Create a new panel to display in the center. JPanel subpanel = new JPanel (new GridLayout (5,1)); // Score on question 1. JLabel L1 = new JLabel ("Score on question 1: " + q1Score); L1.setFont (new Font ("Serif", Font.ITALIC, 15)); subpanel.add (L1); // Score on question 2. if (q2Option1) q2Score += 1; if (q2Option2) q2Score += 2; if (q2Option3) q2Score += 3; if (q2Option4) q2Score += 4; q2Score = 0.6 * q2Score; JLabel L2 = new JLabel ("Score on question 2: " + q2Score); L2.setFont (new Font ("Serif", Font.ITALIC, 15)); subpanel.add (L2); // Score on question 3. JLabel L3 = new JLabel ("Score on question 3: " + q3Score); L3.setFont (new Font ("Serif", Font.ITALIC, 15)); subpanel.add (L3); // Score on question 4. JLabel L4 = new JLabel ("Score on question 4: " + q4Score); L4.setFont (new Font ("Serif", Font.ITALIC, 15)); subpanel.add (L4); // Weighted score. double avg = (q1Score + q2Score + q3Score + q4Score) / (double) 4; JLabel L5; if (avg <= 3.5) L5 = new JLabel ("Your average score: " + avg + " - REJECTED!"); else L5 = new JLabel ("Your average score: " + avg + " - WELCOME!"); L5.setFont (new Font ("Serif", Font.BOLD, 20)); //L5.setAlignment (JLabel.CENTER); subpanel.add (L5); // Now add the new subpanel. centerpanel.add (subpanel, "5"); // Need to mark the centerpanel as "altered" centerpanel.invalidate(); // Everything "invalid" (e.g., the centerpanel above) // is now re-computed. this.validate(); } JPanel getBottomPanel () { // Create a panel into which we will place buttons. JPanel bottomPanel = new JPanel (); // A "previous-question" button. JButton backward = new JButton ("Previous question"); backward.setFont (new Font ("Serif", Font.PLAIN | Font.BOLD, 15)); backward.addActionListener ( new ActionListener () { public void actionPerformed (ActionEvent a) { // Go back in the card layout. card.previous (centerpanel); } } ); bottomPanel.add (backward); // A forward button. JButton forward = new JButton ("Next question"); forward.setFont (new Font ("Serif", Font.PLAIN | Font.BOLD, 15)); forward.addActionListener ( new ActionListener () { public void actionPerformed (ActionEvent a) { // Go forward in the card layout. card.next (centerpanel); } } ); bottomPanel.add (forward); // A submit button. JButton submit = new JButton ("Submit"); submit.setFont (new Font ("Serif", Font.PLAIN | Font.BOLD, 15)); submit.addActionListener ( new ActionListener () { public void actionPerformed (ActionEvent a) { // Perform submit task. computeResult(); } } ); bottomPanel.add (submit); JButton quitb = new JButton ("Quit"); quitb.setFont (new Font ("Serif", Font.PLAIN | Font.BOLD, 15)); quitb.addActionListener ( new ActionListener () { public void actionPerformed (ActionEvent a) { System.exit (0); } } ); bottomPanel.add (quitb); return bottomPanel; } } public class Survey { public static void main (String[] argv) { NewFrame nf = new NewFrame (600, 300); } }

    Read the article

  • Jpanel didn't show rest of it's component

    - by Ali Amiri
    I have jfarame with a button and a JPanel as I named panel, I want after I clicked the button add an inner JPanel to my panel. But this but there is a problem with this! because after adding second panel it didn't add any other panel. my code is: import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.AbstractButton; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import java.awt.GridBagLayout; import java.awt.GridBagConstraints; import java.awt.GridLayout; import javax.swing.JTextField; public class DrawImages extends JFrame{ int i; public DrawImages() { JButton btnNewButton = new JButton("New button"); i = 0; getContentPane().add(btnNewButton, BorderLayout.SOUTH); setMinimumSize(new Dimension(1000,150)); final JPanel panel = new JPanel(); panel.setSize(995, 145); getContentPane().add(panel, BorderLayout.CENTER); panel.setLayout(null); final JLabel lblNewLabel = new JLabel("New label"); lblNewLabel.setBounds(0, 0, 46, 14); panel.add(lblNewLabel); btnNewButton.addActionListener(new ActionListener() public void actionPerformed(ActionEvent paramActionEvent) { JPanel panel_1 = new JPanel(); //getContentPane().add(panel_1, BorderLayout.NORTH); panel_1.setLayout(null); JLabel imagelable = new JLabel(new ImageIcon("c:\\good.jpg")); imagelable.setBounds(70, 5, 105, 65); panel_1.add(imagelable); JLabel lblNewLabel_4 = new JLabel("Up Label"); lblNewLabel_4.setBounds(5, 5, 65, 35); panel_1.add(lblNewLabel_4); JLabel lblNewLabel_2 = new JLabel("Down Label"); lblNewLabel_2.setBounds(5, 25, 65, 65); panel_1.add(lblNewLabel_2); lblNewLabel.setText(""+i); panel_1.setBounds(5+170*i, 5, 170+170*i, 70); panel.add(panel_1); i++; } }); panel.setMinimumSize(new Dimension(995,150)); } public static void main(String[]args) { DrawImages drawImages = new DrawImages(); drawImages.setVisible(true); } }

    Read the article

  • All parts of my Printable Swing component doesn't print

    - by Jonas
    I'm trying to do a printable component (an invoice document). I use JComponent instead of JPanel because I don't want a background. The component has many subcomponents. The main component implements Printable and has a print-method that is calling printAll(g) so that all subcomponents should be printed. But my subcomponents doesn't print. What am I missing? Does all subcomponents also has to implement Printable? import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GridLayout; import java.awt.print.PageFormat; import java.awt.print.Printable; import java.awt.print.PrinterException; import java.awt.print.PrinterJob; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; public class PPanel extends JComponent implements Printable { static double w; static double h; public PPanel() { this.setLayout(new BorderLayout()); this.add(new JLabel("Document Body"), BorderLayout.CENTER); this.add(new Header(), BorderLayout.NORTH); this.add(new Footer(), BorderLayout.SOUTH); } class Header extends JComponent { public Header() { this.setLayout(new BorderLayout()); this.add(new TopHeader(), BorderLayout.NORTH); this.add(new LowHeader(), BorderLayout.SOUTH); } } class TopHeader extends JComponent { public TopHeader() { this.setLayout(new BorderLayout()); JLabel companyName = new JLabel("Company name"); JLabel docType = new JLabel("Document type"); this.add(companyName, BorderLayout.WEST); this.add(docType, BorderLayout.EAST); } } class LowHeader extends JComponent { public LowHeader() { this.setLayout(new GridLayout(0,2)); JLabel col1 = new JLabel("Column 1"); JLabel col2 = new JLabel("Column 2"); this.add(col1); this.add(col2); } } class Footer extends JComponent { public Footer() { this.setLayout(new GridLayout(0,2)); JLabel addr = new JLabel("Address"); JLabel sum = new JLabel("Sum"); this.add(addr); this.add(sum); } } public static void main(String[] args) { final PPanel p = new PPanel(); PrinterJob job = PrinterJob.getPrinterJob(); job.setPrintable(p); try { job.print(); } catch (PrinterException ex) { // print failed } // Preview new JFrame() {{ getContentPane().add(p); this.setSize((int)w, (int)h); setVisible(true); }}; } @Override public int print(Graphics g, PageFormat pf, int page) throws PrinterException { if (page > 0) { return NO_SUCH_PAGE; } Graphics2D g2d = (Graphics2D)g; g2d.translate(pf.getImageableX(), pf.getImageableY()); w = pf.getImageableWidth(); h = pf.getHeight(); this.setSize((int)w, (int)h); this.setPreferredSize(new Dimension((int)w, (int)h)); this.doLayout(); this.printAll(g); return PAGE_EXISTS; } }

    Read the article

  • -Java- Swing GUI - Moving around components specifically with layouts

    - by Xemiru Scarlet Sanzenin
    I'm making a little test GUI for something I'm making. However, problems occur with the positioning of the panels. public winInit() { super("Chatterbox - Login"); try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch(ClassNotFoundException e) { } catch (InstantiationException e) { } catch (IllegalAccessException e) { } catch (UnsupportedLookAndFeelException e) { } setSize(300,135); pn1 = new JPanel(); pn2 = new JPanel(); pn3 = new JPanel(); l1 = new JLabel("Username"); l2 = new JLabel("Password"); l3 = new JLabel("Random text here"); l4 = new JLabel("Server Address"); l5 = new JLabel("No address set."); i1 = new JTextField(10); p1 = new JPasswordField(10); b1 = new JButton("Connect"); b2 = new JButton("Register"); b3 = new JButton("Set IP"); l4.setBounds(10, 12, getDim(l4).width, getDim(l4).height); l1.setBounds(10, 35, getDim(l1).width, getDim(l1).height); l2.setBounds(10, 60, getDim(l2).width, getDim(l2).height); l3.setBounds(10, 85, getDim(l3).width, getDim(l3).height); l5.setBounds(l4.getBounds().width + 14, 12, l5.getPreferredSize().width, l5.getPreferredSize().height); l5.setForeground(Color.gray); i1.setBounds(getDim(l1).width + 15, 35, getDim(i1).width, getDim(i1).height); p1.setBounds(getDim(l1).width + 15, 60, getDim(p1).width, getDim(p1).height); b1.setBounds(getDim(l1).width + getDim(i1).width + 23, 34, getDim(b2).width, getDim(b1).height - 5); b2.setBounds(getDim(l1).width + getDim(i1).width + 23, 60, getDim(b2).width, getDim(b2).height - 5); b3.setBounds(getDim(l1).width + getDim(i1).width + 23, 10, etDim(b2).width, getDim(b3).height - 5); b1.addActionListener(clickButton); b2.addActionListener(clickButton); b3.addActionListener(clickButton); pn1.setLayout(new FlowLayout(FlowLayout.RIGHT)); pn2.setLayout(new FlowLayout(FlowLayout.RIGHT)); pn1.add(l1); pn1.add(i1); pn1.add(b1); pn2.add(l2); pn2.add(p1); pn2.add(b2); add(pn1); add(pn2); } I am attempting to use FlowLayout to position the panels in the way desired. I'd use BorderLayout while adding, but the vertical spacing is too far away when I just use directions closest to one another. The output of this code is to create a window, 300,150, place whatever's in the two panels in the exact same spaces. Yes, I realize there's useless code there with setBounds(), but that was just me screwing around with Absolute Positioning, which wasn't working out for me either.

    Read the article

  • How do I ensure that a JPanel Shrinks when the parent frame is resized?

    - by dah
    I have a basic notes panel that I'm looking to shrink the width of when the parent jframe is resized but it isn't happening. I'm using nested gridbaglayouts. package com.protocase.notes.views; import com.protocase.notes.controller.NotesController; import com.protocase.notes.model.Subject; import com.protocase.notes.model.Note; import com.protocase.notes.model.database.PMSNotesAdapter; import java.awt.Color; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; /** * @author DavidH */ public class NotesViewer extends JPanel { // <editor-fold defaultstate="collapsed" desc="Attributes"> private Subject subject; private NotesController controller; //</editor-fold> // <editor-fold defaultstate="collapsed" desc="Getters N' Setters"> /** * Gets back the current subject. * @return */ public Subject getSubject() { return subject; } public NotesController getController() { return controller; } public void setController(NotesController controller) { this.controller = controller; } /** * Should clear the panel of the current subject and load the details for * the other object. * @param subject */ public void setSubject(Subject subject) { this.subject = subject; } //</editor-fold> // <editor-fold defaultstate="collapsed" desc="Constructor"> /** * -- Sets up a note viewer with a subject and a controller. Likely this * would be the constructor used if you were passing off from another * NoteViewer or something else that used a notes adapter or controller. * @param subject * @param controller */ public NotesViewer(Subject subject, NotesController controller) { this.subject = subject; this.controller = controller; initComponents(); } /** * -- Sets up a note view with a subject and creates a new controller. This * would be the constructor typically chosen if choosing notes was * infrequent and only one or two notes needs to be displayed. * @param subject */ public NotesViewer(Subject subject) { this(subject, new NotesController(new PMSNotesAdapter())); } /** * -- Sets up a note view without a subject and creates a new controller. * This would be for a note viewer without any notes, perhaps populating * as you choose values in another form. * @param subject */ public NotesViewer() { this(null); } //</editor-fold> // <editor-fold defaultstate="collapsed" desc="initComponents()"> /** * Sets up the view for the NotesViewer */ private void initComponents() { // -- Make a new panel for the header JPanel panel = new JPanel(); panel.setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); c.gridx = 0; c.fill = GridBagConstraints.HORIZONTAL; c.gridy = 0; c.weightx = .5; //c.anchor = GridBagConstraints.NORTHWEST; JLabel label = new JLabel("Viewing Notes for [Subject]"); label.setAlignmentX(JLabel.LEFT_ALIGNMENT); label.setBorder(BorderFactory.createLineBorder(Color.YELLOW)); panel.add(label); JButton newNoteButton = new JButton("New"); c = new GridBagConstraints(); // c.fill = GridBagConstraints.HORIZONTAL; c.gridx = 1; c.gridy = 0; c.weightx = .5; c.anchor = GridBagConstraints.EAST; panel.add(newNoteButton, c); // -- NotePanels c = new GridBagConstraints(); c.fill = GridBagConstraints.HORIZONTAL; c.weightx = 1; c.weighty = 1; c.gridx = 0; c.gridwidth = 2; int y = 1; for (Note n : subject.getNotes()) { c.gridy = y++; panel.add(new NotesPanel(n, controller), c); } this.setLayout(new GridBagLayout()); GridBagConstraints pc = new GridBagConstraints(); pc.gridx = 0; pc.gridy = 0; pc.weightx = 1; pc.weighty = 1; pc.fill = GridBagConstraints.BOTH; panel.setBackground(Color.blue); JScrollPane scroll = new JScrollPane(); scroll.setViewportView(panel); //scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); this.add(scroll, pc); //this.add(panel, pc); // -- Add it all to the layout } //</editor-fold> // <editor-fold defaultstate="collapsed" desc="private methods"> //</editor-fold> } package com.protocase.notes.views; import com.protocase.notes.controller.NotesController; import com.protocase.notes.model.Note; import java.awt.CardLayout; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.text.DateFormat; import java.text.SimpleDateFormat; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.border.BevelBorder; import javax.swing.border.Border; import javax.swing.border.MatteBorder; /** * @author dah01 */ public class NotesPanel extends JPanel { // <editor-fold defaultstate="collapsed" desc="Attributes"> private Note note; private NotesController controller; private CardLayout cardLayout; private JTextArea viewTextArea; private JTextArea editTextArea; //</editor-fold> // <editor-fold defaultstate="collapsed" desc="Getters N' Setters"> public NotesController getController() { return controller; } public void setController(NotesController controller) { this.controller = controller; } public Note getNote() { return note; } public void setNote(Note note) { this.note = note; } //</editor-fold> // <editor-fold defaultstate="collapsed" desc="Constructor"> /** * Sets up a note panel that shows everything about the note. * @param note */ public NotesPanel(Note note, NotesController controller) { this.note = note; cardLayout = new CardLayout(); this.setLayout(cardLayout); // -- Setup the layout manager. this.setBackground(new Color(199, 187, 192)); this.setBorder(new BevelBorder(BevelBorder.RAISED)); // -- ViewPanel this.add("ViewPanel", initViewPanel()); this.add("EditPanel", initEditPanel()); } //</editor-fold> // <editor-fold defaultstate="collapsed" desc="EditPanel"> private JPanel initEditPanel() { JPanel editPanel = new JPanel(); editPanel.setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); c.fill = GridBagConstraints.HORIZONTAL; c.gridy = 0; c.weightx = 1; c.weighty = 0.3; editPanel.add(initCreatorLabel(), c); c.gridy++; editPanel.add(initEditTextScroll(), c); c.gridy++; c.anchor = GridBagConstraints.WEST; c.fill = GridBagConstraints.NONE; editPanel.add(initEditorLabel(), c); c.gridx++; c.anchor = GridBagConstraints.EAST; editPanel.add(initSaveButton(), c); return editPanel; } private JScrollPane initEditTextScroll() { this.editTextArea = new JTextArea(note.getContents()); editTextArea.setLineWrap(true); editTextArea.setWrapStyleWord(true); JScrollPane scrollPane = new JScrollPane(editTextArea); scrollPane.setAlignmentX(JScrollPane.LEFT_ALIGNMENT); Border b = scrollPane.getViewportBorder(); MatteBorder mb = BorderFactory.createMatteBorder(2, 2, 2, 2, Color.BLUE); scrollPane.setBorder(mb); return scrollPane; } private JButton initSaveButton() { final CardLayout l = this.cardLayout; final JPanel p = this; final NotesController c = this.controller; final Note n = this.note; final JTextArea noteText = this.viewTextArea; final JTextArea textToSubmit = this.editTextArea; ActionListener al = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { //controller.saveNote(n); noteText.setText(textToSubmit.getText()); l.next(p); } }; JButton saveButton = new JButton("Save"); saveButton.addActionListener(al); saveButton.setPreferredSize(new Dimension(62, 26)); return saveButton; } //</editor-fold> // <editor-fold defaultstate="collapsed" desc="ViewPanel"> private JPanel initViewPanel() { JPanel viewPanel = new JPanel(); viewPanel.setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); c.fill = GridBagConstraints.HORIZONTAL ; c.gridy = 0; c.weightx = 1; c.weighty = 0.3; viewPanel.add(initCreatorLabel(), c); c.gridy++; viewPanel.add(this.initNoteTextArea(), c); c.fill = GridBagConstraints.NONE; c.anchor = GridBagConstraints.WEST; c.gridy++; viewPanel.add(initEditorLabel(), c); c.gridx++; c.anchor = GridBagConstraints.EAST; viewPanel.add(initEditButton(), c); return viewPanel; } private JLabel initCreatorLabel() { DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); if (note != null) { String noteBy = "Note by " + note.getCreator(); String noteCreated = formatter.format(note.getDateCreated()); JLabel creatorLabel = new JLabel(noteBy + " @ " + noteCreated); creatorLabel.setAlignmentX(JLabel.LEFT_ALIGNMENT); return creatorLabel; } else { System.out.println("NOTE IS NULL"); return null; } } private JScrollPane initNoteTextArea() { // -- Setup the notes area. this.viewTextArea = new JTextArea(note.getContents()); viewTextArea.setEditable(false); viewTextArea.setLineWrap(true); viewTextArea.setWrapStyleWord(true); JScrollPane scrollPane = new JScrollPane(viewTextArea); scrollPane.setAlignmentX(JScrollPane.LEFT_ALIGNMENT); return scrollPane; } private JLabel initEditorLabel() { // -- Setup the edited by label. JLabel editorLabel = new JLabel(" -- Last edited by " + note.getLastEdited() + " at " + note.getDateModified()); editorLabel.setAlignmentX(Component.LEFT_ALIGNMENT); return editorLabel; } private JButton initEditButton() { final CardLayout l = this.cardLayout; final JPanel p = this; ActionListener ar = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { l.next(p); } }; JButton editButton = new JButton("Edit"); editButton.setPreferredSize(new Dimension(62,26)); editButton.addActionListener(ar); return editButton; } //</editor-fold> // <editor-fold defaultstate="collapsed" desc="Grow Width When Resized"> @Override public Dimension getPreferredSize() { int fw = this.getParent().getSize().width; int fh = super.getPreferredSize().height; return new Dimension(fw,fh); } //</editor-fold> }

    Read the article

< Previous Page | 1 2 3 4 5