Help with JLabels and JTextFields

I'm experimenting with JLabels and JTextFields in a basic JFrame. What I am trying to accomplish (without success) is to align a JLabel above and centered on a JTextField. The tutorials are confusing me. Any help would be greatly appreciated. a Sample of code is ...
JLabel  myTextLabel = new JLabel("Who's text Field?");
JTextField myTextField = new JTextField("My Text Field");...after reading the tutorial I thought that I needed to assign L&F variables to the JLabel ... i.e.
JLabel myTextLabel = new JLabel("Who's text field?:", JLabel.CENTER, JLabel.TOP); but this results in an error when compiling. (cannot find symbol), so I thought I need to assign the JLabel to the JTextField. i.e.
myTextLabel.setLabelFor(myTextField);Then I get "identifier" expected. So now being completely confused I am here asking "How do I?" :)
Thanks in advance!

Most likely, you need to think a little more about using a layout manager to hlp you along the way. If memory serves, the default layout manager for a JPanel is FlowLayout and that will simply place the components you add to the panel one after another and allow each to adopt it's preferred size.
One way to ensure that the two compoenets were sized equally, would be to use the GridLayout layout manager and create either one row with two columns, or two rows with one column on each. Then add the compoennets to each of the 'cells' so to speak and that should ensure that they are both the same size.
As to making the text centered in each, both the JLabel and JtextField classes have amethod called setHorizontalAlignment(); it can be used to aligh the text as you require.
Simply create an instance of the class;
JLabel aLabel = new JLabel("Some Text");
// Then set the alignment
aLabel.setHorizontalAlignment(SwingConstants.CENTER);Or, do the whole operation i one step
JLabel aLabel = new JLabel("Sone Text", SwingConstants.CENTER);and then add the componenet to the panel once you have set the layout manager.
Remember that the label.textfield will have to be wide enought to make it obvious that the text is centered!

