Search Results

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

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

  • Why am I having this InstantiationException in Java when accessing final local variables?

    - by Oscar Reyes
    I was playing with some code to make a "closure like" construct ( not working btw ) Everything looked fine but when I tried to access a final local variable in the code, the exception InstantiationException is thrown. If I remove the access to the local variable either by removing it altogether or by making it class attribute instead, no exception happens. The doc says: InstantiationException Thrown when an application tries to create an instance of a class using the newInstance method in class Class, but the specified class object cannot be instantiated. The instantiation can fail for a variety of reasons including but not limited to: - the class object represents an abstract class, an interface, an array class, a primitive type, or void - the class has no nullary constructor What other reason could have caused this problem? Here's the code. comment/uncomment the class attribute / local variable to see the effect (lines:5 and 10 ). import javax.swing.*; import java.awt.event.*; import java.awt.*; class InstantiationExceptionDemo { //static JTextField field = new JTextField();// works if uncommented public static void main( String [] args ) { JFrame frame = new JFrame(); JButton button = new JButton("Click"); final JTextField field = new JTextField();// fails if uncommented button.addActionListener( new _(){{ System.out.println("click " + field.getText()); }}); frame.add( field ); frame.add( button, BorderLayout.SOUTH ); frame.pack();frame.setVisible( true ); } } class _ implements ActionListener { public void actionPerformed( ActionEvent e ){ try { this.getClass().newInstance(); } catch( InstantiationException ie ){ throw new RuntimeException( ie ); } catch( IllegalAccessException ie ){ throw new RuntimeException( ie ); } } } Is this a bug in Java? edit Oh, I forgot, the stacktrace ( when thrown ) is: Caused by: java.lang.InstantiationException: InstantiationExceptionDemo$1 at java.lang.Class.newInstance0(Class.java:340) at java.lang.Class.newInstance(Class.java:308) at _.actionPerformed(InstantiationExceptionDemo.java:25)

    Read the article

  • Java Stopping JApplet Components from Resizing based on Applet Size

    - by Doug
    Creating a JApplet I have 2 Text Fields, a button and a Text Area. private JPanel addressEntryPanel = new JPanel(new GridLayout(1,3)); private JPanel outputPanel = new JPanel(new GridLayout(1,1)); private JTextField serverTf = new JTextField(""); private JTextField pageTf = new JTextField(""); private JTextArea outputTa = new JTextArea(); private JButton connectBt = new JButton("Connect"); private JScrollPane outputSp = new JScrollPane(outputTa); public void init() { setSize(500,500); setLayout(new GridLayout(3,1)); add(addressEntryPanel); addressEntryPanel.add(serverTf); addressEntryPanel.add(pageTf); addressEntryPanel.add(connectBt); addressEntryPanel.setPreferredSize(new Dimension(50,50)); addressEntryPanel.setMaximumSize(addressEntryPanel.getPreferredSize()); addressEntryPanel.setMinimumSize(addressEntryPanel.getPreferredSize()); add(outputPanel); outputPanel.add(outputSp); outputTa.setLineWrap(true); connectBt.addActionListener(this); The problem is when debugging and putting it in a page the components / panels resize depending on the applet size. I don't want this. I want the textfields to be a certain size, and the text area to be a certain size. I've put stuff in there to set the size of them but they aren't working. How do I go about actually setting a strict size for either the components or the JPanel.

    Read the article

  • Is it Possible to show a previously hidden JFrame using a keylistener

    - by JIM
    here is my code, i basically just did a tester for the most common listeners, which i might later use in future projects, the main problem is in the keylistener at the bottom, i am trying to re-show the frame but i think it just cant be done that way, please help ps: no idea why the imports dont show up right. package newpackage; import java.awt.Color; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JTextField; import javax.swing.JSeparator; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.JTextArea; import javax.swing.SwingUtilities; import javax.swing.UIManager; public class NewClass1 extends JFrame { private JLabel item1,infomouse,infoclicks,infoKeys,writehere; private JButton button1,button2,button3; private JTextArea text1,status,KeyStatus; private JTextField text2,text3,mouse,clicks,test; private JSeparator sep1; private int clicknumber; public NewClass1() { super("Listener Tests"); setLayout(null); sep1 = new JSeparator(); button1 = new JButton("Button1"); button2 = new JButton("Button2"); button3 = new JButton("Button3"); item1 = new JLabel("Button Status :"); infomouse = new JLabel("Mouse Status :"); infoclicks = new JLabel("Nº of clicks :"); infoKeys = new JLabel("Keyboard status:"); writehere = new JLabel("Write here: "); text1 = new JTextArea(); text2 = new JTextField(20); text3 = new JTextField(20); status = new JTextArea(); mouse = new JTextField(20); clicks = new JTextField(4); KeyStatus = new JTextArea(); test = new JTextField(3); clicks.setText(String.valueOf(clicknumber)); text1.setEditable(true); text2.setEditable(false); text3.setEditable(false); status.setEditable(false); mouse.setEditable(false); clicks.setEditable(false); KeyStatus.setEditable(false); text1.setBounds(135, 310, 150, 20); text2.setBounds(135, 330, 150, 20); text3.setBounds(135, 350, 150, 20); status.setBounds(15, 20, 240, 20); infomouse.setBounds(5,45,120,20); infoKeys.setBounds(5,90,120,20); KeyStatus.setBounds(15,115,240,85); test.setBounds(15,225,240,20); mouse.setBounds(15,70,100,20); infoclicks.setBounds(195, 45, 140, 20); clicks.setBounds(195, 70, 60, 20); item1.setBounds(5, 0, 120, 20); button1.setBounds(10, 310, 115, 20); button2.setBounds(10, 330, 115, 20); button3.setBounds(10, 350, 115, 20); sep1.setBounds(5, 305, 285, 10); sep1.setBackground(Color.BLACK); status.setBackground(Color.LIGHT_GRAY); button1.addActionListener(new button1list()); button2.addActionListener(new button1list()); button3.addActionListener(new button1list()); button1.addMouseListener(new MouseList()); button2.addMouseListener(new MouseList()); button3.addMouseListener(new MouseList()); getContentPane().addMouseListener(new MouseList()); test.addKeyListener(new KeyList()); this.addKeyListener(new KeyList()); test.requestFocus(); add(item1); add(button1); add(button2); add(button3); add(text1); add(text2); add(text3); add(status); add(infomouse); add(mouse); add(infoclicks); add(clicks); add(infoKeys); add(KeyStatus); add(test); add(sep1); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); try{ UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); }catch (Exception e){System.out.println("Error");} SwingUtilities.updateComponentTreeUI(this); setSize(300, 400); setResizable(false); setVisible(true); test.setFocusable(true); test.setFocusTraversalKeysEnabled(false); setLocationRelativeTo(null); } public class button1list implements ActionListener { public void actionPerformed(ActionEvent e) { String buttonpressed = e.getActionCommand(); if (buttonpressed.equals("Button1")) { text1.setText("just"); } else if (buttonpressed.equals("Button2")) { text2.setText(text2.getText()+"testing "); } else if (buttonpressed.equals("Button3")) { text3.setText("this"); } } } public class MouseList implements MouseListener{ public void mouseEntered(MouseEvent e){ if(e.getSource()==button1){ status.setText("button 1 hovered"); } else if(e.getSource()==button2){ status.setText("button 2 hovered"); } else if(e.getSource()==button3){ status.setText("button 3 hovered"); } } public void mouseExited(MouseEvent e){ status.setText(""); } public void mouseReleased(MouseEvent e){ if(!status.getText().equals("")){ status.replaceRange("", 0, 22); } } public void mousePressed(MouseEvent e){ if(e.getSource()==button1){ status.setText("button 1 being pressed"); } else if(e.getSource()==button2){ status.setText("button 2 being pressed"); } else if(e.getSource()==button3){ status.setText("button 3 being pressed"); } } public void mouseClicked(MouseEvent e){ clicknumber++; mouse.setText("mouse working"); clicks.setText(String.valueOf(clicknumber)); } } public class KeyList implements KeyListener{ public void keyReleased(KeyEvent e){} public void keyPressed(KeyEvent e){ KeyStatus.setText(""); test.setText(""); String full = e.paramString(); String [] temp = null; temp = full.split(","); for(int i=0; i<7 ;i++){ KeyStatus.append(temp[i] + "\n"); } if(e.getKeyChar()=='h'){setVisible(false); test.requestFocus(); } if(e.getKeyChar()=='s'){setVisible(true);} } public void keyTyped(KeyEvent e){} } }

    Read the article

  • mig layout - span and grow/push problem

    - by pstanton
    i want 3 components laid out on 2 lines, so that the bottom component and the top-right component use all available horizontal space. JFrame frame = new JFrame(); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.setLayout(new MigLayout("debug, fill")); Container cp = frame.getContentPane(); cp.add(new JTextField("component 1"), ""); cp.add(new JTextField("component 2"), "growx,push,wrap"); cp.add(new JTextField("component 3"), "span,growx,push"); frame.pack(); frame.setVisible(true); considering the above, how do i stop the space between "component 1" and "component 2" from appearing when resizing the frame? thanks.

    Read the article

  • creating BeanInfo objects in NetBeans 6.1 does not work for some objects

    - by Coder
    I have recently learned about BeanInfo classes in Java, and have successfully used them to add icons to my custom GUI components which extend swing components such as JTextField, however i have a more specialized GUI component which extends from another one of my GUI components, which then extends from JTextField. Ie. the class hierarchy is of the form "A - B - JTextField". I can create a bean info object that works for class B, but when i click on the bean info editor option in netbeans to create a bean info object for class A, nothing happens. Ie. there is no error pop-up and a bean info object is not created. There isn't much difference between class A and B. Both A and B have default no argument constructors and they are very similar to each other. The only thing i can really think of is that A uses generics and B does not. I would like to create a beaninfo object for class A so that i can add custom icons for that component. Any help would be appreciated. Thanks.

    Read the article

  • Delay in displaying contents in JDialog

    - by Yohan
    Please have a look at the following code import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.util.List; import java.util.ArrayList; public class SendEmailForm extends JDialog { private JLabel to, cc, bcc, subject, account; private JTextField toTxt, ccTxt, bccTxt, subjectTxt; private JTextArea messageTxt; private JButton send; private JComboBox accountBox; private JScrollPane scroll; private GridBagLayout gbl; private GridBagConstraints gbc; public SendEmailForm() { //Declaring instance variables to = new JLabel("To: "); cc = new JLabel("CC: "); bcc = new JLabel("BCC: "); subject = new JLabel("Subject: "); account = new JLabel("Select an Account: "); toTxt = new JTextField(20); ccTxt = new JTextField(20); bccTxt = new JTextField(20); subjectTxt = new JTextField(20); messageTxt = new JTextArea(20, 50); messageTxt.setLineWrap(true); scroll = new JScrollPane(messageTxt); scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); accountBox = new JComboBox(); accountBox.addItem("Yahoo"); accountBox.addItem("GMail"); accountBox.addItem("MSN"); //accountBox.addItem("Yahoo"); //accountBox.addItem("Yahoo"); JPanel buttonPanel = new JPanel(); buttonPanel.setLayout(new FlowLayout()); send = new JButton("Send"); send.addActionListener(new SendButtonAction()); buttonPanel.add(send); //Creating thr GUI //GUI CREATION IS REMOVED IN THIS POST this.setTitle("Send Emails"); this.setVisible(true); this.pack(); this.setLocationRelativeTo(null); this.validate(); } private class SendButtonAction implements ActionListener { public void actionPerformed(ActionEvent ae) { ProgressMonitor pm = new ProgressMonitor(); //Retreiving the user name and password List userData = new ArrayList(); EmailDBConnector emailCon = new EmailDBHandler(); userData = emailCon.getUserNameAndPassword( accountBox.getSelectedItem().toString().trim()); String userName = userData.get(0).toString(); String password = userData.get(1).toString(); System.out.println(userName); System.out.println(password); pm.setVisible(true); SendEmail sendEmail = new SendEmail(toTxt.getText(), userName.trim(), bccTxt.getText(), ccTxt.getText(), accountBox.getSelectedItem().toString().trim(), messageTxt.getText().trim(), password.trim(), subjectTxt.getText()); String result = sendEmail.send(); //pm.dispose(); JOptionPane.showMessageDialog(null, result); } } private class ProgressMonitor extends JDialog { public ProgressMonitor() { this.setLayout(new BorderLayout()); JLabel text = new JLabel("Sending..Please wait..."); this.add(text, "Center"); this.pack(); this.validate(); this.setLocationRelativeTo(null); } } } First, this is an email program. In here, when the JDialog is called, it just opens as a 100% blank window. I have added a JLabel, but it is not there when it is displaying. Anyway, it takes sometime to send the email, after the email is sent, I can see the JLabel in the JDialog. If I take my issue into one sentence, I am calling the JDialog before the email is sent, but it appears blank, after the email is sent, it's content are there! Why is this? Please help!

    Read the article

  • Java accessing variables using extends

    - by delo
    So here I have two classes: Customer Order Class and Confirmation Class. I want to access the data stored in LastNameTextField (Customer Order Class) and set it as the text for UserLastNameLabel (Confirmation Class) after clicking a "Submit" button. For some reason however, the output displays nothing. Snippet of my code: package customer_order; public class customer_order extends Frame{ private static final long serialVersionUID = 1L; private JPanel jPanel = null; private JLabel LastNameLabel = null; protected JTextField LastNameTextField = null; private JButton SubmitButton = null; public String s; public customer_order() { super(); initialize(); } private void initialize() { this.setSize(729, 400); this.setTitle("Customer Order"); this.add(getJPanel(), BorderLayout.CENTER); } /** * This method initializes LastNameTextField * * @return javax.swing.JTextField */ public JTextField getLastNameTextField() { if (LastNameTextField == null) { LastNameTextField = new JTextField(); LastNameTextField.setBounds(new Rectangle(120, 100, 164, 28)); LastNameTextField.setName("LastNameTextField"); } return LastNameTextField; } /** * This method initializes SubmitButton * * @return javax.swing.JButton */ private JButton getSubmitButton() { if (SubmitButton == null) { SubmitButton = new JButton(); SubmitButton.setBounds(new Rectangle(501, 225, 96, 29)); SubmitButton.setName("SubmitButton"); SubmitButton.setText("Submit"); SubmitButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent e) { System.out.println("actionPerformed()"); // TODO Auto-generated Event stub actionPerformed() //THE STRING I WANT s = LastNameTextField.getText(); java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new confirmation().setVisible(true); } }); } }); } return SubmitButton; } package customer_order; public class confirmation extends customer_order{ private static final long serialVersionUID = 1L; private JPanel jPanel = null; // @jve:decl-index=0:visual-constraint="58,9" private JLabel LastNameLabel = null; private JLabel UserLastNameLabel = null; // @jve:decl-index=0: /** * This method initializes frame * * @return java.awt.Frame */ public confirmation() { super(); initialize(); } private void initialize() { this.setSize(729, 400); this.setTitle("Confirmation"); this.add(getJPanel(), BorderLayout.CENTER); } /** * This method initializes jPanel * * @return javax.swing.JPanel */ private JPanel getJPanel() { if (jPanel == null) { UserLastNameLabel = new JLabel(); UserLastNameLabel.setBounds(new Rectangle(121, 60, 167, 26)); //THE PROBLEM? UserLastNameLabel.setText(s); } return jPanel; }

    Read the article

  • Line up swing components by edges

    - by rasen58
    Is it possible to line up swing components? The components are in separate panels which both use flow layout. These two panels are in another panel which is using a grid layout. As you can see there is a subtle difference and I find it annoying. I know that all of the jlabels [the rectangles in blue/purple all have the same size, so i think it might be because of the '+' and '*', but I'm not sure because the left sides of the first two boxes aren't lined up. the panels JPanel panel2 = new JPanel(new GridLayout(4, 1)); JPanel panel2a = new JPanel(new FlowLayout()); JPanel panel2b = new JPanel(new FlowLayout()); the first two rectangles (purple) add1 = new JLabel("", JLabel.CENTER); add1.setTransferHandler(new TransferHandler("text")); add1.setBorder(b2); add2 = new JLabel("", JLabel.CENTER); add2.setTransferHandler(new TransferHandler("text")); add2.setBorder(b2); the two blue rectangles textFieldA = new JTextField(); textFieldA.setHorizontalAlignment(JTextField.CENTER); textFieldA.setEditable(false); textFieldA.setBorder(new LineBorder(Color.blue)); textFieldM = new JTextField(); textFieldM.setHorizontalAlignment(JTextField.CENTER); textFieldM.setEditable(false); textFieldM.setBorder(new LineBorder(Color.blue)); the + and * opA = new JLabel("+", JLabel.CENTER); opS = new JLabel("*", JLabel.CENTER); Showing that the rectangles are the same size Dimension d = card1.getPreferredSize(); int width = d.width + 100; int height = d.height + 50; add1.setPreferredSize(new Dimension(width, height)); add2.setPreferredSize(new Dimension(width, height)); mult1.setPreferredSize(new Dimension(width, height)); mult2.setPreferredSize(new Dimension(width, height)); textFieldA.setPreferredSize(new Dimension(width, height)); textFieldM.setPreferredSize(new Dimension(width, height)); Adding to the panels panel2a.add(add1); panel2a.add(opA); panel2a.add(add2); panel2a.add(enterA); panel2a.add(textFieldA); panel2c.add(mult1); panel2c.add(opM); panel2c.add(mult2); panel2c.add(enterM); panel2c.add(textFieldM); panel2.add(panel2a); panel2.add(panel2c);

    Read the article

  • GroupLayout: JScrollPane in TextArea is not working

    - by Dozent
    i'm new in java and recently started to develop an simple application. For the moment i have a problem with JScrollPanne, it's not able to scroll down (or up) when the text in textarea more than size of area. I have looked to some solutions, but all of them were for FlowLayot (GridLayout and BoxLayout), but not for GroupLayout. Here is the code: JPanel conent_p = new JPanel(); conent_p.setBorder(new TitledBorder(null, "", TitledBorder.LEADING, TitledBorder.TOP, null, null)); JLabel lblItemName = new JLabel("Item name:"); itemField = new JTextField(); itemField.setColumns(10); JLabel lblMxPrice = new JLabel("Max price:"); mpriceField = new JTextField(); mpriceField.setColumns(10); JLabel lblQuantity = new JLabel("Quantity:"); quanField = new JTextField(); quanField.setColumns(10); JLabel lblDelivery = new JLabel("Delivery:"); delivField = new JTextField(); delivField.setColumns(10); JLabel lblLogcat = new JLabel("LogCat:"); final JTextArea txtConsole = new JTextArea(); txtConsole.setEditable(false); txtConsole.setLineWrap(true); txtConsole.setWrapStyleWord(true); sbrText = new JScrollPane(txtConsole); sbrText.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); // Now create a new TextAreaOutputStream to write to our JTextArea control and wrap a // PrintStream around it to support the println/printf methods. PrintStream out = new PrintStream(new TextAreaOutputStream(txtConsole)); // redirect standard output stream to the TextAreaOutputStream System.setOut(out); // redirect standard error stream to the TextAreaOutputStream System.setErr(out); GroupLayout gl_conent_p = new GroupLayout(conent_p); gl_conent_p.setHorizontalGroup( gl_conent_p.createParallelGroup(Alignment.LEADING) .addGroup(gl_conent_p.createSequentialGroup() .addContainerGap() .addGroup(gl_conent_p.createParallelGroup(Alignment.LEADING) .addComponent(lblMxPrice, Alignment.TRAILING) .addComponent(lblItemName, Alignment.TRAILING) .addComponent(lblLogcat, Alignment.TRAILING)) .addGap(18) .addGroup(gl_conent_p.createParallelGroup(Alignment.LEADING) .addGroup(gl_conent_p.createSequentialGroup() .addGroup(gl_conent_p.createParallelGroup(Alignment.LEADING, false) .addComponent(itemField, GroupLayout.PREFERRED_SIZE, 365, GroupLayout.PREFERRED_SIZE) .addGroup(gl_conent_p.createSequentialGroup() .addComponent(mpriceField, GroupLayout.PREFERRED_SIZE, 80, GroupLayout.PREFERRED_SIZE) .addGap(18) .addComponent(lblQuantity) .addPreferredGap(ComponentPlacement.RELATED) .addComponent(quanField, 0, 0, Short.MAX_VALUE) .addGap(18) .addComponent(lblDelivery) .addPreferredGap(ComponentPlacement.RELATED) .addComponent(delivField, GroupLayout.PREFERRED_SIZE, 80, GroupLayout.PREFERRED_SIZE) .addPreferredGap(ComponentPlacement.RELATED))) .addGap(100)) .addGroup(gl_conent_p.createSequentialGroup() .addComponent(txtConsole, GroupLayout.PREFERRED_SIZE, 345, GroupLayout.PREFERRED_SIZE) .addComponent(sbrText) .addContainerGap()))) ); gl_conent_p.setVerticalGroup( gl_conent_p.createParallelGroup(Alignment.LEADING) .addGroup(gl_conent_p.createSequentialGroup() .addContainerGap() .addGroup(gl_conent_p.createParallelGroup(Alignment.BASELINE) .addComponent(lblItemName) .addComponent(itemField, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE)) .addGap(20) .addGroup(gl_conent_p.createParallelGroup(Alignment.LEADING) .addGroup(gl_conent_p.createParallelGroup(Alignment.BASELINE) .addComponent(lblDelivery) .addComponent(delivField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)) .addGroup(gl_conent_p.createParallelGroup(Alignment.BASELINE) .addComponent(lblMxPrice) .addComponent(mpriceField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addComponent(lblQuantity) .addComponent(quanField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))) .addGap(55) .addGroup(gl_conent_p.createParallelGroup(Alignment.BASELINE) .addComponent(lblLogcat) .addComponent(txtConsole, GroupLayout.PREFERRED_SIZE, 200, GroupLayout.PREFERRED_SIZE) .addComponent(sbrText)) .addContainerGap()) ); conent_p.setLayout(gl_conent_p); getContentPane().add(conent_p, BorderLayout.NORTH); JButton btnBuy = new JButton("Buy"); btnBuy.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent ev) { try { String title = itemField.getText().trim(); String mprice = mpriceField.getText().trim(); String quantity = quanField.getText().trim(); String deliver = delivField.getText().trim(); Item_CONCEPT item = new Item_CONCEPT(); item.setName(title); item.setDelivery(Integer.parseInt(deliver)); item.setStartPrice(0); item.setMaxPrice(Integer.parseInt(mprice)); myAgent.existsSeller(item); Date date = new Date(); DateFormat df = new SimpleDateFormat("dd.MM.yy HH:mm"); System.out.println(df.format(date)+": Buyer orders an item: "+item.getName()); //Clearing all fields itemField.setText(""); quanField.setText(""); delivField.setText(""); //txtConsole.setText(""); mpriceField.setText(""); } catch (Exception e) { JOptionPane.showMessageDialog(BuyerGUI.this, "A field is filled incorrectly. "+e.getMessage()+" is invalid.", "Error", JOptionPane.ERROR_MESSAGE); } } } );![enter image description here][1]

    Read the article

  • Cannot bind text field to selected item in JTable in NetBeans

    - by titaniumdecoy
    I am trying to use NetBeans to bind a JTextField to the selected element of a JTable. The JTable gets its data from an AbstractTableModel subclass which returns Cow objects. At present, each Cow object is displayed as a string through its toString method. The binding seems obvious but does not work; the bound value of the text field is always null. I bound the text property of the JTextField in NetBeans to: flowTable[${selectedElement.prefix}] This produces the following line of generated code: org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, flowTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.prefix}"), courseNameTextField, org.jdesktop.beansbinding.BeanProperty.create("text")); What am I doing wrong?

    Read the article

  • Why do I keep on getting an exception-illegal operation on ResultSet?

    - by eli1987
    Here is the code-admittedly I'm terrible at Java, but surely I catch a null result set with the if....else statement....sorry its the whole Class: /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * SearchParts.java * * Created on 08-Mar-2010, 12:14:31 */ package garits; import java.sql.*; import javax.swing.*; /** * * @author Deniz */ public class SearchParts extends javax.swing.JFrame { /** Creates new form SearchParts */ public SearchParts() { 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") private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { if (!jTextField1.getText().equals("")) { String result = ""; int Partnumber = Integer.parseInt(jTextField1.getText()); DB db = new DB(); try { db.connect(); String query = "Select * from Stock Where Part_no =" + "'" + jTextField1.getText() + "'"; ResultSet rs = db.execSQL(query); if (rs.equals(null)) { PartNotFound nf = new PartNotFound(); nf.setVisible(true); } else { ResultSetMetaData rsmd = rs.getMetaData(); int numberOfColumns = rsmd.getColumnCount(); int RowCount = 0; for (int i = 1; i < numberOfColumns; i++) { rs.getString(i); result += i + "/n"; } if (!result.equals("")) { Receptionist_FranchiseePartFound part = new Receptionist_FranchiseePartFound(); part.setVisible(true); while (rs.next()) { RowCount++; } part.getTable().addRowSelectionInterval(0, RowCount); } else { PartNotFound nf = new PartNotFound(); } } } catch (Exception e) { e.printStackTrace(); JOptionPane.showMessageDialog(jButton1, "More information needed for search", "Error Message", JOptionPane.ERROR_MESSAGE); } } else if (!jTextField2.getText().equals("")) { String result = ""; DB db = new DB(); try { db.connect(); String query = "Select * from Stock Where Part_name =" + "'" + jTextField2.getText() + "'"; ResultSet rs = db.execSQL(query); if (rs.equals(null)) { PartNotFound nf = new PartNotFound(); nf.setVisible(true); } else { ResultSetMetaData rsmd = rs.getMetaData(); int numberOfColumns = rsmd.getColumnCount(); int RowCount = 0; for (int i = 1; i < numberOfColumns; i++) { rs.getString(i); result += i + "/n"; } // Receptionist_FranchiseePartFound part = new Receptionist_FranchiseePartFound(); // part.setVisible(true); if (!result.equals("")) { Receptionist_FranchiseePartFound part = new Receptionist_FranchiseePartFound(); part.setVisible(true); while (rs.next()) { RowCount++; } part.getTable().addRowSelectionInterval(0, RowCount); } else { PartNotFound nf = new PartNotFound(); nf.setVisible(true); } } } catch (Exception e) { e.printStackTrace(); JOptionPane.showMessageDialog(jButton1, "More information needed for search", "Error Message", JOptionPane.ERROR_MESSAGE); } } else if (jTextField1.getText().equals("") && jTextField2.getText().equals("")) { String result = ""; DB db = new DB(); try { db.connect(); String query = "Select * from Stock Where Manufacturer =" + "'" + jTextField3.getText() + "'AND Vehicle_type ='" + jTextField4.getText() + "'"; ResultSet rs = db.execSQL(query); if (rs.equals(null)) { PartNotFound nf = new PartNotFound(); nf.setVisible(true); } else{ ResultSetMetaData rsmd = rs.getMetaData(); int numberOfColumns = rsmd.getColumnCount(); int RowCount = 0; for (int i = 1; i < numberOfColumns; i++) { rs.getString(i); result += i + "/n"; } // Receptionist_FranchiseePartFound part = new Receptionist_FranchiseePartFound(); // part.setVisible(true); if (!result.equals("")) { Receptionist_FranchiseePartFound part = new Receptionist_FranchiseePartFound(); part.setVisible(true); while (rs.next()) { RowCount++; } part.getTable().addRowSelectionInterval(0, RowCount); } else { PartNotFound nf = new PartNotFound(); nf.setVisible(true); } } } catch (Exception e) { e.printStackTrace(); JOptionPane.showMessageDialog(jButton1, "More information needed for search", "Error Message", JOptionPane.ERROR_MESSAGE); } } else if (jTextField3.getText().equals("") || jTextField4.getText().equals("")) { JOptionPane.showMessageDialog(jButton1, "More information needed for search", "Error Message", JOptionPane.ERROR_MESSAGE); } } /** * @param args the command line arguments */ // Variables declaration - do not modify private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JTextField jTextField1; private javax.swing.JTextField jTextField2; private javax.swing.JTextField jTextField3; private javax.swing.JTextField jTextField4; // End of variables declaration }

    Read the article

  • GroupLayout giving error with java swing

    - by Name
    I am getting some long list of error . Can anyone suggest me where i am wrong with group layout layout.setHorizontalGroup( layout.createSequentialGroup() .addComponent(new JLabel("Enter Book Name")) .addComponent(new JTextField("TextField", 20)) ); ERROR Exception in thread "main" java.lang.IllegalStateException: javax.swing.JTextField[,0,0,0x0,invalid,layout=javax.swing.plaf.basic.BasicTextUI$UpdateHandler,alignmentX=0.0,alignmentY=0.0,border=javax.swing.plaf.BorderUIResource$CompoundBorderUIResource@3d0bbf9e,flags=296,maximumSize=,minimumSize=,preferredSize=,caretColor=sun.swing.PrintColorUIResource[r=51,g=51,b=51],disabledTextColor=javax.swing.plaf.ColorUIResource[r=184,g=207,b=229],editable=true,margin=javax.swing.plaf.InsetsUIResource[top=0,left=0,bottom=0,right=0],selectedTextColor=sun.swing.PrintColorUIResource[r=51,g=51,b=51],selectionColor=javax.swing.plaf.ColorUIResource[r=184,g=207,b=229],columns=20,columnWidth=0,command=,horizontalAlignment=LEADING] is not attached to a vertical group at javax.swing.GroupLayout.checkComponents(Unknown Source) at javax.swing.GroupLayout.prepare(Unknown Source)

    Read the article

  • Java programming accessing object variables

    - by Haxed
    Helo, there are 3 files, CustomerClient.java, CustomerServer.java and Customer.java PROBLEM: In the CustomerServer.java file, i get an error when I compile the CustomerServer.java at line : System.out.println(a[k].getName()); ERROR: init: deps-jar: Compiling 1 source file to C:\Documents and Settings\TLNA\My Documents\NetBeansProjects\Server\build\classes C:\Documents and Settings\TLNA\My Documents\NetBeansProjects\Server\src\CustomerServer.java:44: cannot find symbol symbol : method getName() location: class Customer System.out.println(a[k].getName()); 1 error BUILD FAILED (total time: 0 seconds) CustomerClient.java import java.io.*; import java.net.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.border.*; public class CustomerClient extends JApplet { private JTextField jtfName = new JTextField(32); private JTextField jtfSeatNo = new JTextField(32); // Button for sending a student to the server private JButton jbtRegister = new JButton("Register to the Server"); // Indicate if it runs as application private boolean isStandAlone = false; // Host name or ip String host = "localhost"; public void init() { JPanel p1 = new JPanel(); p1.setLayout(new GridLayout(2, 1)); p1.add(new JLabel("Name")); p1.add(jtfName); p1.add(new JLabel("Seat No.")); p1.add(jtfSeatNo); add(p1, BorderLayout.CENTER); add(jbtRegister, BorderLayout.SOUTH); // Register listener jbtRegister.addActionListener(new ButtonListener()); // Find the IP address of the Web server if (!isStandAlone) { host = getCodeBase().getHost(); } } /** Handle button action */ private class ButtonListener implements ActionListener { public void actionPerformed(ActionEvent e) { try { // Establish connection with the server Socket socket = new Socket(host, 8000); // Create an output stream to the server ObjectOutputStream toServer = new ObjectOutputStream(socket.getOutputStream()); // Get text field String name = jtfName.getText().trim(); String seatNo = jtfSeatNo.getText().trim(); // Create a Student object and send to the server Customer s = new Customer(name, seatNo); toServer.writeObject(s); } catch (IOException ex) { System.err.println(ex); } } } /** Run the applet as an application */ public static void main(String[] args) { // Create a frame JFrame frame = new JFrame("Register Student Client"); // Create an instance of the applet CustomerClient applet = new CustomerClient(); applet.isStandAlone = true; // Get host if (args.length == 1) { applet.host = args[0]; // Add the applet instance to the frame } frame.add(applet, BorderLayout.CENTER); // Invoke init() and start() applet.init(); applet.start(); // Display the frame frame.pack(); frame.setVisible(true); } } CustomerServer.java import java.io.*; import java.net.*; public class CustomerServer { private String name; private int i; private ObjectOutputStream outputToFile; private ObjectInputStream inputFromClient; public static void main(String[] args) { new CustomerServer(); } public CustomerServer() { Customer[] a = new Customer[30]; try { // Create a server socket ServerSocket serverSocket = new ServerSocket(8000); System.out.println("Server started "); // Create an object ouput stream outputToFile = new ObjectOutputStream( new FileOutputStream("student.dat", true)); while (true) { // Listen for a new connection request Socket socket = serverSocket.accept(); // Create an input stream from the socket inputFromClient = new ObjectInputStream(socket.getInputStream()); // Read from input //Object object = inputFromClient.readObject(); for (int k = 0; k <= 2; k++) { if (a[k] == null) { a[k] = (Customer) inputFromClient.readObject(); // Write to the file outputToFile.writeObject(a[k]); //System.out.println("A new student object is stored"); System.out.println(a[k].getName()); break; } if (k == 2) { //fully booked outputToFile.writeObject("All seats are booked"); break; } } } } catch (ClassNotFoundException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } finally { try { inputFromClient.close(); outputToFile.close(); } catch (Exception ex) { ex.printStackTrace(); } } } } Customer.java public class Customer implements java.io.Serializable { private String name; private String seatno; public Customer(String name, String seatno) { this.name = name; this.seatno = seatno; } public String getName() { return name; } public String getSeatNo() { return seatno; } }

    Read the article

  • JButton and next/previous object of treemap

    - by supacat
    I have this problem: 1) There are objects placed in the TreeMap through the JTextField. (Phonebook-like program). 2)There are buttons that implement view of available records in TreeMap. When you click on these buttons next / previous available objects of TreeMap displaying in JTextField. (scroll through the available records). I tried this code, but I didn't work :/ btn[4].addActionListener(new ActionListener(){ Iterator iter = tree.keySet().iterator(); public void actionPerformed(ActionEvent e) { if (iter.hasNext()){ String str = iter.next().toString(); fldFio.setText(str); fldNumber.setText(tree.get(str)); } } });

    Read the article

  • How do scroll the contents to bottom by default in JTextPane?

    - by Nitesh Panchal
    Hello, I have JTextPane on my window and i have JTextField. When i press enter enter in JTextField, the text gets added in JTextPane. Everything works fine and scrollbar too appears on its own. But, it doesn't appear properly. It automatically scrolls to the beginning of the content in JTextPane. How do i keep the scrollbar to the end of JTextPane? Please let me know if my question is unclear. Thanks in advance :)

    Read the article

  • Using MigLayout, why is a JButton following a JTable unresponsive and how to fix this?

    - by M. Joanis
    Hi everyone, I am having a mind-boggling problem regarding the use of a JButton following a JTable with MigLayout. It is totally unresponsive unless I push it far enough past the JTable (then it can behave correctly). I have tried running the code with both the MigLayout JAR of the version we use for end user products and with the very most recent one; same result. Here is a sample code reproducing the problem (Main.java): import java.awt.Dimension; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.table.DefaultTableModel; import net.miginfocom.swing.MigLayout; @SuppressWarnings("serial") public class Main extends JFrame { private JPanel panel; private JTextField textField; private JButton chooseButton; private JTable table; private JButton reloadButton; private final DefaultTableModel model = new DefaultTableModel() { @Override public boolean isCellEditable(int row, int column) { return false; } }; public Main() { panel = new JPanel(new MigLayout("debug", "[][grow][]")); setContentPane(panel); setDefaultCloseOperation(EXIT_ON_CLOSE); /*** First row ***/ // "File:" panel.add(new JLabel("File:")); // textField for filename textField = new JTextField("No file selected yet!"); textField.setEditable(false); panel.add(textField, "growx"); // "Choose..." button chooseButton = new JButton("Choose..."); panel.add(chooseButton, "wrap, sg buttons"); /*** Second row ***/ panel.add(new JLabel()); table = new JTable(model); model.setColumnIdentifiers(new String[] {"col title"}); JScrollPane scrollpane = new JScrollPane(table); Dimension scrollpaneDimension = new Dimension(125, 110); scrollpane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); table.setPreferredScrollableViewportSize(scrollpaneDimension); table.setFillsViewportHeight(true); panel.add(table.getTableHeader(), "grow"); panel.add(scrollpane, "grow"); reloadButton = new JButton("Reload"); panel.add(reloadButton, "top, wrap, sg buttons"); pack(); setVisible(true); } public static void main(String[] args) { new Main(); } } I suppose it has something to do with the table header and the table itself ending up in the same layout cell, but I'm really not sure of this. As I said, if I push the button far enough past the JTable, it will work again. If I drop it on the next row, it doesn't work, I have to move it down one more row. The only library you need in your workspace to run the code is MigLayout. Thank you all for your help, much appreciated! M. Joanis

    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

  • 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

  • Counting the number of words in a text area

    - by user1320483
    Hello everyone my first question on stack overflow import javax.swing.*; import java.util.*; import java.awt.event.*; public class TI extends JFrame implements ActionListener { static int count=0; String ct; JTextField word; JTextArea tohide; public static void main(String arg[]) { TI ti=new TI(); } public TI() { JPanel j=new JPanel(); JLabel def=new JLabel("Enter the text to be encrypted"); word=new JTextField("",20); tohide=new JTextArea("",5,20); JButton jb=new JButton("COUNT"); tohide.setBorder(BorderFactory.createLoweredBevelBorder()); j.add(def); j.add(tohide); j.add(word); j.add(jb); add(j); setSize(500,500); setVisible(true); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); jb.addActionListener(this); } public void actionPerformed(ActionEvent ae) { String txt=tohide.getText(); StringTokenizer stk=new StringTokenizer(txt," "); while(stk.hasMoreTokens()) { String token=stk.nextToken(); count++; } ct=Integer.toString(count);; word.setText(ct); } } I want to count the number of words that are being typed in the textarea.There is a logical error.As I keep clicking the count button the word count increases.

    Read the article

  • Best Practice With JFrame Constructors?

    - by David Barry
    In both my Java classes, and the books we used in them laying out a GUI with code heavily involved the constructor of the JFrame. The standard technique in the books seems to be to initialize all components and add them to the JFrame in the constructor, and add anonymous event handlers to handle events where needed, and this is what has been advocated in my class. This seems to be pretty easy to understand, and easy to work with when creating a very simple GUI, but seems to quickly get ugly and cumbersome when making anything other than a very simple gui. Here is a small code sample of what I'm describing: public class FooFrame extends JFrame { JLabel inputLabel; JTextField inputField; JButton fooBtn; JPanel fooPanel; public FooFrame() { super("Foo"); fooPanel = new JPanel(); fooPanel.setLayout(new FlowLayout()); inputLabel = new JLabel("Input stuff"); fooPanel.add(inputLabel); inputField = new JTextField(20); fooPanel.add(inputField); fooBtn = new JButton("Do Foo"); fooBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { //handle event } }); fooPanel.add(fooBtn); add(fooPanel, BorderLayout.CENTER); } } Is this type of use of the constructor the best way to code a Swing application in java? If so, what techniques can I use to make sure this type of constructor is organized and maintainable? If not, what is the recommended way to approach putting together a JFrame in java?

    Read the article

  • Netbeans GUI building on pre-defined code

    - by deliriumtremens
    I am supposed edit some code for an assignment, and he gave us the framework and wants us to implement code for it. I load the project into netbeans and can't figure out how I'm supposed to edit the swing components. I don't see how to edit source vs. design. import javax.swing.*; import java.util.*; import java.io.*; public class CurrencyConverterGUI extends javax.swing.JFrame { /************************************************************************************************************** insert your code here - most of this will be generated by NetBeans, however, you must write code for the event listeners and handlers for the two ComboBoxes, the two TextBoxes, and the Button. Please note you must also poulate the ComboBoxes withe currency symbols (which are contained in the KeyList attribute of CurrencyConverter CC) ***************************************************************************************************************/ private CurrencyConverter CC; private javax.swing.JTextField Currency1Field; private javax.swing.JComboBox Currency1List; private javax.swing.JTextField Currency2Field; private javax.swing.JComboBox Currency2List; private javax.swing.JButton jButton1; private javax.swing.JPanel jPanel1; } class CurrencyConverter{ private HashMap HM; // contains the Currency symbols and conversion rates private ArrayList KeyList; // contains the list of currency symbols public CurrencyConverter() { /************************************************** Instantiate HM and KeyList and load data into them. Do this by reading the data from the Rates.txt file ***************************************************/ } public double convert(String FromCurrency, String ToCurrency, double amount){ /*************************************************************************** Will return the converted currency value. For example, to convert 100 USD to GBP, FromCurrency is USD, ToCurrency is GBP and amount is 100. The rate specified in the file represent the amount of each currency which is equivalent to one Euro (EUR). Therefore, 1 Euro is equivalent to 1.35 USD Use the rate specified for USD to convert to equivalent GBP: amount / USD_rate * GBP_rate ****************************************************************************/ } public ArrayList getKeys(){ // return KeyList } } This is what we were given, but I can't do anything with it inside the GUI editor. (Can't even get to the GUI editor). I have been staring at this for about an hour. Any ideas?

    Read the article

  • ObjectOutputStream .writeObject

    - by bigbluedragon
    hey i have some problems with this code... This is a JDialogForm in which I have jTextField and button. I want to save data from this Jtextfield when i click button to use it in another window but i don't know why it doesn't work. I always get Exception ek and the message i have put there. private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { String sciezka = jTextField1.getText(); if (sciezka.length() > 0) { Zmienne_pomocnicze zp = new Zmienne_pomocnicze(); zp.setPrzechowaj(sciezka); try { ObjectOutputStream oos = new ObjectOutputStream (new FileOutputStream("danebaza")); oos.writeObject(zp); oos.close(); } catch(Exception ek) { JOptionPane.showMessageDialog(null, "Nie mozna pobrac nazwy_przedmiotu: " + ek); } } this.setVisible(false); } where class Zmienne_pomocnicze looks like this public class Zmienne_pomocnicze { public String n; public void setPrzechowaj (String neew){ n = neew; } public String getPrzechowaj () { return n; } } i guess the problem is with oos.writeObject(zp); but i don't know why.

    Read the article

  • Java: Help constructing a fillTextFields() method

    - by Holly
    I have a Java project where I am to connect to a database and create buttons (next, new, save, delete, previous) to navigate through the database content where there are appropriate text fields and labels for the specific information. I'll use the code below as an example (each button is set up very similar)... I have it as follows: JButton jbtnNext = new JButton("Next ->"); jbtnNext.addActionListener(this); if (e.getSource() == jbtnNext) jbtnNext_Click(); private void jbtnNext_Click() { JOptionPane.showMessageDialog(null, "Next" ,"Button Pressed", JOptionPane.INFORMATION_MESSAGE); try { if (rset.next()) { fillTextFields(true); }else{ //Display result in a dialog box JOptionPane.showMessageDialog(null, "Not found"); } } catch (SQLException ex) { ex.printStackTrace(); } } The professor gave the following outline of logic to construct the fillTextFields() method: Construct the method to provide reusable code that would fill the JTextFields on the GUI with appropriate values from current record from the database (when "Previous or "Next" buttons are pressed) or blank values (when the new Button is pressed). To determine when the current record was to provide values (next and previous) or the value would be blank (new button) pass a boolean argument into the method. If data from the current record was to be used as fill values, pass true for both previous and next button code after moving the record pointer. If the new button was pressed and want to fill with blank values, pass false to the method. Inside the method, use a conditional expression to evaluate the boolean variable. If true, The appropriate get----() resultset method is used to fill the JTextFields. If false, fill them with "". The .setText() method of the JTextField is used to fill each JTextField. Make sure the fillTextFields method throws the appropriate exception. I understand and have the previous and next button methods passing true, while the new button method is passing false, but I don't quite understand how to set up the fillTextFields() method correctly or how to "throw the appropriate exception"... Any help would really be appreciated, thank you!

    Read the article

  • Relating text fields to check boxes in Java

    - by Finzz
    This program requires the user to login and request a database to access. The program then gets a connection object, searches through the database storing the column names into a vector for later use. The problem comes with implementing text fields to allow the user to search for specific values within the database. I can get the check boxes and text fields to appear using a gridlayout and add them to a panel. How do I relate the text fields to their appropriate check box? I've tried adding them to a vector, but then they can't also be added to the panel as well. I've searched for a way to name the text fields as the loop cycles through the column names, but it seems impossible to do without having them declared ahead of time. This can't be done either, as it's impossible to determine the attributes that the user will request. I just need to be able to know the names of the text fields so I can test to see if the user entered information and perform the necessary logic. Let me know if you have to see the rest of the code to give an answer, but hopefully you get the general idea of what I'm trying to accomplish. Picture of UI: try { ResultSet r2 = con.getMetaData().getColumns("", "", rb.getText(), ""); colNames1 = new Vector<String>(); columns1 = new Vector<JCheckBox>(); while (r2.next()) { colNames1.add(r2.getString(4)); JCheckBox cb = new JCheckBox(r2.getString(4)); JTextField tf = new JTextField(10); columns1.add(cb); p3.add(cb); p3.add(tf); } }

    Read the article

  • How do I use requestFocus in a Java JFrame GUI?

    - by JohnWong
    I am given an assignment but I am totally new to Java (I have been programming in C++ and Python for two years). So we are doing GUI and basically we extended JFrame and added a couple fields. Say we have a field named "Text 1" and "Text 2". When user presses enter with the cursor in Text 1, move the focus to Text 2. I tried to add private JTextField textfield1() { textfield1 = new JTextField(); textfield1.setPreferredSize(new Dimension(200, 20)); textfield1.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { textfield1text = textfield1.getText().trim(); textfield1.setText(textfield1text); System.out.println(textfield1text); textfield1.requestFocus(); } }); return textfield1; } But that doesn't work at all. I noticed that requestFocus is not recommended, and instead one should use requestFocusWindows. But I tried that too. Upon some readings it seems like I have to do keyboard action and listener? But my teacher said it only requires 1 line...

    Read the article

< Previous Page | 1 2 3 4 5  | Next Page >