Similar Messages

  • Problem with PropertyChangeListener and JTextField

    I'm having a problem with PropertyChangeListener and JTextField.
    I can not seem to get the propertychange event to fire.
    Anyone have any idea why the code below doesn't work?
    * NewJFrame.java
    * Created on May 15, 2005, 4:21 PM
    import java.beans.*;
    import javax.swing.*;
    * @author wolfgray
    public class NewJFrame extends javax.swing.JFrame
    implements PropertyChangeListener {
    /** Creates new form NewJFrame */
    public NewJFrame() {
    initComponents();
    jTextField1.addPropertyChangeListener( this );
    public void propertyChange(PropertyChangeEvent e) {
    System.out.println(e);
    /** This method is called from within the constructor to
    * initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is
    * always regenerated by the Form Editor.
    private void initComponents() {
    jTextField1 = new javax.swing.JTextField();
    jScrollPane1 = new javax.swing.JScrollPane();
    jFormattedTextField1 = new javax.swing.JFormattedTextField();
    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    jTextField1.setText("jTextField1");
    getContentPane().add(jTextField1, java.awt.BorderLayout.NORTH);
    jFormattedTextField1.setText("jFormattedTextField1");
    jScrollPane1.setViewportView(jFormattedTextField1);
    getContentPane().add(jScrollPane1, java.awt.BorderLayout.CENTER);
    pack();
    * @param args the command line arguments
    public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
    new NewJFrame().setVisible(true);
    // Variables declaration - do not modify
    private javax.swing.JFormattedTextField jFormattedTextField1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration
    }

    If you want to listen to changes in the textfield's contents you should use a DocumentListener and not a PropertyChangeListener:
    http://java.sun.com/docs/books/tutorial/uiswing/events/documentlistener.html
    And please use [co[/i]de]  tags when you are posting code (press the code button above the message window).

  • Help with writing and retrieving data from a table field with type "LCHR"

    Hi Experts,
    I need help with writing and reading data from a database table field which has a type of "LCHR". I have given an example of the original code but don't know what to change it to in order to fix it and still read in the original data that's stored in the LCHR field.
    Basically we have two Function modules, one that saves list data to a database table and one that reads in this data. Both Function modules have an identicle table which has an array of fields from type INT4, CHAR, and type P. The INT4 field is the first one.
    Incidentally this worked in the 4.7 non-unicode system but is now dumping in the new ECC6 Unicode system.
    Thanks in advance,
    C
    SAVING THE LIST DATA TO DB
    DATA: L_WA(800).
    LOOP AT T_TAB into L_WA.
    ZDBTAB-DATALEN = STRLEN( L_WA ).
    MOVE: L_WA to ZDBTAB-RAWDATA.
    ZDBTAB-LINENUM = SY-TABIX.
    INSERT ZDBTAB.
    READING THE DATA FROM DB
    DATA: BEGIN OF T_DATA,
                 SEQNR type ZDBTAB-LINENUM,
                 DATA type ZDBTAB-RAWDATA,
               END OF T_TAB.
    Select the data.
    SELECT linenum rawdata from ZDBTAB into table T_DATA
         WHERE repid = w_repname
         AND rundate = w_rundate
         ORDER BY linenum.
    Populate calling Internal Table.
    LOOP AT T-DATA.
    APPEND T_DATA to T_TAB.
    ENDLOOP.

    Hi Anuj,
    The unicode flag is active.
    When I run our report and then to try and save the list data a dump is happening at the following point
    LOOP AT T_TAB into L_WA.
    As I say, T_TAB consists of different fields and field types whereas L_WA is CHAR 800. The dump mentions UC_OBJECTS_NOT_CONVERTIBLE
    When I try to load a saved list the dump is happening at the following point
    APPEND T_DATA-RAWDATA to T_TAB.
    T_DATA-RAWDATA is type LCHR and T_TAB consists of different fields and field types.
    In both examples the dumps mention UC_OBJECTS_NOT_CONVERTIBLE
    Regards
    C

  • Layout of JLabels and JTextFields

    Hi!
    I am looking for an easy way to layout JLabels and JTextFields side by side like this:
    jlabel             jtextField
    small jlabel       jtextField
    longer jlabel      jtextFieldAny ideas on how to do this?
    Peter

    Read this section from the Swing tutorial on "Using Layout Managers":
    http://java.sun.com/docs/books/tutorial/uiswing/layout/using.html
    The easiest way is to use a GridLayout.
    JPanel panel = new JPanel();
    panel.setLayout( new GridLayout(0, 2) );
    panel.add( new JLabel("...") );
    panel.add( new JTextField(10) );
    panel.add( new JLabel("...") );
    panel.add( new JTextField(10) );
    A more complicated, but more flexible way is to use a GridBagLayout. Something like this:
    public class ActivityPanel extends JPanel
         public ActivityPanel()
              setBorder( new EmptyBorder(5, 5, 5, 5) );
              setLayout( new GridBagLayout() );
              GridBagConstraints gbc = new GridBagConstraints();
              gbc.insets = new Insets(5, 10, 5, 10);
              // add street
              JLabel lStreet = new JLabel("Street");
              JTextField cStreet = new JTextField(32);
              addRow(gbc, lStreet, cStreet);
              // add city
              JLabel lCity = new JLabel("City");
              JTextField cCity = new JTextField(32);
              addRow(gbc, lCity, cCity);
         private void addRow(GridBagConstraints gbc, Component left, Component right)
              gbc.gridx = GridBagConstraints.RELATIVE;
              gbc.gridy = GridBagConstraints.RELATIVE;
              gbc.gridheight = 1;
              gbc.gridwidth = 1;
              gbc.anchor = GridBagConstraints.EAST;
              add(left, gbc);
              gbc.gridwidth = GridBagConstraints.REMAINDER;
              gbc.anchor = GridBagConstraints.WEST;
              add(right, gbc);
    }

  • Align JLabels and JTextFields vertically in different areas

    I like to have 3 TitledBorders for 3 different areas of my frame.
    Each area has its own components - JLabels, JTextField, etc.
    How to align JLabels and JTextFields vertically in different areas?
    e.g. for the following test program, how to configure label1, label2, label3 so that their right sides all align vertically and
    tf1, tf2, tf3 so that their left sides all align vertically?
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.GridLayout;
    import java.awt.Insets;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    import javax.swing.border.TitledBorder;
    public class TitledBorderDemo extends JFrame {
      public TitledBorderDemo() {
        super("TitledBorderDemo");
        JTextField tf1 = new JTextField("hello", 6);
        JTextField tf2 = new JTextField("hello", 12);
        JTextField tf3 = new JTextField("test");
        JTextField tf4 = new JTextField("test2");
        JLabel label1 = new JLabel("1234567890ertyuiyup label");
        JLabel label2 = new JLabel("zzzzzzzzzzzzzzzzzzzzzzzzzzzzzz long label");
        JLabel label3 = new JLabel("short label");
        JLabel label4 = new JLabel("test");
        JPanel panel_tf = new JPanel(new GridBagLayout());
        JPanel panel_pf = new JPanel(new GridBagLayout());
        JPanel panel_ftf = new JPanel(new GridBagLayout());
        GridBagConstraints constraints = new GridBagConstraints(0, 0, 3, 3,
                0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE,
                new Insets(10, 10, 10, 10), 0, 0);
        constraints.gridx = 0;
        constraints.gridy = 0;
        constraints.gridwidth = 2;
        constraints.anchor = GridBagConstraints.WEST;
        panel_tf.add(label1, constraints);
        constraints.gridx = 2;
        constraints.gridwidth = 1;
        constraints.anchor = GridBagConstraints.EAST;
        panel_tf.add(tf1, constraints);
        constraints.gridx = 0;
        constraints.gridy = 1;
        constraints.gridwidth = 2;
        constraints.anchor = GridBagConstraints.WEST;
        panel_pf.add(label2, constraints);
        constraints.gridx = 2;
        constraints.gridwidth = 1;
        constraints.anchor = GridBagConstraints.EAST;
        panel_pf.add(tf2, constraints);
        constraints.gridx = 0;
        constraints.gridy = 2;
        constraints.gridwidth = 2;
        constraints.anchor = GridBagConstraints.WEST;
        panel_ftf.add(label3, constraints);
        constraints.gridx = 2;
        constraints.gridwidth = 1;
        constraints.anchor = GridBagConstraints.EAST;
        panel_ftf.add(tf3, constraints);
        constraints.gridx = 3;
        constraints.gridwidth = 1;
        constraints.anchor = GridBagConstraints.WEST;
        panel_ftf.add(label4, constraints);
        constraints.gridx = 4;
        constraints.anchor = GridBagConstraints.EAST;
        panel_ftf.add(tf4, constraints);
        panel_tf.setBorder(new TitledBorder("JTextField1"));
        panel_pf.setBorder(new TitledBorder("JTextField2"));
        panel_ftf.setBorder(new TitledBorder("JTextField3"));
        JPanel pan = new JPanel(new GridLayout(3, 1, 10, 10));
        pan.add(panel_tf);
        pan.add(panel_pf);
        pan.add(panel_ftf);
        this.add(pan);
      public static void main(String args[]) {
        JFrame frame = new TitledBorderDemo();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(600, 450);
        frame.setVisible(true);
    }

    Thank you! It works!
    I add some labels & components to your demo program.
    Most of the components align vertically.
    How to align the "Country", "Test2" & "Extension" labels on the right sides?
    How to align their corresponding components so that their left sides all align vertically?
    How to make the Cancel button stick to the Save button
    (i.e. eliminate the gap between the Cancel and the Save button)?
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.border.*;
    public class TitledBorderDemoNew extends JFrame {
      public TitledBorderDemoNew() {
        super("TitledBorderDemoNew");
        JLabel nameLabel = new JLabel("Name");
        JTextField nameText = new JTextField(20);
        JLabel addressLabel = new JLabel("Address (City & State)");
        JTextField addressText = new JTextField(40);
        JLabel countryLabel = new JLabel("Country");
        JTextField countryText = new JTextField(30);
        JLabel testLabel = new JLabel("Test");
        JTextField testText = new JTextField(20);   
        JLabel test2Label = new JLabel("Test2");
        JTextField test2Text = new JTextField(20);   
        JLabel phoneLabel = new JLabel("Phone");
        JTextField phoneText = new JTextField(20);
        JLabel extensionLabel = new JLabel("Extension");
        JTextField extensionText = new JTextField(5);
        JLabel postalCodeLabel = new JLabel("Postal Code");
        JTextField postalCodeText = new JTextField(6);
        JButton saveButton = new JButton("Save");
        JButton cancelButton = new JButton("Cancel");
        JButton commentButton = new JButton("Comment");
        int longWidth = addressLabel.getPreferredSize().width;
        GridBagConstraints constraints = new GridBagConstraints();
        JPanel p1 = new JPanel(new GridBagLayout());
        p1.setBorder(createBorder("Name"));
        constraints.gridx = 0;
        constraints.gridy = 0;
        constraints.anchor = GridBagConstraints.EAST;
        constraints.insets = new Insets(4,6,4,6);
        p1.add(nameLabel, constraints);
        constraints.gridx = 1;
        constraints.anchor = GridBagConstraints.WEST;
        p1.add(nameText, constraints);
        constraints.gridx = 2;
        constraints.anchor = GridBagConstraints.WEST;
        constraints.fill = GridBagConstraints.HORIZONTAL;
        constraints.weightx = 1.0;
        p1.add(Box.createHorizontalGlue(), constraints);
        constraints.gridx = 0;
        constraints.gridy = 1;
        constraints.fill = GridBagConstraints.NONE;
        constraints.weightx = 0.0;
        p1.add(Box.createHorizontalStrut(longWidth), constraints);
        JPanel p2 = new JPanel(new GridBagLayout());
        p2.setBorder(createBorder("Address"));
        constraints.gridx = 0;
        constraints.gridy = 0;
        constraints.anchor = GridBagConstraints.EAST;
        constraints.insets = new Insets(4,6,4,6);
        p2.add(addressLabel, constraints);
        constraints.gridx = 1;
        constraints.anchor = GridBagConstraints.WEST;
        p2.add(addressText, constraints);
        // extra label & component
        constraints.gridx = 2;
        constraints.anchor = GridBagConstraints.EAST;
        constraints.insets = new Insets(4,36,4,6);
        p2.add(countryLabel, constraints);
        constraints.gridx = 3;
        constraints.anchor = GridBagConstraints.WEST;
        constraints.insets = new Insets(4,6,4,6);
        p2.add(countryText, constraints);
        constraints.gridx = 0;
        constraints.gridy = 1;
        constraints.anchor = GridBagConstraints.EAST;
        constraints.insets = new Insets(4,6,4,6);
        p2.add(testLabel, constraints);
        constraints.gridx = 1;
        constraints.anchor = GridBagConstraints.WEST;
        p2.add(testText, constraints);
        // extra label & component
        constraints.gridx = 2;
        constraints.anchor = GridBagConstraints.EAST;
        constraints.insets = new Insets(4,36,4,6);
        p2.add(test2Label, constraints);
        constraints.gridx = 3;
        constraints.anchor = GridBagConstraints.WEST;
        constraints.insets = new Insets(4,6,4,6);
        p2.add(test2Text, constraints);
        constraints.gridx = 4;
        constraints.anchor = GridBagConstraints.WEST;
        constraints.fill = GridBagConstraints.HORIZONTAL;
        constraints.weightx = 1.0;
        p2.add(Box.createHorizontalGlue(), constraints);
        constraints.gridx = 0;
        constraints.gridy = 2;
        constraints.fill = GridBagConstraints.NONE;
        constraints.weightx = 0.0;
        p2.add(Box.createHorizontalStrut(longWidth), constraints);
        JPanel p3 = new JPanel(new GridBagLayout());
        p3.setBorder(createBorder("Phone"));
        constraints.gridx = 0;
        constraints.gridy = 0;
        constraints.anchor = GridBagConstraints.EAST;
        constraints.insets = new Insets(4,6,4,6);
        p3.add(phoneLabel, constraints);
        constraints.gridx = 1;
        constraints.anchor = GridBagConstraints.WEST;
        p3.add(phoneText, constraints);
        constraints.gridx = 2;
        constraints.anchor = GridBagConstraints.EAST;
        constraints.insets = new Insets(4,6,4,6);
        p3.add(extensionLabel, constraints);
        constraints.gridx = 3;
        constraints.anchor = GridBagConstraints.WEST;
        p3.add(extensionText, constraints);
        constraints.gridx = 2;
        constraints.anchor = GridBagConstraints.WEST;
        constraints.fill = GridBagConstraints.HORIZONTAL;
        constraints.weightx = 1.0;
        p3.add(Box.createHorizontalGlue(), constraints);
        constraints.gridx = 0;
        constraints.gridy = 1;
        constraints.fill = GridBagConstraints.NONE;
        constraints.weightx = 0.0;
        p3.add(Box.createHorizontalStrut(longWidth), constraints);
        JPanel p4 = new JPanel(new GridBagLayout());
        p4.setBorder(createBorder("Postal Code"));
        constraints.gridx = 0;
        constraints.gridy = 0;
        constraints.anchor = GridBagConstraints.EAST;
        constraints.insets = new Insets(4,6,4,6);
        p4.add(postalCodeLabel, constraints);
        constraints.gridx = 1;
        constraints.anchor = GridBagConstraints.WEST;
        p4.add(postalCodeText, constraints);
        constraints.gridx = 2;
        constraints.anchor = GridBagConstraints.WEST;
        constraints.fill = GridBagConstraints.HORIZONTAL;
        constraints.weightx = 1.0;
        p4.add(Box.createHorizontalGlue(), constraints);
        constraints.gridx = 0;
        constraints.gridy = 1;
        constraints.fill = GridBagConstraints.NONE;
        constraints.weightx = 0.0;
        p4.add(Box.createHorizontalStrut(longWidth), constraints);
        JPanel p5 = new JPanel(new GridBagLayout());
        constraints.gridx = 0;
        constraints.gridy = 0;
        constraints.anchor = GridBagConstraints.WEST;
        constraints.insets = new Insets(4,6,4,6);
        p5.add(commentButton, constraints);
        constraints.gridx = 1;
        constraints.anchor = GridBagConstraints.WEST;
        constraints.fill = GridBagConstraints.HORIZONTAL;
        constraints.weightx = 1.0;
        p5.add(Box.createHorizontalGlue(), constraints);
        constraints.gridx = 2;
        constraints.gridwidth = GridBagConstraints.RELATIVE;
        constraints.fill = GridBagConstraints.NONE;
        constraints.anchor = GridBagConstraints.EAST;
        p5.add(cancelButton, constraints);
        constraints.gridx = 3;
        constraints.gridwidth = GridBagConstraints.REMAINDER;
        constraints.anchor = GridBagConstraints.EAST;
        p5.add(saveButton, constraints);
        JPanel panel = new JPanel(new GridBagLayout());
        constraints.gridx = 0;
        constraints.gridy = 0;
        constraints.fill = GridBagConstraints.HORIZONTAL;
        constraints.weightx = 1.0;
        panel.add(p1, constraints);
        constraints.gridy = 1;
        panel.add(p2, constraints);
        constraints.gridy = 2;
        panel.add(p3, constraints);
        constraints.gridy = 3;
        panel.add(p4, constraints);
        constraints.gridy = 4;
        panel.add(p5, constraints);
        this.add(new JScrollPane(panel));
      private Border createBorder(String title)
        TitledBorder b = new TitledBorder(title);
        b.setTitleColor(Color.RED.darker());
        return b;
      public static void main(String args[]) {
        JFrame frame = new TitledBorderDemoNew();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }Edited by: 833768 on 26-Apr-2011 10:32 AM

  • Help with count and sum query

    Hi I am using oracle 10g. Trying to aggregate duplicate count records. I have so far:
    SELECT 'ST' LEDGER,
    CASE
    WHEN c.Category = 'E' THEN 'Headcount Exempt'
    ELSE 'Headcount Non-Exempt'
    END
    ACCOUNTS,
    CASE WHEN a.COMPANY = 'ZEE' THEN 'OH' ELSE 'NA' END MARKET,
    'MARCH_12' AS PERIOD,
    COUNT (a.empl_id) head_count
    FROM essbase.employee_pubinfo a
    LEFT OUTER JOIN MMS_DIST_COPY b
    ON a.cost_ctr = TRIM (b.bu)
    INNER JOIN MMS_GL_PAY_GROUPS c
    ON a.pay_group = c.group_code
    WHERE a.employee_status IN ('A', 'L', 'P', 'S')
    AND FISCAL_YEAR = '2012'
    AND FISCAL_MONTH = 'MARCH'
    GROUP BY a.company,
    b.district,
    a.cost_ctr,
    c.category,
    a.fiscal_month,
    a.fiscal_year;
    which gives me same rows with different head_counts. I am trying to combine the same rows as a total (one record). Do I use a subquery?

    Hi,
    Whenever you have a problem, please post a little sample data (CREATE TABLE and INSERT statements, relevant columns only) from all tables involved.
    Also post the results you want from that data, and an explanation of how you get those results from that data, with specific examples.
    user610131 wrote:
    ... which gives me same rows with different head_counts.If they have different head_counts, then the rows are not the same.
    I am trying to combine the same rows as a total (one record). Do I use a subquery?Maybe. It's more likely that you need a different GROUP BY clause, since the GROUP BY clause determines how many rows of output there will be. I'll be able to say more after you post the sample data, results, and explanation.
    You may want both a sub-query and a different GROUP BY clause. For example:
    WITH    got_group_by_columns     AS
         SELECT  a.empl_id
         ,     CASE
                        WHEN  c.category = 'E'
                  THEN  'Headcount Exempt'
                        ELSE  'Headcount Non-Exempt'
                END          AS accounts
         ,       CASE
                        WHEN a.company = 'ZEE'
                        THEN 'OH'
                        ELSE 'NA'
                END          AS market
         FROM              essbase.employee_pubinfo a
         LEFT OUTER JOIN  mms_dist_copy             b  ON   a.cost_ctr     = TRIM (b.bu)
         INNER JOIN       mms_gl_pay_groups        c  ON   a.pay_group      = c.group_code
         WHERE     a.employee_status     IN ('A', 'L', 'P', 'S')
         AND        fiscal_year           = '2012'
         AND        fiscal_month          = 'MARCH'
    SELECT    'ST'               AS ledger
    ,       accounts
    ,       market
    ,       'MARCH_12'          AS period
    ,       COUNT (empl_id)       AS head_count
    FROM       got_group_by_columns
    GROUP BY  accounts
    ,            market
    ;But that's just a wild guess.
    You said you wanted "Help with count and sum". I see the COUNT, but what do you want with SUM? No doubt this will be clearer after you post the sample data and results.
    Edited by: Frank Kulash on Apr 4, 2012 5:31 PM

  • MOVED: [Athlon64] Need Help with X64 and Promise 20378

    This topic has been moved to Operating Systems.
    [Athlon64] Need Help with X64 and Promise 20378

    I'm moving this the the Administration Forum.  It seems more apporpiate there.

  • Need help with JTextArea and Scrolling

    import java.awt.*;
    import java.awt.event.*;
    import java.text.DecimalFormat;
    import javax.swing.*;
    public class MORT_RETRY extends JFrame implements ActionListener
    private JPanel keypad;
    private JPanel buttons;
    private JTextField lcdLoanAmt;
    private JTextField lcdInterestRate;
    private JTextField lcdTerm;
    private JTextField lcdMonthlyPmt;
    private JTextArea displayArea;
    private JButton CalculateBtn;
    private JButton ClrBtn;
    private JButton CloseBtn;
    private JButton Amortize;
    private JScrollPane scroll;
    private DecimalFormat calcPattern = new DecimalFormat("$###,###.00");
    private String[] rateTerm = {"", "7years @ 5.35%", "15years @ 5.5%", "30years @ 5.75%"};
    private JComboBox rateTermList;
    double interest[] = {5.35, 5.5, 5.75};
    int term[] = {7, 15, 30};
    double balance, interestAmt, monthlyInterest, monthlyPayment, monPmtInt, monPmtPrin;
    int termInMonths, month, termLoop, monthLoop;
    public MORT_RETRY()
    Container pane = getContentPane();
    lcdLoanAmt = new JTextField();
    lcdMonthlyPmt = new JTextField();
    displayArea = new JTextArea();//DEFINE COMBOBOX AND SCROLL
    rateTermList = new JComboBox(rateTerm);
    scroll = new JScrollPane(displayArea);
    scroll.setSize(600,170);
    scroll.setLocation(150,270);//DEFINE BUTTONS
    CalculateBtn = new JButton("Calculate");
    ClrBtn = new JButton("Clear Fields");
    CloseBtn = new JButton("Close");
    Amortize = new JButton("Amortize");//DEFINE PANEL(S)
    keypad = new JPanel();
    buttons = new JPanel();//DEFINE KEYPAD PANEL LAYOUT
    keypad.setLayout(new GridLayout( 4, 2, 5, 5));//SET CONTROLS ON KEYPAD PANEL
    keypad.add(new JLabel("Loan Amount$ : "));
    keypad.add(lcdLoanAmt);
    keypad.add(new JLabel("Term of loan and Interest Rate: "));
    keypad.add(rateTermList);
    keypad.add(new JLabel("Monthly Payment : "));
    keypad.add(lcdMonthlyPmt);
    lcdMonthlyPmt.setEditable(false);
    keypad.add(new JLabel("Amortize Table:"));
    keypad.add(displayArea);
    displayArea.setEditable(false);//DEFINE BUTTONS PANEL LAYOUT
    buttons.setLayout(new GridLayout( 1, 3, 5, 5));//SET CONTROLS ON BUTTONS PANEL
    buttons.add(CalculateBtn);
    buttons.add(Amortize);
    buttons.add(ClrBtn);
    buttons.add(CloseBtn);//ADD ACTION LISTENER
    CalculateBtn.addActionListener(this);
    ClrBtn.addActionListener(this);
    CloseBtn.addActionListener(this);
    Amortize.addActionListener(this);
    rateTermList.addActionListener(this);//ADD PANELS
    pane.add(keypad, BorderLayout.NORTH);
    pane.add(buttons, BorderLayout.SOUTH);
    pane.add(scroll, BorderLayout.CENTER);
    addWindowListener( new WindowAdapter()
    public void windowClosing(WindowEvent e)
    System.exit(0);
    public void actionPerformed(ActionEvent e)
    String arg = lcdLoanAmt.getText();
    int combined = Integer.parseInt(arg);
    if (e.getSource() == CalculateBtn)
    try
    JOptionPane.showMessageDialog(null, "Got try here", "Error", JOptionPane.ERROR_MESSAGE);
    catch(NumberFormatException ev)
    JOptionPane.showMessageDialog(null, "Got here", "Error", JOptionPane.ERROR_MESSAGE);
    if ((e.getSource() == CalculateBtn) && (arg != null))
    try{
    if ((e.getSource() == CalculateBtn) && (rateTermList.getSelectedIndex() == 1))
    monthlyInterest = interest[0] / (12 * 100);
    termInMonths = term[0] * 12;
    monthlyPayment = combined * (monthlyInterest / (1 - (Math.pow (1 + monthlyInterest,  -termInMonths))));
    lcdMonthlyPmt.setText(calcPattern.format(monthlyPayment));
    if ((e.getSource() == CalculateBtn) && (rateTermList.getSelectedIndex() == 2))
    monthlyInterest = interest[1] / (12 * 100);
    termInMonths = term[1] * 12;
    monthlyPayment = combined * (monthlyInterest / (1 - (Math.pow (1 + monthlyInterest,  -termInMonths))));
    lcdMonthlyPmt.setText(calcPattern.format(monthlyPayment));
    if ((e.getSource() == CalculateBtn) && (rateTermList.getSelectedIndex() == 3))
    monthlyInterest = interest[2] / (12 * 100);
    termInMonths = term[2] * 12;
    monthlyPayment = combined * (monthlyInterest / (1 - (Math.pow (1 + monthlyInterest,  -termInMonths))));
    lcdMonthlyPmt.setText(calcPattern.format(monthlyPayment));
    catch(NumberFormatException ev)
    JOptionPane.showMessageDialog(null, "Invalid Entry!\nPlease Try Again", "Error", JOptionPane.ERROR_MESSAGE);
    }                    //IF STATEMENTS FOR AMORTIZATION
    if ((e.getSource() == Amortize) && (rateTermList.getSelectedIndex() == 1))
    loopy(7, 5.35);
    if ((e.getSource() == Amortize) && (rateTermList.getSelectedIndex() == 2))
    loopy(15, 5.5);
    if ((e.getSource() == Amortize) && (rateTermList.getSelectedIndex() == 3))
    loopy(30, 5.75);
    if (e.getSource() == ClrBtn)
    rateTermList.setSelectedIndex(0);
    lcdLoanAmt.setText(null);
    lcdMonthlyPmt.setText(null);
    displayArea.setText(null);
    if (e.getSource() == CloseBtn)
    System.exit(0);
    private void loopy(int lTerm,double lInterest)
    double total, monthly, monthlyrate, monthint, monthprin, balance, lastint, paid;
    int amount, months, termloop, monthloop;
    String lcd2 = lcdLoanAmt.getText();
    amount = Integer.parseInt(lcd2);
    termloop = 1;
    paid = 0.00;
    monthlyrate = lInterest / (12 * 100);
    months = lTerm * 12;
    monthly = amount *(monthlyrate/(1-Math.pow(1+monthlyrate,-months)));
    total = months * monthly;
    balance = amount;
    while (termloop <= lTerm)
    displayArea.setCaretPosition(0);
    displayArea.append("\n");
    displayArea.append("Year " + termloop + " of " + lTerm + ": payments\n");
    displayArea.append("\n");
    displayArea.append("Month\tMonthly\tPrinciple\tInterest\tBalance\n");
    monthloop = 1;
    while (monthloop <= 12)
    monthint = balance * monthlyrate;
    monthprin = monthly - monthint;
    balance -= monthprin;
    paid += monthly;
    displayArea.setCaretPosition(0);
    displayArea.append(monthloop + "\t" + calcPattern.format(monthly) + "\t" + calcPattern.format(monthprin) + "\t");
    displayArea.append(calcPattern.format(monthint) + "\t" + calcPattern.format(balance) + "\n");
    monthloop ++;
    termloop ++;
    public static void main(String args[])
    MORT_RETRY f = new MORT_RETRY();
    f.setTitle("MORTGAGE PAYMENT CALCULATOR");
    f.setBounds(600, 600, 500, 500);
    f.setLocationRelativeTo(null);
    f.setVisible(true);
    }need help with displaying the textarea correctly and the scroll bar please.
    Message was edited by:
    new2this2020

    What's the problem you're having ???
    PS.

  • Help with BufferedImage and JPanel

    I have a program that should display some curves, but thats not the problem, the real problem is when i copy the image contained in the JPanel to the buffered image then i draw something there and draw it back to the JPanel. My panel initialy its white but after the operation it gets gray
    Please if some one could help with this
    here is my code divided in three classes
    //class VentanaPrincipal
    package gui;
    import java.awt.BorderLayout;
    import java.awt.FlowLayout;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.Insets;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.image.BufferedImage;
    import javax.swing.BorderFactory;
    import javax.swing.JButton;
    import javax.swing.JLabel;
    import javax.swing.JSeparator;
    import javax.swing.border.LineBorder;
    import javax.swing.JMenuItem;
    import javax.swing.JPanel;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    * This code was edited or generated using CloudGarden's Jigloo
    * SWT/Swing GUI Builder, which is free for non-commercial
    * use. If Jigloo is being used commercially (ie, by a corporation,
    * company or business for any purpose whatever) then you
    * should purchase a license for each developer using Jigloo.
    * Please visit www.cloudgarden.com for details.
    * Use of Jigloo implies acceptance of these licensing terms.
    * A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
    * THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
    * LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
    public class VentanaPrincipal extends javax.swing.JFrame {
              //Set Look & Feel
              try {
                   javax.swing.UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
              } catch(Exception e) {
                   e.printStackTrace();
         private JMenuItem helpMenuItem;
         private JMenu jMenu5;
         private JMenuItem deleteMenuItem;
         private JSeparator jSeparator1;
         private JMenuItem pasteMenuItem;
         private JLabel jLabel4;
         private JLabel jLabel5;
         private JLabel jLabel3;
         private JLabel jLabel2;
         private JLabel jLabel1;
         private JButton jSPLineButton;
         private JButton jHermiteButton;
         private JButton jBezierButton;
         private JPanel jPanel2;
         private JPanel jPanel1;
         private JMenuItem jResetMenuItem1;
         private JMenuItem copyMenuItem;
         private JMenuItem cutMenuItem;
         private JMenu jMenu4;
         private JMenuItem exitMenuItem;
         private JSeparator jSeparator2;
         private JMenu jMenu3;
         private JMenuBar jMenuBar1;
          * Variables no autogeneradas
         private int botonSeleccionado;
         * Auto-generated main method to display this JFrame
         public static void main(String[] args) {
              VentanaPrincipal inst = new VentanaPrincipal();
              inst.setVisible(true);
         public VentanaPrincipal() {
              super();
              initGUI();
         private void initGUI() {
              try {
                        this.setTitle("Info3 TP 2");
                             jPanel1 = new pizarra();
                             getContentPane().add(jPanel1, BorderLayout.WEST);
                             jPanel1.setPreferredSize(new java.awt.Dimension(373, 340));
                             jPanel1.setMinimumSize(new java.awt.Dimension(10, 342));
                             jPanel1.setBackground(new java.awt.Color(0,0,255));
                             jPanel1.setBorder(BorderFactory.createCompoundBorder(
                                  new LineBorder(new java.awt.Color(0, 0, 0), 1, true),
                                  null));
                             BufferedImage bufimg = (BufferedImage)jPanel1.createImage(jPanel1.getWidth(), jPanel1.getHeight());
                             ((pizarra) jPanel1).setBufferedImage(bufimg);
                             jPanel2 = new JPanel();
                             getContentPane().add(jPanel2, BorderLayout.CENTER);
                             GridBagLayout jPanel2Layout = new GridBagLayout();
                             jPanel2Layout.rowWeights = new double[] {0.0, 0.0, 0.0, 0.0};
                             jPanel2Layout.rowHeights = new int[] {69, 74, 76, 71};
                             jPanel2Layout.columnWeights = new double[] {0.0, 0.0, 0.1};
                             jPanel2Layout.columnWidths = new int[] {83, 75, 7};
                             jPanel2.setLayout(jPanel2Layout);
                                  jBezierButton = new JButton();
                                  jPanel2.add(jBezierButton, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
                                  jBezierButton.setText("Bezier");
                                  jBezierButton.setFont(new java.awt.Font("Tahoma",0,10));
                                  jBezierButton.addActionListener(new ActionListener() {
                                       public void actionPerformed(ActionEvent evt) {
                                            bezierActionPerformed();
                                  jHermiteButton = new JButton();
                                  jPanel2.add(jHermiteButton, new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
                                  jHermiteButton.setText("Hermite");
                                  jHermiteButton.setFont(new java.awt.Font("Tahoma",0,10));
                                  jSPLineButton = new JButton();
                                  jPanel2.add(jSPLineButton, new GridBagConstraints(1, 2, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
                                  jSPLineButton.setText("SP Line");
                                  jSPLineButton.setFont(new java.awt.Font("Tahoma",0,10));
                                  jLabel1 = new JLabel();
                                  jPanel2.add(jLabel1, new GridBagConstraints(0, 3, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
                                  jLabel1.setText("Posicion Mouse");
                                  jLabel2 = new JLabel();
                                  jPanel2.add(jLabel2, new GridBagConstraints(1, 3, 1, 1, 0.0, 0.0, GridBagConstraints.NORTH, GridBagConstraints.NONE, new Insets(12, 0, 0, 0), 0, 0));
                                  jLabel2.setText("X:");
                                  jLabel3 = new JLabel();
                                  jPanel2.add(jLabel3, new GridBagConstraints(1, 3, 1, 1, 0.0, 0.0, GridBagConstraints.SOUTH, GridBagConstraints.NONE, new Insets(0, 0, 12, 0), 0, 0));
                                  jLabel3.setText("Y:");
                                  jLabel4 = new JLabel();
                                  jPanel2.add(jLabel4, new GridBagConstraints(2, 3, 1, 1, 0.0, 0.0, GridBagConstraints.NORTH, GridBagConstraints.NONE, new Insets(12, 0, 0, 0), 0, 0));
                                  jLabel4.setText("-");
                                  jLabel5 = new JLabel();
                                  jPanel2.add(jLabel5, new GridBagConstraints(2, 3, 1, 1, 0.0, 0.0, GridBagConstraints.SOUTH, GridBagConstraints.NONE, new Insets(0, 0, 12, 0), 0, 0));
                                  jLabel5.setText("-");
                   this.setSize(600, 400);
                        jMenuBar1 = new JMenuBar();
                        setJMenuBar(jMenuBar1);
                             jMenu3 = new JMenu();
                             jMenuBar1.add(jMenu3);
                             jMenu3.setText("Archivo");
                                  jSeparator2 = new JSeparator();
                                  jMenu3.add(jSeparator2);
                                  exitMenuItem = new JMenuItem();
                                  jMenu3.add(exitMenuItem);
                                  exitMenuItem.setText("Exit");
                                  jResetMenuItem1 = new JMenuItem();
                                  jMenu3.add(jResetMenuItem1);
                                  jResetMenuItem1.setText("Reset");
                             jMenu4 = new JMenu();
                             jMenuBar1.add(jMenu4);
                             jMenu4.setText("Edit");
                                  cutMenuItem = new JMenuItem();
                                  jMenu4.add(cutMenuItem);
                                  cutMenuItem.setText("Cut");
                                  copyMenuItem = new JMenuItem();
                                  jMenu4.add(copyMenuItem);
                                  copyMenuItem.setText("Copy");
                                  pasteMenuItem = new JMenuItem();
                                  jMenu4.add(pasteMenuItem);
                                  pasteMenuItem.setText("Paste");
                                  jSeparator1 = new JSeparator();
                                  jMenu4.add(jSeparator1);
                                  deleteMenuItem = new JMenuItem();
                                  jMenu4.add(deleteMenuItem);
                                  deleteMenuItem.setText("Delete");
                             jMenu5 = new JMenu();
                             jMenuBar1.add(jMenu5);
                             jMenu5.setText("Help");
                                  helpMenuItem = new JMenuItem();
                                  jMenu5.add(helpMenuItem);
                                  helpMenuItem.setText("Help");
              } catch (Exception e) {
                   e.printStackTrace();
         private void bezierActionPerformed(){
              botonSeleccionado = 1;
              ((pizarra) jPanel1).setTipoFigura(botonSeleccionado);
              ((pizarra) jPanel1).pintarGrafico();
    //class graphUtils
    package func;
    import java.awt.Image;
    import java.awt.Point;
    import java.awt.image.BufferedImage;
    public class graphUtils {
         public static void dibujarPixel(BufferedImage img, int x, int y, int color){
              img.setRGB(x, y, color);
         public static void dibujarLinea(BufferedImage img, int x0, int y0, int x1, int y1, int color){
            int dx = x1 - x0;
            int dy = y1 - y0;
            if (Math.abs(dx) > Math.abs(dy)) {          // Pendiente m < 1
                float m = (float) dy / (float) dx;     
                float b = y0 - m*x0;
                if(dx < 0) dx = -1; else dx = 1;
                while (x0 != x1) {
                    x0 += dx;
                    dibujarPixel(img, x0, Math.round(m*x0 + b), color);
            } else
            if (dy != 0) {                              // Pendiente m >= 1
                float m = (float) dx / (float) dy;
                float b = x0 - m*y0;
                if(dy < 0) dy = -1; else dy = 1;
                while (y0 != y1) {
                    y0 += dy;
                    dibujarPixel(img, Math.round(m*y0 + b), y0, color);
         public static void dibujarBezier(BufferedImage img, Point puntos, int color){
    //class pizarra
    package gui;
    import javax.swing.*;
    import sun.awt.VerticalBagLayout;
    import sun.security.krb5.internal.bh;
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Image;
    import java.awt.Point;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.awt.image.BufferedImage;
    import java.util.ArrayList;
    import func.graphUtils;
    * esta clase pizarra extiende la clase JPanel y se agregan las funciones de pintado
    * y rellenado que se muestra en pantalla dentro del panel que se crea con esta clase
    * @author victorg
    public class pizarra extends JPanel implements MouseListener{
         private int tipoFigura;
         BufferedImage bufferImagen;
         Image img;
         Graphics img_gc;
         private Color colorRelleno, colorLinea;
         private Point puntosBezier[] = new Point[3];
         public pizarra(){
              super();          
              addMouseListener(this);
              //this.setBackground(Color.BLUE);
              colorLinea = Color.BLUE;
         public void setTipoFigura(int seleccion){
              // se setea para ver si es bezier, hermite, SP line
              tipoFigura = seleccion;
         public void setTipoRelleno(int seleccion){
         public void setColorRelleno(Color relleno){
              colorRelleno = relleno;          
         public void setColorLinea(Color linea){
              colorLinea = linea;
         public void setBufferedImage(BufferedImage bufimg){
              bufferImagen = bufimg;
         public void pintarGrafico(){
              Graphics g = this.getGraphics();     
              g.setColor(colorLinea);
              //accion ejecutada cuando se selecciona para graficar un poligono
              if(tipoFigura == 1){// bezier
                   if(bufferImagen == null){
                        //mantiene guardada la imagen cuando la pantalla pasa a segundo plano
                        bufferImagen = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB);
                        this.setBackground(Color.WHITE);                                                  
                        bufferImagen = (BufferedImage)createImage(getWidth(), getHeight());
                        //bufferImagen = this.createImage(getWidth(), getHeight());
                   //g.drawImage(bufferImagen,0,0,this);
                   graphUtils.dibujarLinea(bufferImagen,10, 10, 50, 50, colorLinea.getRGB());
                   g.drawImage(bufferImagen,0,0,this);
         protected void paintComponent(Graphics g) { // llamado al repintar
              //setBackground(colorFondo);
              super.paintComponent(g);
    //          Graphics2D g2 = (Graphics2D)g;          
    //          g2.drawImage(bufferImagen, 0,0, this);          
    //          g2.dispose();     
         public void mouseClicked(MouseEvent arg0) {          
         public void mousePressed(MouseEvent arg0) {
              // TODO Auto-generated method stub
         public void mouseReleased(MouseEvent arg0) {
              // TODO Auto-generated method stub
         public void mouseEntered(MouseEvent arg0) {
              // TODO Auto-generated method stub
         public void mouseExited(MouseEvent arg0) {
              // TODO Auto-generated method stub
    }

    1) Swing related questions should be posted in the Swing forum.
    Custom painting should be done in the paintComponent(..) method. You created a "pintarGraphico" method to do the custom painting, but that method is only execute once. When Java determines that the panel needs to be repainted, the paintComponent() method is executed which simply does a super.paintComponent(), which in turn simply paints the background of the panel overwriting you custom painting.

  • Help with JLabel

    Hello all. I am fairly new to Java and having a problem setting the text in a JLabel. I am trying to create a calculator program and when the user clicks a button I want that number to appear in a JLabel at the top. I used output.setText("7"); but when I compiled it said <identifier> expected. I will paste the full code below and would appreciate any help. Also, is there a getText function with JLabel, because I need to get what is currently in the output field and concatenate it with the number pressed.
    Thanks in advance for your help,
    Jeremy
    * Write a description of class calculator here.
    * @author (Jeremy Kruer)
    * @version (11/19/02)
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class calculator extends JFrame
    private JButton one, two, three, four, five, six, seven, eight, nine, zero, dec, eq, plus, minus, mult, div;
    private JLabel output;
    private Container container;
    //set up GUI
    public calculator()
    //Create Title
    super("Calculator");
    //Set size and make visible
    setSize( 400, 400 );
    setVisible( true );
    container = getContentPane();
    container.setLayout( new FlowLayout() );
    //set up output
    output = new JLabel();
    container.add( output );
    //set up seven and register its event handler
    seven = new JButton( " 7 " );
    seven.addActionListener(
    //anonymouse inner class
    new ActionListener()
    //add a seven to the output diplay when clicked
    output.setText( "7" );
    }//end anonymouse inner class
    ); //end call to addActionListener
    container.add( seven );
    //set up eight
    eight = new JButton( " 8 " );
    container.add( eight );
    //set up nine
    nine = new JButton( " 9 " );
    container.add( nine );
    //set up div
    div = new JButton( " / " );
    container.add( div );
    //set up four
    four = new JButton( " 4 " );
    container.add( four );
    //set up five
    five = new JButton( " 5 " );
    container.add( five );
    //set up six
    six = new JButton( " 6 " );
    container.add( six );
    //set up mult
    mult = new JButton( " * " );
    container.add( mult );
    //set up one
    one = new JButton( " 1 " );
    container.add( one );
    //set up two
    two = new JButton( " 2 " );
    container.add( two );
    //set up three
    three = new JButton( " 3 " );
    container.add( three );
    //set up minus
    minus = new JButton( " - " );
    container.add( minus );
    //set up zero
    zero = new JButton( " 0 " );
    container.add( zero );
    //set up dec
    dec = new JButton( " . " );
    container.add( dec );
    //set up eq
    eq = new JButton( " = " );
    container.add( eq );
    //set up plus
    plus = new JButton( " +" );
    container.add( plus );
    //Set size and make visible
    setSize( 220, 250 );
    setVisible( true );
    //execute application
    public static void main( String args[] )
    calculator application = new calculator();
    application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
    }

    I played with the lauout a bit and added the actionListener:
    you will see what you click on !!
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    public class calcu extends JFrame implements ActionListener
         private JButton  one, two, three, four, five, six, seven, eight, nine, zero, dec, eq, plus, minus, mult, div;
         private JLabel   output;
    public calcu()
         super("Calculator");
         JPanel container = new JPanel();
         container.setLayout(new FlowLayout(FlowLayout.LEFT));
         output = new JLabel("");
         output.setBorder(new MatteBorder(2,2,2,2,Color.gray));
         output.setPreferredSize(new Dimension(1,26));
         getContentPane().setBackground(Color.white);
         getContentPane().add("North",output);
         getContentPane().add("Center",container);
    //set up seven and register its event handler
         seven = new JButton(" 7 ");
         container.add(seven);
         seven.addActionListener(this);
    //set up eight
         eight = new JButton(" 8 ");
         container.add(eight);
         eight.addActionListener(this);
    //set up nine
         nine = new JButton( " 9 " );
         container.add( nine );
         nine.addActionListener(this);
    //set up div
         div = new JButton( " / " );
         container.add( div );
         div.addActionListener(this);
    //set up four
         four = new JButton( " 4 " );
         container.add( four );
         four.addActionListener(this);
    //set up five
         five = new JButton( " 5 " );
         container.add( five );
         five.addActionListener(this);
    //set up six
         six = new JButton( " 6 " );
         container.add( six );
         six.addActionListener(this);
    //set up mult
         mult = new JButton( " * " );
         container.add( mult );
         mult.addActionListener(this);
    //set up one
         one = new JButton( " 1 " );
         container.add( one );
         one.addActionListener(this);
    //set up two
         two = new JButton( " 2 " );
         container.add( two );
         two.addActionListener(this);
    //set up three
         three = new JButton( " 3 " );
         container.add( three );
         three.addActionListener(this);
    //set up minus
         minus = new JButton( " - " );
         container.add( minus );
         minus.addActionListener(this);
    //set up zero
         zero = new JButton( " 0 " );
         container.add( zero );
         zero.addActionListener(this);
    //set up dec
         dec = new JButton( " .  " );
         container.add( dec );
         dec.addActionListener(this);
    //set up eq
         eq = new JButton( " = " );
         container.add( eq );
         eq.addActionListener(this);
    //set up plus
         plus = new JButton( " +" );
         container.add( plus );
         plus.addActionListener(this);
    //Set size and make visible
         setSize(220,250);
         setResizable(false);
         setVisible( true );
    public void actionPerformed(ActionEvent ae)
         JButton but = (JButton)ae.getSource();
         output.setText(but.getText());
    //execute application
    public static void main( String args[] )
         calcu application = new calcu();
         application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
    } Noah

  • Having probelm with JLabel and setText

    I posted a message in Java Programming but I think it will be more appropriate here. I am trying to create a calculator so I want my JLabel(output) to display the number of the button that is clicked on. I used output.setText("7") but I get an error when compiling saying <identifier> expected. Any advice would be great. Also, is there a getText method in JLabel? I need to concatenate the current contents of JLabel and the value of the button pushed. For example:
    output.setText( output.getText() + "7" );
    Anyways, here is my code. I tried to make it indent so it is easier to read but it doesn't show up once I post it.
    Thanks for you help.
    * Write a description of class calculator here.
    * @author (Jeremy Kruer)
    * @version (11/19/02)
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class calculator extends JFrame
    private JButton one, two, three, four, five, six, seven, eight, nine, zero, dec, eq, plus, minus, mult, div;
    private JLabel output;
    private Container container;
    //set up GUI
    public calculator()
    //Create Title
    super("Calculator");
    //Set size and make visible
    setSize( 400, 400 );
    setVisible( true );
    container = getContentPane();
    container.setLayout( new FlowLayout() );
    //set up output
    output = new JLabel();
    container.add( output );
    //set up seven and register its event handler
    seven = new JButton( " 7 " );
    seven.addActionListener(
    //anonymouse inner class
    new ActionListener()
    //add a seven to the output diplay when clicked
    output.setText( "7" );
    }//end anonymouse inner class
    ); //end call to addActionListener
    container.add( seven );
    //set up eight
    eight = new JButton( " 8 " );
    container.add( eight );
    //set up nine
    nine = new JButton( " 9 " );
    container.add( nine );
    //set up div
    div = new JButton( " / " );
    container.add( div );
    //set up four
    four = new JButton( " 4 " );
    container.add( four );
    //set up five
    five = new JButton( " 5 " );
    container.add( five );
    //set up six
    six = new JButton( " 6 " );
    container.add( six );
    //set up mult
    mult = new JButton( " * " );
    container.add( mult );
    //set up one
    one = new JButton( " 1 " );
    container.add( one );
    //set up two
    two = new JButton( " 2 " );
    container.add( two );
    //set up three
    three = new JButton( " 3 " );
    container.add( three );
    //set up minus
    minus = new JButton( " - " );
    container.add( minus );
    //set up zero
    zero = new JButton( " 0 " );
    container.add( zero );
    //set up dec
    dec = new JButton( " . " );
    container.add( dec );
    //set up eq
    eq = new JButton( " = " );
    container.add( eq );
    //set up plus
    plus = new JButton( " +" );
    container.add( plus );
    //Set size and make visible
    setSize( 220, 250 );
    setVisible( true );
    //execute application
    public static void main( String args[] )
    calculator application = new calculator();
    application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

    // not tested but try it ...
    1. put an empty string into the JLabel
    declare
    String labString = "";
    (and declare the JLabel too)
    2. initialise label - init() {
    myLabel = new JLabel(labString)
    3. activate
    actionPerformed(ActionEvent evt) {
    if (evt.getSource()==button#7) {
    labString = getActionCommand();
    myLabel.setText(labString);
    validate();
    Something like that anyway - it should work + if you 'play' with it, you can probably make it a bit more efficiently than the methods I've outlined here.

  • Help with Mathscipt and for loop

    I have a code in Mathscript/matlab and I need to output the array out. One option is my first code,the other option is using a for loop, but I am only getting the last ouput out. I need to get the whole output out.
    Any help.
    Thanks
    Solved!
    Go to Solution.
    Attachments:
    Help with Mathscript_for loop.vi ‏115 KB
    Help with Mathscript_for loop2.vi ‏84 KB

    Here's how it should look like.
    Message Edited by altenbach on 10-30-2008 05:12 PM
    LabVIEW Champion . Do more with less code and in less time .
    Attachments:
    MathscriptInFOR.png ‏15 KB

  • Help with encapsulation and a specific case of design

    Hello all. I have been playing with Java (my first real language and first OOP language) for a couple months now. Right now I am trying to write my first real application, but I want to design it right and I am smashing my head against the wall with my data structure, specifically with encapsulation.
    I go into detail about my app below, but it gets long so for those who don't want to read that far, let me just put these two questions up front:
    1) How do principles of encapsulation change when members are complex objects rather than primitives? If the member objects themselves have only primitive members and show good encapsulation, does it make sense to pass a reference to them? Or does good encapsulation demand that I deep-clone all the way to the bottom of my data structure and pass only cloned objects through my top level accessors? Does the analysis change when the structure gets three or four levels deep? Don't DOM structures built of walkable nodes violate basic principles of encapsulation?
    2) "Encapsulation" is sometimes used to mean no public members, othertimes to mean no public members AND no setter methods. The reasons for the first are obvious, but why go to the extreme of the latter? More importantly HOW do you go to the extreme of the latter? Would an "updatePrices" method that updates encapsulated member prices based on calculations, taking a single argument of say the time of year be considered a "setter" method that violates the stricter vision of encapsulation?
    Even help with just those two questions would be great. For the masochistic, on to my app... The present code is at
    http://www.immortalcoil.org/drake/Code.zip
    The most basic form of the application is statistics driven flash card software for Japanese Kanji (Chinese characters). For those who do not know, these are ideographic characters that represent concepts rather than sounds. There are a few thousand. In abstract terms, my data structure needs to represent the following.
    -  There are a bunch of kanji.
       Each kanji is defined by:
       -  a single character (the kanji itself); and
       -  multiple readings which fall into two categories of "on" and "kun".
          Each reading is defined by:
          -  A string of hiragana or katakana (Japanese phoenetic characters); and
          -  Statistics that I keep to represent knowledge of that reading/kanji pair.Ideally the structure should be extensible. Later I might want to add statistics associated with the character itself rather than individual readings, for example. Right now I am thinking of building a data structure like so:
    -  A Vector that holds:
       -  custom KanjiEntry objects that each hold
          -  a kanji in a primitive char value; and
          -  two (on, kun) arrays or Vectors of custom Reading objects that hold
             -  the reading in a String; and
             -  statistics of some sort, probably in primitive valuesFirst of all, is this approach sensible in the rough outlines?
    Now, I need to be able to do the obvious things... save to and load from file, generate tables and views, and edit values. The quesiton of editting values raises the questions I identified above as (1) and (2). Say I want to pull up a reading, quiz the user on it, and update its statistics based on whether the user got it right or wrong. I could do all this through the KanjiEntry object with a setter method that takes a zillion arguments like:
    theKanjiEntry.setStatistic(
    "on",   // which set of readings
    2,      // which element in that array or Vector
    "score", // which statistic
    98);      // the valueOr I could pass a clone of the Reading object out, work with that, then tell the KanjiEntry to replace the original with my modified clone.
    My instincts balk at the first approach, and a little at the second. Doesn't it make more sense to work with a reference to the Reading object? Or is that bad encapsulation?
    A second point. When running flash cards, I do not care about the subtlties of the structure, like whether a reading is an on or a kun (although this is important when browsing a table representing the entire structure). All I really care about is kanij/reading pairings. And I should be able to quickly poll the Reading objects to see which ones need quizzing the most, based on their statistics. I was thinking of making a nice neat Hashtable with the keys being the kanji characters in Strings (not the KanjiEntry objects) and the values being the Reading objects. The result would be two indeces to the Reading objects... the basic structure and my ad hoc hashtable for runninq quizzes. Then I would just make sure that they stay in sync in terms of the higher level structure (like if a whole new KanjiEntry got added). Is this bad form, or even downright dangerous?
    Apart from good form, the other consideration bouncing around in my head is that if I get all crazy with deep cloning and filling the bottom level guys with instance methods then this puppy is going to get bloated or lag when there are several thousand kanji in memory at once.
    Any help would be appreciated.
    Drake

    Usually by better design. Move methods that use the
    getters inside the class that actually has the data....
    As a basic rule of thumb:
    The one who has the data is the one using it. If
    another class needs that data, wonder what for and
    consider moving that operation away from that class.
    Or move from pull to push: instead of A getting
    something from B, have B give it to A as a method
    call argument.Thanks for the response. I think I see what you are saying.. in my case it is something like this.
    Solution 1 (disfavored):
    public class kanjiDrill{ // a chunk of Swing GUI or something
         public void runDrill(Vector kanjiEntries){
              KanjiEntry currentKanjiEntry = kanjiEntries.elementAt(0); // except really I will pick one randomly
              char theKanji = currentKanjiEntry.getKanji();
              String theReading = currentKanjiEntry.getReading();
              // build and show a flashcard based on theKanji and theReading
              // use a setter to change currentKanji's data based on whether the user answers correctly;
    }Solution 2 (favored):
    public class kanjiDrill{ // a chunk of Swing GUI or something
         public void runDrill(Vector kanjiEntries){
              KanjiEntry currentKanjiEntry = kanjiEntries.elementAt(0); // except really I will pick one randomly
              currentKanji.buildAndShowFlashcard(); // method includes updating stats
    }I can definitely see the advantages to this, but two potential reasons to think hard about it occur to me right away. First, if this process is carried out to a sufficient extreme the objects that hold my data end up sucking in all the functionality of my program and my objects stop resembling natural concepts.
    In your shopping example, say you want to generate price tags for the items. The price tags can be generated with ONLY the raw price, because we do not want the VAT on them. They are simple GIF graphics that have the price printed on a an irregular polygon. Should all that graphics generating code really go into the item objects, or should we just get the price out of the object with a simple getter method and then make the tags?
    My second concern is that the more instance methods I put into my bottom level data objects the bigger they get, and I intend to have thousands of these things in memory. Is there a balance to strike at some point?
    It's not really a setter. Outsiders are not setting
    the items price - it's rather updating its own price
    given an argument. This is exactly how it should be,
    see my above point. A breach of encapsulation would
    be: another object gets the item price, re-calculates
    it using a date it knows, and sets the price again.
    You can see yourself that pushing the date into the
    item's method is much beter than breaching
    encapsulation and getting and setting the price.So the point is not "don't allow access to the members" (which after all you are still doing, albeit less directly) so much as "make sure that any functionality implicated in working with the members is handled within the object," right? Take your shopping example. Say we live in a country where there is no VAT and the app will never be used internationally. Then we would resort to a simple setter/getter scheme, right? Or is the answer that if the object really is pure data are almost so, then it should be turned into a standard java.util collection instead of a custom class?
    Thanks for the help.
    Drake

  • Can anyone help with iPlayer and Sky Mobile?

    Ok, I'm so close to giving up with this useless phone. There are 3 apps on my N97 which give me a constant headache.
    BBC iPlayer
    Sky Mobile*
    YouTube
    *I should point out that I only use Sky Mobile to set recordings on my Sky+. I do not use it for, nor have any desire to use it for actually watching Mobile TV.
    All of these apps work absolutely fine over my home WiFi network. It's when I try to use them over 3G (my Vodafone Live! connection) that I start running in to trouble.
    All 3 give me connection problems, errors, and simply refuse to load half the time when on 3G. I got so annoyed I just did a hard reset the other week, and magically all three started working again. However, now 2 of them are failing me again. YouTube (touch wood) is working fine at the moment, but iPlayer and Sky Mobile just aren't.
    iPlayer sometimes works. But sometimes I get script errors (unable to load content), and sometimes it says something about checking my connection settings. I wouldn't mind but it's not actually possible to access any options for the iPlayer. Even in application settings there are no options you're able to set.
    Sky Mobile simply flat out refuses to work ever on 3G. But it did after I did a hard reset for a couple of weeks, now it just stopped working! It wont even load. It just gives the error message 'Unable to connect to network - please check connection settings" or something along those lines.
    I've tried so many different things. Tried setting my internet connections to 'always ask', tried setting it to default to Vodafone Live! all the time, tried setting my video streaming settings to WAP, all sorts. Every combination I can think of.
    I just can't wait to get rid of this phone. I've put so many people off buying one. They see it and think it's all swish and cool, and I just say 'Don't. You'll regret it'. I can't wait for my contract to be up so I can upgrade to an iPhone now Vodafone have got them.
    Can anyone help with these problems? Thanks in advance, but I don't hold out much hope...

    About iPlayer.
    Have a chat with Vodaphone. Streaming iPlayer over 3G IS allowed on Vodaphone contract, unlike my O2 contract. As long as your contract allows it, and you have the correct AP address, it should be fine. Vodaphone should be able to give you the setting.
    Mine only works over Wlan.
    FWIW, "... streaming over 3G is not currently available on iPhone handsets on any mobile network".
    p.s. Just to be clear. You say  "Tried setting my internet connections to 'always ask', tried setting it to default to Vodafone Live!".
    iPlayer uses the Nokia browser "Web". So that's where you should make the setting "Ask when needed". It should then offer you the choice of whatever you've set in Destinations> Internet> then select whatever you've chosen as your GPRS connection.(as advised, or sent to you by Vodaphone).

  • Help with exporting and image size or boundaries?

    I am trying to slide the cat into the scene a little at a time foir an animation project I am working on. However, when I export the image the back ground of the image expands with a checkered back ground( showing here in white) and shows the whole cat.
    How do I just show a little of the cat on the image at a time when exporting. I am trying to give the impression that the cat is walking into the room. I do not want to have to cut the cat up.
    I would be thankful for any suggestions.

    Provide the name of the program you are using so a Moderator may move this message to the correct program forum
    This Cloud forum is not about help with program problems... a program would be Photoshop or Lighroom or Muse or ???

Maybe you are looking for

  • Failed to import publish settings file in Azure Toolkit for Eclipse with Java downloaded from Azure Management Portal

    I tried to deploy the Hello World JSP application to Azure from Eclipse following the instructions at http://msdn.microsoft.com/library/azure/hh690944%28VS.103%29.aspx. Got the following error when trying to import Publish Settings file downloaded fr

  • IMAC doesn't recognize lacie external hard drive

    Friends, I have an imac 2013 3TB fusion drive running Mavericks.  I have a lacie external quadra drive USB 3.0. When I turn on the drive, the computer does not recognize it.  However, if I restart the computer, it then will recognize the drive.  Why

  • Removing item from Finder Toolbar?

    I inadvertently dragged a file to my finder toolbar where it is now stuck? I cannot drag it off or use and command or option key to drag it off? What am I missing here, it did it get corrupted in some manner? TIA Henry

  • When I click on a new tab, I can't type anything in.

    Up until a little while ago, when I clicked on the + sign for a new tab, a large blank box would drop down where I could type in the URL. Now that isn't happening and I am not able to type anything in. I can browse history, but if I want a new URL or

  • WebCenter Links Service for Fusion Object

    I am working on a Fusion Application that has the following requirements: 1. Links between Fusion Business Objects (i.e. VO). For example, link a Fusion Srevice Request Object to another Fusion Service Request Object or to a Fusion "Solution" object.