Hot questions for Using JTextField in int

Question:

I figure this must be a simple mistake in the code or a misunderstanding on my part, but I cannot get a DocumentFilter to detect insertString events. Below is a simple filter for upper case letters, but that is not as important as the fact that the insertString(..) method never seems to be called!

Why is the insertString(..) method of the DocumentFilter not called?

The filter is applied to the JTextField at the top. Every time insertString(..) is called, it should append information to the JTextArea in the CENTER. At the moment, there is no action in the text field that causes text to be appended to the text area.

import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.text.*;

public class FilterUpperCaseLetters {

    private JComponent ui = null;
    private final JTextField textField = new JTextField(25);
    private final JTextArea textArea = new JTextArea(5, 20);

    FilterUpperCaseLetters() {
        initUI();
    }

    public void initUI() {
        // The document filter that seems to do nothing.
        DocumentFilter capsFilter = new DocumentFilter() {
            @Override
            public void insertString(
                    DocumentFilter.FilterBypass fb,
                    int offset,
                    String string,
                    AttributeSet attr) throws BadLocationException {
                textArea.append("insertString! " + string + "\n");
                if (!string.toUpperCase().equals(string)) {
                    textArea.append("Insert!\n");
                    super.insertString(fb, offset, string, attr);
                } else {
                    textArea.append("DON'T insert!\n");
                }
            }
        };
        AbstractDocument abstractDocument
                = (AbstractDocument) textField.getDocument();
        abstractDocument.setDocumentFilter(capsFilter);

        ui = new JPanel(new BorderLayout(4, 4));
        ui.setBorder(new EmptyBorder(4, 4, 4, 4));

        ui.add(textField, BorderLayout.PAGE_START);
        ui.add(new JScrollPane(textArea), BorderLayout.CENTER);
    }

    public JComponent getUI() {
        return ui;
    }

    public static void main(String[] args) {
        Runnable r = new Runnable() {
            @Override
            public void run() {
                FilterUpperCaseLetters o = new FilterUpperCaseLetters();

                JFrame f = new JFrame(o.getClass().getSimpleName());
                f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                f.setLocationByPlatform(true);

                f.setContentPane(o.getUI());
                f.pack();
                f.setMinimumSize(f.getSize());

                f.setVisible(true);
            }
        };
        SwingUtilities.invokeLater(r);
    }
}

Answer:

The text components use the replaceSelection(...) method which will in turn invoke the replace(...) method of the AbstractDocument which will invoke the replace(...) method of the DocumentFilter.

The insertString(...) method of the DocumentFilter is only called when you use the Document.insertString(...) method to directly update the Document.

So in reality you need to override both methods to make sure the upper case conversion is done.

A simple example showing how to easily implement both methods:

import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;

public class UpperCaseFilter extends DocumentFilter
{
    public void insertString(FilterBypass fb, int offs, String str, AttributeSet a)
        throws BadLocationException
    {
        replace(fb, offs, 0, str, a);
    }

    public void replace(FilterBypass fb, final int offs, final int length, final String str, final AttributeSet a)
        throws BadLocationException
    {
        if (str != null)
        {
            String converted = convertString(str);
            super.replace(fb, offs, length, converted, a);
        }
    }

    private String convertString(String str)
    {
        char[] upper = str.toCharArray();

        for (int i = 0; i < upper.length; i++)
        {
            upper[i] = Character.toUpperCase(upper[i]);
        }

        return new String( upper );
    }

    private static void createAndShowGUI()
    {
        JTextField textField = new JTextField(10);
        AbstractDocument doc = (AbstractDocument) textField.getDocument();
        doc.setDocumentFilter( new UpperCaseFilter() );

        JFrame frame = new JFrame("Upper Case Filter");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout( new java.awt.GridBagLayout() );
        frame.add( textField );
        frame.setSize(220, 200);
        frame.setLocationByPlatform( true );
        frame.setVisible( true );
    }

    public static void main(String[] args) throws Exception
    {
        EventQueue.invokeLater( () -> createAndShowGUI() );
/*
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                createAndShowGUI();
            }
        });
*/
    }

}

Question:

JTextfield does not show korean charaters properly. It shows empty boxes in instead of characters. Here is the screenshot of my application.


Answer:

Thats because of the fonts that you used.

According to this oracle document Korean letters is not supported by Lucida font.

Note that of the writing systems that are generally fully supported by the JRE, the Lucida fonts do not support Chinese (Simplified), Chinese (Traditional), Japanese, and Korean.

So if you use the fonts that support the korean language, it will work properly.

Question:

I made a program that dynamically gets data from a Panel but my code needs the user to hit the enter button for the data to be updated. Is there a change listener or other listeners that can update the data from a Jtextfield whenever it is updated? Thanks!


Answer:

Just add a listener to the textfield so that it tracks when the text changes

textfieldName.getDocument().addDocumentListener(new DocumentListener() {
    // implement the methods
});

Question:

Please have a look at the below code

Border border = BorderFactory.createLineBorder(Color.RED, 1);
introducerFeesTxt.setBorder(border);

I used this code to create a line border for the JTextField. However now I need to remove it and replace it's normal view. Below is what I tried.

introducerFeesTxt.setBorder(BorderFactory.createLineBorder(Color.BLACK, 1));

That code above again created a border which is not similar to other normal JTextFields. Below is a screenshot.

You can clearly see the differnece between the "Normal" JTextField and the JTextField with the added border. How can I reset it to be "normal" ?


Answer:

You could keep the original border in a variable before change it and then use this border to set it back to its original state:

Border originalBorder;
...
JTextField textField = new JTextField(20);
originalBorder = textField.getBorder();
// here you can safely change text field's border

Of course the scope of this originalBorder variable should be wide enough to use it when needed (f.e.: class member).

Note: Please note this approach is independent of the PLAF used by your application.

Question:

I am creating a minesweeper game, and what I want to do is to have a JTextField where the user inputs his name in order for his score to be saved in a file.

My problem is that when I create a JTextField and add it to my Jpanel it appears in 2 locations. Here is an image of what is happening (https://i.imgur.com/Ao8dRo1.jpg)

This is my code over-simplified. I believe that I don't properly understand something about how the mechanism of the GUI works.

GUI.java

public class GUI extends JFrame {
  //..
  //some variables here
  //...

  public GUI() {
        this.setTitle("Minesweeper Game");
        this.setSize(WIDTH, HEIGHT);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setVisible(true);
        this.setResizable(false);
        this.setLayout(null);

        //This method does not involve any drawing, it only places data in some arrays that I later use in paintComponent() to draw stuff accordingly to what the data is
        setMinefield();


        Board board = new Board();
        this.setContentPane(board);

        Click click = new Click();
        this.addMouseListener(click);
    }

    public class Board extends JPanel {
        public void paintComponent (Graphics g) {
        //...    
        //Drawing tiles, smiley, counters
        //...

        //And now I draw the area for the JTextField, and I also create it and add it in the Jpanel
        JTextField textField = new JTextField();
        textField.setFont(new Font("Tahoma", Font.PLAIN, 35));
        textField.setBounds(290, 80, 135, 40); //<-- This correctly places the textField where I want. The second textField seems to appear in the exact center of the X axis of my window

        add(textField); //<-- Adding the textField to the Jpanel

        } //End of paintComponent()
    }//End of Board class
}//End of GUI class

Main.java

public class Main implements Runnable {

    GUI gui = new GUI();

    public static void main(String[] args) {
        new Thread (new Main()).start();
    }

    @Override
    public void run() {
        while (true) {
            gui.repaint();
        }
    }

}

Answer:

I think the problem is that you have overridden paintComponent in your Board class. This method gets called every time the component needs to be drawn so a new text field will be added each time.

It would be better to add the text field in the constructor for your board class.

Question:

I'm making a program where you type in a number and it will either tell you if you got it right or wrong. This is the code.

static int num = 1;

JPanel pnl = new JPanel();
        JTextField numSlot = new JTextField(5);
        pnl.add(new JLabel("Enter the number:"));
        pnl.add(numSlot);

        int k = JOptionPane.showConfirmDialog(null, pnl, "Enter your code", -1);
        if (k == JOptionPane.OK_OPTION) {

            if(numSlot.getText().equals(num)) {
                JOptionPane.showMessageDialog(null, "It Worked", "It Worked", -1);
            } else {
                JOptionPane.showMessageDialog(null, "Sorry", "Sorry", -1);
            }
        }
        if (k == JOptionPane.CANCEL_OPTION) {

        } else {

        }

With this code it always outputs sorry even if i type 1 so is there something i'm doing wrong? If so could you answer it and try not to be rude i am a beginner.


Answer:

use

if(numSlot.getText().equals(num+"")){

instead of

if(numSlot.getText().equals(num)) {

as num+"" convert it int to String. Otherway you can use Integer.toString(num) or String.valueOf(num)

Explanation

numSlot.getText() return String and num is int so numSlot.getText().equals(num) always false as String value can not be same as integer value.

Question:

So I am a having a problem regarding my JTextField. What I'm trying to do is to put the JTextField box below the picture(map of a certain town). Yeah, I used .setBounds and it was already below the image, but what I want to happen is that if I do .pack();, it must be still visible. Unfortunately, it wasn't.

I tried using the .setBorder(BorderFactory.createEmptyBorder(5,50,0,50)); and I saw that the box is below the picture but it is no longer available for putting a text.

And to conclude, I want the JTextField below the picture and still must be visible whenever I pack it.

Please Help. Thank you. I am still on the stage of discovering new things about GUI. Sorry for the noob question.

  import java.awt.BorderLayout;
  import java.awt.Color;
  import java.awt.FlowLayout;
  import java.awt.Font;

  import javax.swing.BorderFactory;
  import javax.swing.ImageIcon;
  import javax.swing.JFrame;
  import javax.swing.JLabel;
  import javax.swing.JPanel;
  import javax.swing.SwingUtilities;
  import javax.swing.JTextField;

  class ProgDraftMain {

   public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable(){
        public void run() {
            ProgDraft gui = new ProgDraft();
            gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
            gui.setResizable(false);
            gui.pack();
            //gui.setSize(1000 , 1000);
            gui.setVisible(true);           
        }
    });
}
}

class ProgDraft extends JFrame {
private ImageIcon image1;
private JLabel label1;
private JTextField textField1;

ProgDraft() {

    /***Panel**/ 
    JPanel panel = new JPanel();
    panel.setLayout(new FlowLayout(FlowLayout.LEADING));

    /***Title***/
    JLabel title = new JLabel("Perimeter Check", JLabel.CENTER);
    Font font = new Font("Gigi", Font.BOLD, 50);
    title.setFont(font);

    /***Image***/
    ImageIcon pics = new ImageIcon(getClass().getResource("antipolo.png"));

    JLabel logo = new JLabel(pics);
    logo.setBorder(BorderFactory.createEmptyBorder(10, 70, 0, 50));
    logo.setToolTipText("Ito raw kunware yung barangay.");
    panel.add(logo);

    /***Info ANtipolo***/
    String text = "Ito kunware ang ANtipolo" + "<br>" +
          "Marami ditong landslide areas" + "<br>" + "<br>" +
          "Take care and stay safe!" + "<br>" +
          "I love my dogs" + "<br>" + "<br>" +"<br>" +
          "Please help!";
    JLabel dog = new JLabel("<html><div style=\"text-align: center;\">" + text + "</html>");
    dog.setBorder(BorderFactory.createEmptyBorder(5,50,0,50));
    panel.add(dog);

    /***JTextFieldski**/
    JTextField textField = new JTextField(6);
    textField.setBorder(BorderFactory.createEmptyBorder(5,50,0,50));
    textField.setBounds(210,470,100,25);
    panel.add(textField);




    getContentPane().setLayout(new BorderLayout());

    getContentPane().add(textField, BorderLayout.SOUTH);
    getContentPane().add(dog, BorderLayout.CENTER);
    getContentPane().add(panel, BorderLayout.SOUTH);
    getContentPane().add(title, BorderLayout.NORTH);
}
}

Answer:

I think you took my advice yesterday about using EmptyBorder a little too far. You are trying to use it for pixel perfect position. That's not what they're meant for. Don't worry about pixel perfect positioning. Like I said yesterday, learn the layout managers and make use of them. Also you can wrap components in panels with different layout managers and nest the panels. You don't have to try and get everything perfect on one panel. Different layout managers have different features and qualities.

For instance What you are trying to do is add two different components to the BorderLayout.SOUTH. The thing about BorderLayout is each position can only have one components. The last one added wins. So what can we do? How about wrapping the two in a panel, then adding that panel to the SOUTH :-) Easy right?

Also in regards to the EmptyBorders, Make use the the JLabel api. You can setHorizontalAlignment to JLabel.CENTER. The default is JLabel.LEADING, so all the text is to the left. If you set it to the center, then it will be centered.

Also just FYI, setBounds will not work unless you are using null layouts, which I advise against. You don't use it.

Here is the refactor (using NO Empty Borders, letting the layout managers do the job we pay them to do)

import java.awt.BorderLayout;
import java.awt.Font;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.JTextField;

class ProgDraftMain {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                ProgDraft gui = new ProgDraft();
                gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                gui.setResizable(false);
                gui.pack();
                //gui.setSize(1000 , 1000);
                gui.setVisible(true);
            }
        });
    }
}

class ProgDraft extends JFrame {

    private ImageIcon image1;
    private JLabel label1;
    private JTextField textField1;

    ProgDraft() {

        /**
         * Main Panel
         */
        JPanel mainPanel = new JPanel(new BorderLayout());
        /**
         * *Title**
         */
        JLabel title = new JLabel("Perimeter Check", JLabel.CENTER);
        Font font = new Font("Gigi", Font.BOLD, 50);
        title.setFont(font);
        mainPanel.add(title, BorderLayout.PAGE_START);   // add title to top

        /**
         * *Info ANtipolo**
         */
        String text = "Ito kunware ang ANtipolo" + "<br>"
                + "Marami ditong landslide areas" + "<br>" + "<br>"
                + "Take care and stay safe!" + "<br>"
                + "I love my dogs" + "<br>" + "<br>" + "<br>"
                + "Please help!";
        JLabel dog = new JLabel("<html><div style=\"text-align: center;\">" + text + "</html>");
        dog.setHorizontalAlignment(JLabel.CENTER);
        mainPanel.add(dog);   //   add dog to center

        /**
         * *Image** ==========>>>>>> Make sure to change the image name back.
         */
        ImageIcon pics = new ImageIcon(getClass().getResource("stackoverflow.png"));

        JLabel logo = new JLabel(pics);
        logo.setHorizontalAlignment(JLabel.CENTER);
        //logo.setBorder(BorderFactory.createEmptyBorder(10, 70, 0, 50));
        logo.setToolTipText("Ito raw kunware yung barangay.");

        /**
         *  Wrapper for text field and icon
         */
        JPanel iconFieldPanel = new JPanel(new BorderLayout());
        JTextField textField = new JTextField(10);    
        iconFieldPanel.add(logo);
        iconFieldPanel.add(textField, BorderLayout.PAGE_END);
        JPanel iconFieldWrapper = new JPanel();
        iconFieldWrapper.add(iconFieldPanel);

        mainPanel.add(iconFieldWrapper, BorderLayout.PAGE_END);  // add icon and field to bottom

        getContentPane().add(mainPanel);
    }
}

And pleeease do take some time to go over the link I provided for using layout managers. Study one at a time and get the hang of each. It's an art, so it'll take time, just like anything else.

Question:

private void loadActionPerformed(java.awt.event.ActionEvent evt) {                                     
    // TODO add your handling code here:
    try{
        FileReader reader = new FileReader("reload.txt");
        BufferedReader br = new BufferedReader(reader);
        koontf.read(br,null);
        baamtf.read(br,null);
        sachitf.read(br,null);
        fakertf.read(br,null);
        phonsekaltf.read(br,null);
        lauretf.read(br,null);
        yeontf.read(br,null);
        aguerotf.read(br,null);
        agnistf.read(br,null);
        lokitf.read(br,null);
        lawliettf.read(br,null);
        ryuzakitf.read(br,null);
        br.close();
        koontf.requestFocus();
        baamtf.requestFocus();
        sachitf.requestFocus();
        fakertf.requestFocus();
        phonsekaltf.requestFocus();
        lauretf.requestFocus();
        yeontf.requestFocus();
        aguerotf.requestFocus();
        agnistf.requestFocus();
        lokitf.requestFocus();
        lawliettf.requestFocus();
        ryuzakitf.requestFocus();

    }catch(IOException e) {

    }
}                                    

Is it even possible to put each of them to a certain textfield?Like 12 to jtextfield1,10 to jtextfield2 and so on...I've tried some tutorials and can't really figure it out.


Answer:

You could put all your textFields in an array and then iterate over that array while you are reading the text file. Like this:

JTextField[] textFields = new JTextField[10];
// ... init your textFields here

int line =0;  // first line will be first textfield and so on
Scanner scanner = new Scanner(new File("reload.txt"));  // use Scanner instead of FileReader, it's easier :) 
while(scanner.hasNextLine()){   // as long as you did not reach the end of the file
    textFields[line++].setText(scanner.nextLine()); // get the next line and put it in the respective textfield
}

However, in this case you have to make sure that there is a textfield for every line or that you do not read more lines than there are textfields.

for example:

while(.....){
   ....
   if(line==textFields.length){
       break;
   }
}

Another thing to notice will be, that the order of the lines has to correspond to the order of your textFields.

Edit I have to add, that all this can work without any problem. But it is not a very elegant solution. What happens when you change your UI and the Textfields are in a different order? Or there is an important new line in your textfile but no TextField in your UI?

Edit 2 The code from your comment does not show how you put the JTextFields in your array. My Guess is that you are using some IDE to create the GUI, so you should have a initComomponents(); call or something in your constructor. In this case, remove the line JTextField[] textFields = new JTextField[10]; from your loadActionPerformed method and put it in your constructor like this:

public class MyClass{

     private JTextField[] textFields;

     public MyClass(){
         initComponents();
         this.textFields = new JTextField[10]  // where 10 is the number of lines in your textfile AND the number of JTextFields you have in your GUI
         // then fill the array (by hand if you like)
         this.textField[0] = koontf;
         this.textField[1] = baamtf;
         // and so on..
     }

Edit 3 Just to make it clear, this is what you need to make the program run. Let's say your class is called MyClass then it could look like this:

private JTextField[] textFields;  // this creates your array

public MyClass(){        // this is the constructor of your class (I don't know how it is called) 
    initComponents();    // auto generated code from NetBeans to initalize your GUI elements
    // init your array
    textFields = new JTextField[12];  // 12 if I counted correctly
    // fill it
    textFields[0] = koontf;
    textFields[1] = baamtf;
    textFields[2] = sachitf;
    textFields[3] = fakertf;
    textFields[4] = phonsekaltf;
    textFields[5] = lauretf;
    textFields[6] = yeontf;
    textFields[7] = aguerotf;
    textFields[8] = agnistf;
    textFields[9] = lokitf;
    textFields[10] = lawliettf;
    textFields[11] = ryuzakitf;
}

private void loadActionPerformed(java.awt.event.ActionEvent evt){
    int line = 0;
    try(Scanner scanner = new Scanner(new File("reload.txt"))){
        while(scanner.hasNextLine()){
            textFields[line++].setText(scanner.nextLine());
            if(line == textFields.length){
                break;
            }
        }
    }catch(FileNotFoundException ex){
        Logger.getLogger(MyClass.class.getName()).log(Level.SEVERE, null, ex);
    }
    koontf.requestFocus();  // you can only call request focus on one element at a time (it does not make sense to call it on all textfields
}

Question:

so i'm trying to implement a simple GUI program whereby the user types in the text field then when he presses enter, the text is appended to the text field but i'm getting this kind of output:

Here's my codes:

TextField.java:

package activity1;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JLabel;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JOptionPane;
import java.awt.FlowLayout;

public class TextField extends JFrame{

private JTextField text;
private JTextArea textArea;

public TextField()
{
    super("Activity 1");
    setLayout(new FlowLayout());

    text = new JTextField(20);
    add(text);

    textArea = new JTextArea(5,20);
    textArea.setEditable(false);
    add(textArea);

    TextFieldHandler handler = new TextFieldHandler();

    text.addActionListener(handler);
}

private class TextFieldHandler implements ActionListener{

    public void actionPerformed(ActionEvent event)
    {
        String line = text.getText();
        textArea.append(text + "\n");
        //text.setText("");
    }
}

}

And my main TextFieldTEST.java:

package activity1;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class TextFieldTEST {

public static void main(String[] args) {

    TextField myFrame = new TextField();
    myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    myFrame.setSize(300,200);
    myFrame.setVisible(true);
}

}

Please help.


Answer:

You're appending the JTextField not its content, and so you're seeing the result of calling toString() on this JTextField object. The fix is small and simple:

Change:

String line = text.getText();
textArea.append(text + "\n"); // don't use text here

to:

String line = text.getText();
textArea.append(line + "\n"); // notice the difference? using line here

As a side recommendation:

  • Put your JTextArea in a JScrollPane and add that to the GUI.
  • Don't set sizes of your components. Rather pack() your GUI and let the layout managers and the components size themselves.
  • For instance, I'd use a BorderLayout (which is the default for your JFrame's contentPane), and then add the JTextField BorderLayout.PAGE_START and the JScrollPane that holds the JTextArea BorderLayout.CENTER.

Question:

How to get integer value from JTextField of Swing as we get string value via getText() method?

try {
        String sql = "insert into employeeinfo   (username,password,obtainmark) values(?,?,?)";
        pst = conn.prepareStatement(sql);
        pst.setString(1, txt_username.getText());
        pst.setString(2, txt_password.getText());
        pst.setInt(3, txt_obtainmark.getText());
        pst.execute();

        JOptionPane.showMessageDialog(null, "data inserted");
    } catch (Exception e) {

        JOptionPane.showMessageDialog(null, e);
    }

I am not able to insert integer data type value from the JTextField, but able to insert only string or varchar type data.


Answer:

You can do Integer.parseInt(string) to get Integer value.

pst.setInt(Interger.parseInt(txt_obtainmark.getText()));

Question:


Answer:

Do something like below:

public void checkEmpty() {
    JTextField [] textFields = {jTextField1,jTextField2,jTextField3,jTextField4,jTextField5,jTextField6};
    isInputValid = true;
    for (int i = 0; i < textFields.length; i++) {
        JTextField jTextField = textFields[i];
        String textValue = jTextField.getText().trim();
        if (textValue.length() == 0) {
            //turn background into red
            jTextField.setBackground(Color.RED);
            isInputValid = false;
        }
    }

    // now check if input are valid
    if(!isInputValid) return;

    //save to database----> I know what I have to do here.
}

Question:

I have two JFrame (JFrame1 and JFrame2) with two JTextField1 and JTextField2. My question is when I write "Hello world " on JTextField2 from Jframe2 and then click on OK button, I see "Hello world " on JTextField1 on Jframe1 class.

How can I do this? I'm sorry if this is a newbie question but I'm learning..

Here is my code:

JFrame2:

private JFrame1 jf1;
private void btn2ActionPerformed(java.awt.event.ActionEvent evt) {                                     
    jf1.setjTextField1(this.jTextField2);
} 

Answer:

What you are doing there is actually sending the reference to the actual JTextField from one frame to the other one.

That's probably not a good idea cause both frames would be end up referencing the same visual component.

What you probably want is to keep all visual components separate, but make the text of the second text field equal to the text in the first one.

Something like this:

private void btn2ActionPerformed(java.awt.event.ActionEvent evt) {                                     
    jf1.getjTextField1().setText(this.jTextField2.getText());
} 

Question:

Dunno if anyone can help me out or not. Assignment is due here in about 3 hours and I'm pretty frustrated. I cannot get the file that I am reading to display in the JTextArea. That is all that I need to do. Can anyone help out?

public class Reader extends javax.swing.JFrame {

/**
 * Creates new form Reader
 */
public Reader() {
    initComponents();
}

public void displayText(){
    JLabel Text = new JLabel();
    add(Text);
}
/**
 * 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();
    jScrollPane1 = new javax.swing.JScrollPane();
    jTextArea1 = new javax.swing.JTextArea();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    jLabel1.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
    jLabel1.setText("Contact Info");

    jTextArea1.setColumns(20);
    jTextArea1.setRows(5);
    jScrollPane1.setViewportView(jTextArea1);
    jTextArea1.setEditable(false);

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGap(54, 54, 54)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 477, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap(71, Short.MAX_VALUE))
        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 210, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(176, 176, 176))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
            .addGap(25, 25, 25)
            .addComponent(jLabel1)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 35, Short.MAX_VALUE)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 301, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(64, 64, 64))
    );

    pack();
    setLocationRelativeTo(null);
}// </editor-fold>                        

/**
 * @param args the command line arguments
 */
public static void main(String args[]) throws IOException {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
     */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(Reader.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(Reader.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(Reader.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(Reader.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    BufferedReader br = new BufferedReader(new FileReader("file1.txt"));
        try {
            StringBuilder sb = new StringBuilder();
            String line = br.readLine();

            while (line != null) {
                sb.append(line);
                sb.append(System.lineSeparator());
                line = br.readLine();
            }
            String everything = sb.toString();
        } finally {
            br.close();
        }          


    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new Reader().setVisible(true);

        }
    });
}

// Variables declaration - do not modify                    
private javax.swing.JLabel jLabel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextArea jTextArea1;
// End of variables declaration                  
}

Answer:

Move

BufferedReader br = new BufferedReader(new FileReader("file1.txt"));
try {
    StringBuilder sb = new StringBuilder();
    String line = br.readLine();

    while (line != null) {
        sb.append(line);
        sb.append(System.lineSeparator());
        line = br.readLine();
    }
    String everything = sb.toString();
} finally {
    br.close();
}         

Into your classes constructor, public Reader() {, then use jTextArea1.setText(sb.toString()) to apply the text to the JTexArea

public Reader() {
    initComponents();
    BufferedReader br = new BufferedReader(new FileReader("file1.txt"));
    try {
        StringBuilder sb = new StringBuilder();
        String line = br.readLine();

        while (line != null) {
            sb.append(line);
            sb.append(System.lineSeparator());
            line = br.readLine();
        }
        jTextArea1.setText(sb.toString())
    } finally {
        br.close();
    }         
}

Having said that, you're not really managing your resources well, consider using something more like...

try (BufferedReader myReader = new BufferedReader(new FileReader("file1.txt"))) {
    String text = null;
    while ((text = myReader.readLine()) != null) {
        jTextArea1.append(text + "\n");
    }
} catch (IOException exp) {
    exp.printStackTrace();
}

Or more simply...

try (Reader myReader = new BufferedReader(new FileReader("file1.txt"))) {
    jTextArea1.read(myReader, "Inventory");
} catch (IOException exp) {
    exp.printStackTrace();
}

Question:

JTextField's SetText method throws an exception whenever I try to set the contents while the field has focus. I need that to change, because I want to input a very precise number of characters, and once that character count is reached the field needs to be cleared while still having focus so the next set of characters can immediately be added without pushing any buttons.

I tried creating a static method that would re-create the text field from scratch every time it filled up, allowing a sort of recursive regeneration of the field each time. The method simply didn't do anything. For reference, basically everything in this program is static because it's a very simple application and I basically just want to access every important variable from "main".

Trying to set the text while the field has focus shows the following:

Exception in thread "AWT-EventQueue-0" java.lang.IllegalStateException: Attempt to mutate in notification
    at javax.swing.text.AbstractDocument.writeLock(Unknown Source)
    at javax.swing.text.AbstractDocument.replace(Unknown Source)
    at javax.swing.text.JTextComponent.setText(Unknown Source)
    at onlypack.ProgramMain$3.insertUpdate(ProgramMain.java:118)
    at javax.swing.text.AbstractDocument.fireInsertUpdate(Unknown Source)
    at javax.swing.text.AbstractDocument.handleInsertString(Unknown Source)
    at javax.swing.text.AbstractDocument.insertString(Unknown Source)
    at javax.swing.text.PlainDocument.insertString(Unknown Source)
    at javax.swing.text.AbstractDocument.replace(Unknown Source)
    at javax.swing.text.JTextComponent.replaceSelection(Unknown Source)
    at javax.swing.text.DefaultEditorKit$DefaultKeyTypedAction.actionPerformed(Unknown Source)
    at javax.swing.SwingUtilities.notifyAction(Unknown Source)
    at javax.swing.JComponent.processKeyBinding(Unknown Source)
    at javax.swing.JComponent.processKeyBindings(Unknown Source)
    at javax.swing.JComponent.processKeyEvent(Unknown Source)
    at java.awt.Component.processEvent(Unknown Source)
    at java.awt.Container.processEvent(Unknown Source)
    at java.awt.Component.dispatchEventImpl(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.KeyboardFocusManager.redispatchEvent(Unknown Source)
    at java.awt.DefaultKeyboardFocusManager.dispatchKeyEvent(Unknown Source)
    at java.awt.DefaultKeyboardFocusManager.preDispatchKeyEvent(Unknown Source)
    at java.awt.DefaultKeyboardFocusManager.typeAheadAssertions(Unknown Source)
    at java.awt.DefaultKeyboardFocusManager.dispatchEvent(Unknown Source)
    at java.awt.Component.dispatchEventImpl(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Window.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    at java.awt.EventQueue.access$500(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue$4.run(Unknown Source)
    at java.awt.EventQueue$4.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)

Answer:

you can't modify the document from inside a Document LIstener

Correct, you need to wait until the Document is in a state to accept input.

One way to do this is to wrap your code in the DocumentListener in a SwingUtilties.invokeLater(). This will place the code at the end of the Event Dispatch Thread and it will execute after the Document has finished updating itself.

Another option, instead of using a DocumentListener, it to use a DocumentFilter. This intercepts the text BEFORE it is added to the Document. So you could just simply clear the Document when the specified number of characters has been input. Read the section from the Swing tutorial on Implement a DocumentFilter for more information.

Question:

So here is my code, which displays a 9x9 grid:

import javax.swing.*;
import java.awt.*;

public class SudokuGrid extends JFrame {

private static final int ROWS = 9;
private static final int COLUMNS = 9;
int fontSize = 30;

public static void main(String[] args) {

  SudokuGrid makeSudokuGrid = new SudokuGrid();

} // end of main

// constructor SudokuGrid
public SudokuGrid() {

  JTextField[][] inputBoxes = new JTextField[ROWS][COLUMNS];
  Font font = new Font("Helvetica", Font.BOLD, fontSize);

  setLayout(new GridLayout(ROWS, COLUMNS));
  // set frame size
  setSize(400, 400);
  setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

  // outer loop to create the rows
  for (int rows = 0 ; rows < ROWS ; rows++) {

    // inner loop to create the columns
    for (int columns = 0 ; columns < COLUMNS ; columns++) {

      // make text fields empty
      inputBoxes[rows][columns] = new JTextField("");
      // add text fields to the frame
      add(inputBoxes[rows][columns]);
      // center text in each text box
      inputBoxes[rows][columns].setHorizontalAlignment(JTextField.CENTER);
      // apply font to each text box
      inputBoxes[rows][columns].setFont(font);

    } // end of columns loop

  } // end of rows loop

  // make frame visible
  getContentPane().setBackground(Color.RED);
  setVisible(true);

} // end of constructor SudokuGrid

} // end of class SudokuGrid

What I am trying to do is to draw a line every third row. So every third text box, there should be a thick line spanning all columns. Hope that makes sense.

Any help is greatly apprecaited. Thank you!


Answer:

The simple answer is, GridLayout isn't going to do what you want, it's simply not flexible enough, instead...

You could...

Change the layout manager and make use of a JSeparator

import java.awt.EventQueue;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class SudokuGrid {

    public static void main(String[] args) {
        new SudokuGrid();
    }

    public SudokuGrid() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public static class TestPane extends JPanel {

        private static final int ROWS = 9;
        private static final int COLUMNS = 9;
        int fontSize = 30;

        public TestPane() {
            JTextField[][] inputBoxes = new JTextField[ROWS][COLUMNS];
            Font font = new Font("Helvetica", Font.BOLD, fontSize);

            setLayout(new GridBagLayout());

            GridBagConstraints gbc = new GridBagConstraints();
            gbc.fill = GridBagConstraints.BOTH;
            gbc.weightx = 1;
            gbc.weighty = 1;
            gbc.gridy = 0;

            GridBagConstraints split = new GridBagConstraints();
            split.fill = GridBagConstraints.BOTH;
            split.weightx = 1;
            split.gridx = 0;
            split.gridwidth = GridBagConstraints.REMAINDER;

            // outer loop to create the rows
            for (int rows = 0; rows < ROWS; rows++) {

                gbc.gridy++;
                // inner loop to create the columns
                for (int columns = 0; columns < COLUMNS; columns++) {

                    gbc.gridx = columns;

                    // make text fields empty
                    inputBoxes[rows][columns] = new JTextField(1);
                    // add text fields to the frame
                    add(inputBoxes[rows][columns], gbc);
                    // center text in each text box
                    inputBoxes[rows][columns].setHorizontalAlignment(JTextField.CENTER);
                    // apply font to each text box
                    inputBoxes[rows][columns].setFont(font);

                } // end of columns loop

                if ((rows + 1) % 3 == 0) {
                    System.out.println("Split");
                    split.gridy = gbc.gridy + 1;
                    gbc.gridy += 2;
                    JSeparator sep = new JSeparator(JSeparator.HORIZONTAL);
                    add(sep, split);
                }

            } // end of rows loop
        }

    }

}
You could...

Make your own "split" component through the use of custom painting

public static class HorizontalSplit extends JPanel {

    public HorizontalSplit() {
        setOpaque(false);
    }

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(0, 3);
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g); 
        Graphics2D g2d = (Graphics2D) g.create();
        int y = (getHeight() - 3) / 2;
        BasicStroke stroke = new BasicStroke(3, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND);
        g2d.setStroke(stroke);
        g2d.drawLine(0, y, getWidth(), y);
        g2d.dispose();
    }

}

Which would simply replace the JSeparator...

if ((rows + 1) % 3 == 0) {
    System.out.println("Split");
    split.gridy = gbc.gridy + 1;
    gbc.gridy += 2;
    JPanel sep = new HorizontalSplit();
    add(sep, split);
}
You could...

Use a compound layout and a MatteLayout...

import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.MatteBorder;

public class SudokuGrid {

    public static void main(String[] args) {
        new SudokuGrid();
    }

    public SudokuGrid() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public static class TestPane extends JPanel {

        private static final int ROWS = 9;
        private static final int COLUMNS = 9;
        int fontSize = 30;

        public TestPane() {
            JTextField[][] inputBoxes = new JTextField[ROWS][COLUMNS];
            Font font = new Font("Helvetica", Font.BOLD, fontSize);

            setLayout(new GridBagLayout());

            GridBagConstraints groupContraint = new GridBagConstraints();
            groupContraint.fill = GridBagConstraints.BOTH;
            groupContraint.weightx = 1;
            groupContraint.weighty = 1;
            groupContraint.gridwidth = GridBagConstraints.REMAINDER;

            JPanel group = new JPanel(new GridLayout(3, COLUMNS));
            group.setBorder(new MatteBorder(0, 0, 1, 0, Color.BLACK));

            // outer loop to create the rows
            for (int rows = 0; rows < ROWS; rows++) {

                // inner loop to create the columns
                for (int columns = 0; columns < COLUMNS; columns++) {

                    // make text fields empty
                    inputBoxes[rows][columns] = new JTextField(1);
                    // add text fields to the frame
                    group.add(inputBoxes[rows][columns]);
                    // center text in each text box
                    inputBoxes[rows][columns].setHorizontalAlignment(JTextField.CENTER);
                    // apply font to each text box
                    inputBoxes[rows][columns].setFont(font);

                } // end of columns loop

                if ((rows + 1) % 3 == 0) {
                    add(group, groupContraint);
                    group = new JPanel(new GridLayout(3, COLUMNS));
                    group.setBorder(new MatteBorder(0, 0, 1, 0, Color.BLACK));
                }

            } // end of rows loop
        }

    }

}

Question:

I want to add a JTextField to the north region of a frame and a panel (which holds the copy of the same JTextField) to the east region.

But only the field in the north region appears. The panel in the east region is there but the problem is that the field isn't in the panel.

import java.awt.*;
import javax.swing.*;

public class Gui {

    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel panel = new JPanel();

        frame.getContentPane().setBackground(Color.BLACK);
        panel.setBackground(Color.YELLOW);

        JTextField field = new JTextField("Your name");

        panel.add(field);
        frame.add(BorderLayout.NORTH, field);
        frame.add(BorderLayout.EAST, panel);

        frame.setSize(300, 300);
        frame.setVisible(true);
       }
    }

Answer:

You need to have two seperate JTextField objects if you want two seperate fields: try adding

JTextField field2 = new JTextField("Your second field");

and change the first add() call on your frame to

frame.add(BorderLayout.NORTH, field2);

This will produce

which I assume is what you want.

Question:

I know this is a common question, but I'm trying to create a TextField that only accept int numbers, and it's almost done, here's the code:

Create textfield:

nome = new JFormattedTextField();
            nome.setHorizontalAlignment(SwingConstants.CENTER);
            nome.setColumns(2);

            DocumentFilter filtro = new FiltroNumero();
            ((AbstractDocument) nome.getDocument()).setDocumentFilter(filtro);

            panel.add(nome);

DocummentFilter:

public class FiltroNumero extends DocumentFilter{

    public void insertString(DocumentFilter.FilterBypass fb, int offset, int length,
              String text, javax.swing.text.AttributeSet attr)

              throws BadLocationException {
                    fb.insertString(offset, text.replaceAll("[^-0-9]", ""), attr);
         }  
}

With this, the TextField will only accept numbers and "-", but it means that "1-" is a possible value.

What I need is a way to make the textfield don't accept the minus after the first character.

If someone can help me, I'll be really glad :)


Answer:

You could simply get the entire text from the Document (which is the before replace), then create a new String from that document text, adding the text argument. Then just check against a complete regex that matches integers (negative or positive). If it matches, then do the replace. Something like:

@Override
public void replace(FilterBypass fb, int offs, int length,
        String str, AttributeSet a) throws BadLocationException {

    String text = fb.getDocument().getText(0,
            fb.getDocument().getLength());

    StringBuilder builder = new StringBuilder(text);
    builder.insert(offs, str);
    String newText = builder.toString();

    // check
    System.out.println("text = " + text 
                   + ", offset = " + offs 
                   + ", newText = " + newText);

    if (newText.matches("(-)?\\d*")) {
        super.replace(fb, offs, length, str, a);
    } else {
        Toolkit.getDefaultToolkit().beep();
    }
}

Note: you should be using replace rather than insertString, though doesn't hurt to override both.

Here's a complete demo

import java.awt.Toolkit;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;

public class FilterDemo {

    public FilterDemo() {
        JFrame frame = new JFrame();
        frame.add(createFilteredField());
        frame.pack();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationByPlatform(true);
        frame.setVisible(true);

    }

    private  JTextField createFilteredField() {
        JTextField field = new JTextField(10);
        AbstractDocument document = (AbstractDocument) field.getDocument();
        document.setDocumentFilter(new DocumentFilter() {

            @Override
            public void replace(FilterBypass fb, int offs, int length,
                    String str, AttributeSet a) throws BadLocationException {

                String text = fb.getDocument().getText(0,
                        fb.getDocument().getLength());

                StringBuilder builder = new StringBuilder(text);
                builder.insert(offs, str);
                String newText = builder.toString();

                // check
                System.out.println("text = " + text 
                               + ", offset = " + offs 
                               + ", newText = " + newText);

                if (newText.matches("(-)?\\d*")) {
                    super.replace(fb, offs, length, str, a);
                } else {
                    Toolkit.getDefaultToolkit().beep();
                }
            }


            @Override
            public void insertString(FilterBypass fb, int offs, String str,
                    AttributeSet a) throws BadLocationException {

                String text = fb.getDocument().getText(0,
                        fb.getDocument().getLength());

                StringBuilder builder = new StringBuilder(text);
                builder.insert(offs, str);
                String newText = builder.toString();

                // checks
                System.out.println("text = " + text 
                               + ", offset = " + offs 
                               + ", newText = " + newText);

                if (newText.matches("(-)?\\d*")) {
                    super.insertString(fb, offs, str, a);
                } else {
                    Toolkit.getDefaultToolkit().beep();
                }
            } 
        });
        return field;
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new FilterDemo();
            }
        });
    }
}

Question:

I'm trying to accept a user field in the form of a jTextArea (Search box). Then take this text and compare it against an ID OR Name and return if its inside of any.

  • Compare User Entry to ID
  • Compare User Entry to Name

Essentially check the user entry against a String and an Int.

I've got the following however am getting NumberFormatException.

String name = "Window";
int id = 12;
if (name.contains(searchText.getText().toLowerCase()) || id == Integer.valueOf(searchText.getText().replaceAll("[^0-9]", ""))) {
                    // TRUE STATEMENT
                }

So if a user enters "Win" it will return true. If they enter "test" it will return false. However if they enter "1","2" or "12" it will return true since the ID contains these.

I think I'm overthinking this one and could use some help. Thanks in advance


Answer:

 if (name.toLowerCase().contains(searchText.getText()) 
                    || Integer.toString(id).contains(searchText.getText())) {
                System.out.println("TRUE");
             }

Question:

I am making my own assistant program that connects to a bank management program i wrote. I want the user to be able to type into the command field: add $5 or add $10500 or any other amount. How would i calculate the "10500" while ignoring the "add $". The "add $" is used to check what command the user is typing to perform the action. This is what i have so far.

} else if (AssistantFrame.getCommand().equalsIgnoreCase("add $5")) {

        BankBalance.addToBalance(5);

}

This is the code that handles adding the money to the balance.

public static void addToBalance(int balanceAdd){

    Commands.setContinuity(0);

    if(fileBalance.exists()) {

            try {
                loadBalance();
            } catch (FileNotFoundException | UnsupportedEncodingException e) {

            }

            balance += balanceAdd;

            try {
                saveBalance();
            } catch (FileNotFoundException | UnsupportedEncodingException e) {

            }

            AssistantFrame.updateAssistant("Your balance has been succesfully updated.\nYour new balance is - $" + balance);

    } else {

        AssistantFrame.updateAssistant("Sorry, but you don't seem to have a personal\nbank balance created yet.");

    }

Answer:

Something like that:

String command = AssistantFrame.getCommand();
int amount = Integer.parseInt(command.replaceAll("[^\\d]",""));
BankBalance.addToBalance(amount);

Question:

I am creating a program to take in 1 or more 8 bit binary sequences and convert them into 12 bit hamming binary sequences. The code works and achieves everything right up until it tries to put the information into the JTextField at which point it converts the 8-bit stream into 1111 1111 and converts the 12 bit stream into 0000 0000 0000 (spacing for easier reading). I have tried stepping through the code and at every point it thinks the list is correct, right until i turn it into a string. Im not sure if im incorrectly using something but hopefully someone can help.

As an example for those who dont understand hamming codes. If you put in "10101010" no spaces, the system should spit out "Your original bit-stream was: 1010 1010 Your new Hamming bit-stream is: 1010 0101 1000"

But instead it will say "Your original bit-stream was: 1111 1111 Your new Hamming bit-stream is: 0000 0000 0000"

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Collections;

@SuppressWarnings("serial")
public class MainProgram extends JPanel {
private static final String INITIAL_TITLE = "Please enter your next 8 bits. "
        + "Do not enter more than 8 bits.\n"
        + "Press Enter when done";
private static final String ARE_YOU_FINISHED = "Are you finished entering streams?";
private static final String CALCULATING = "Just one moment while the code is generated...";
private static final String YES = "YES";
private static final String ENTER = "ENTER";
private static final String NO = "NO";
private static final String CONTINUE = "CONTINUE";
private static int GAP = 12;
private static final int COLUMNS = 35;
private static  int TEMP_STREAM = 0;
static int numberOfStreams = 0;
static int counter = 0;
static String OriBuild;
static String NewBuild;

// this is a JTextArea built to look like a JLabel
private JTextArea topTextArea = new JTextArea(2, COLUMNS);
private JTextField dataEntryField = new JTextField(COLUMNS);
private JTextArea dataPrinter = new JTextArea(2,2);
private JButton yesEnterButton = new JButton(ENTER);
private JButton noButton = new JButton(NO);
private JButton contButton = new JButton(CONTINUE);

private boolean enteringData = true;
private boolean dataValidYet = false;

java.util.List<Integer> streamSplit = new ArrayList<>();
java.util.List<Integer> tempEight = new ArrayList<>();
java.util.List<Integer> finalStream = new ArrayList<>();

public MainProgram(){
    yesEnterButton.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            yesEnterButtonActionPerfromed(e);
        }
    });

    noButton.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            noButtonActionPerfromed(e);
        }
    });

    contButton.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            contButtonActionPerfromed(e);
        }
    });

    topTextArea.setWrapStyleWord(true);
    topTextArea.setLineWrap(true);
    topTextArea.setFocusable(false);
    topTextArea.setEditable(false);
    topTextArea.setOpaque(false);
    topTextArea.setText(INITIAL_TITLE);

    JPanel innerButtonPanel = new JPanel(new GridLayout(1, 0, GAP, 0));
    innerButtonPanel.add(yesEnterButton);
    innerButtonPanel.add(contButton);
    innerButtonPanel.add(noButton);
    contButton.setVisible(false);
    noButton.setVisible(false);
    JPanel outerButtonPanel = new JPanel();
    outerButtonPanel.add(innerButtonPanel);

    setBorder(BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP));
    setLayout(new BorderLayout(GAP, GAP));
    add(topTextArea, BorderLayout.PAGE_START);
    add(dataEntryField, BorderLayout.LINE_END);
    dataPrinter.setVisible(false);
    add(dataPrinter, BorderLayout.LINE_START);
    add(outerButtonPanel, BorderLayout.PAGE_END);

}

protected void noButtonActionPerfromed(ActionEvent e) {
    if(!dataValidYet){
        enteringData = true;
        topTextArea.setText(INITIAL_TITLE);
        noButton.setVisible(false);
        dataEntryField.setVisible(true);
        return;
    }
    // Pressing no allows more entry
}

private void yesEnterButtonActionPerfromed(ActionEvent e) {
    if (enteringData) {
        topTextArea.setText(ARE_YOU_FINISHED);
        yesEnterButton.setText(YES);
        yesEnterButton.setActionCommand(YES);
        noButton.setVisible(true);
        TEMP_STREAM = checkInput();
        enteringData = false;
        dataEntryField.setText("");
        dataEntryField.setVisible(false);
        streamAdd();//This function adds the stream (example: 10101010) to a list creating individual digits of 1,0,1,0,1,0,1,0
        return;
    }//pressing enter takes the value in box. Pressing yes causes the system to move on
    else{
        dataValidYet = true;
        yesEnterButton.setVisible(false);
        noButton.setVisible(false);
        logicLaunch();//converts the 8 digit binary into a 12 digit hamming code
        contButton.setVisible(true);
    }

}

private void contButtonActionPerfromed(ActionEvent e) {
    //This groups the 8 original individual digits, that were seperated into a list, back into a string for printing purposes
    if(counter < numberOfStreams) {
        dataPrinter.setVisible(true);
        dataEntryField.setVisible(false);
        OriBuild = ("Your original bit-stream was: "
                + streamSplit.get(counter * 0)
                + streamSplit.get(counter * 1)
                + streamSplit.get(counter * 2)
                + streamSplit.get(counter * 3) + " "
                + streamSplit.get(counter * 4)
                + streamSplit.get(counter * 5)
                + streamSplit.get(counter * 6)
                + streamSplit.get(counter * 7));
        NewBuild = ("Your new Hamming bit-stream is: "
                //This groups the 12 new individual digits, that were seperated into a list, back into a string for printing purposes
                + finalStream.get(counter * 0)
                + finalStream.get(counter * 1)
                + finalStream.get(counter * 2)
                + finalStream.get(counter * 3) + " "
                + finalStream.get(counter * 4)
                + finalStream.get(counter * 5)
                + finalStream.get(counter * 6)
                + finalStream.get(counter * 7) + " "
                + finalStream.get(counter * 8)
                + finalStream.get(counter * 9)
                + finalStream.get(counter * 10)
                + finalStream.get(counter * 11));
        System.out.println(OriBuild + " " + NewBuild);
        dataPrinter.setText(OriBuild + "\n" + NewBuild);
        counter++;
        //Prints the strings to the screen so that the user can retrieve wanted information. Then adds 1 to the counter incase more than 1 stream was entered to cycle
    } else {
        dataPrinter.setText("Program complete. Close and relaunch to re-use");
        contButton.setVisible(false);
        //Once out of streams program finishes on this informing user that its reached the end of its usefulness and require re-launching.
    }
}

private static void createAndShowGui() {
    MainProgram mainPanel = new MainProgram();

    JFrame frame = new JFrame("HammingCode");
    frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    frame.getContentPane().add(mainPanel);
    frame.pack();
    frame.setLocationByPlatform(true);
    frame.setVisible(true);
}

public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            createAndShowGui();
        }
    });
}

public int checkInput()
{
    String temp1 = dataEntryField.getText();
    int temp = Integer.parseInt(temp1);
    return temp;
}

public void streamAdd(){
    do {
        streamSplit.add(TEMP_STREAM % 10);
        TEMP_STREAM /= 10;
    } while (TEMP_STREAM != 0);
}

public void logicLaunch(){
    topTextArea.setText(CALCULATING);
    int arrayLength = streamSplit.size();
    int bufferLength = 8 - arrayLength % 8;

    if (bufferLength != 8)
    {
        numberOfStreams = arrayLength / 8 + 1;
    } else
    {
        numberOfStreams = arrayLength / 8;
    }
    int tempStreams = numberOfStreams;
    System.out.println(numberOfStreams + "<Streams Buffer>" + bufferLength);
    while (bufferLength > 0 && bufferLength != 8)
    {
        streamSplit.add(0);
        bufferLength--;
    }
    while (tempStreams > 0)
    {
        for (int i = 0; i < 8; i++)
        {
            tempEight.add(streamSplit.get(i));
        }
        if ((tempEight.get(0) + tempEight.get(1) + tempEight.get(3) + tempEight.get(4) + tempEight.get(6)) % 2 == 0)
        {
            tempEight.add(0, 0);
        } else
        {
            tempEight.add(0, 1);
        }
        if ((tempEight.get(1) + tempEight.get(3) + tempEight.get(4) + tempEight.get(6) + tempEight.get(7)) % 2 == 0)
        {
            tempEight.add(1, 0);
        } else
        {
            tempEight.add(1, 1);
        }
        if ((tempEight.get(3) + tempEight.get(4) + tempEight.get(5) + tempEight.get(9)) % 2 == 0)
        {
            tempEight.add(3, 0);
        } else
        {
            tempEight.add(3, 1);
        }
        if ((tempEight.get(7) + tempEight.get(8) + tempEight.get(9) + tempEight.get(10)) % 2 == 0)
        {
            tempEight.add(7, 0);
        } else
        {
            tempEight.add(7, 1);
        }
        tempStreams--;
        for (int i = 0; i < 12; i++)
        {
            finalStream.add(tempEight.get(0));
            tempEight.remove(0);
        }
    }
    Collections.reverse(streamSplit);
}//Runs all the logic to generate the 12 bit code, this part is working     fine. Reverse is for formatting purposes
}

Answer:

I haven't figured out the code entirely, but it appears your use of counter in contButtonActionPerfromed is incorrect. When counter is 0, it will get element 0 every time; when 1 it will get 0, 1, 2, etc.; when 2 it will get 0, 2, 4, etc. Then there's something about exiting the program after the first time, so maybe you don't go through it a second time (and a third time would likely generate an error attempting to access a non-existent element).

You really ought to be able to debug that method...

Question:

I have a class which only allows integers with limited amount. The problem is, class is doing its work but when I use multiple objects, it only takes the last objects limitation number and applies to others.

I also couldn't get rid of static warnings.

Code is ;

public class LimitedIntegerTF extends JTextField {

    private static final long serialVersionUID = 1L;
    private static int limitInt;
    public LimitedIntegerTF() {
        super();
    }

    public LimitedIntegerTF(int limitInt) {
        super();
        setLimit(limitInt);
    }

    @SuppressWarnings("static-access")
    public final void setLimit(int newVal) 
    {
        this.limitInt = newVal;
    }

    public final int getLimit() 
    {
        return limitInt;
    }

    @Override
    protected Document createDefaultModel() {
        return new UpperCaseDocument();
    }

    @SuppressWarnings("serial")
    static class UpperCaseDocument extends PlainDocument {

        @Override
        public void insertString(int offset, String strWT, AttributeSet a)
                throws BadLocationException {

            if(offset < limitInt){
                if (strWT == null) {
                    return;
                }

                char[] chars = strWT.toCharArray();
                boolean check = true;

                for (int i = 0; i < chars.length; i++) {

                    try {
                        Integer.parseInt(String.valueOf(chars[i]));
                    } catch (NumberFormatException exc) {
                        check = false;
                        break;
                    }
                }

                if (check)
                    super.insertString(offset, new String(chars),a);

            }
        }
    }
}

How I call it on another class ;

final LimitedIntegerTF no1 = new LimitedIntegerTF(5);
final LimitedIntegerTF no2 = new LimitedIntegerTF(7);
final LimitedIntegerTF no3 = new LimitedIntegerTF(10);

The result is no1, no2, and no3 has (10) as a limitation.

Example:
no1: 1234567890 should be max len 12345
no2: 1234567890 should be max len 1234567
no3: 1234567890 it's okay

Answer:

It's because your limitInt is static, which means it has the same value for all instances of that class (What does the 'static' keyword do in a class?). Make it non-static, and each instance of your class will have their own value for it.

If you want to use limitInt in the inner class UpperCaseDocument, then make that class non-static as well. However, if you do that, each instance of UpperCaseDocument will also have an instance of LimitedIntegerTF associated with it.

Question:

I am receiving the following error when running my code.

error: incompatible types: double cannot be converted to JTextField

JGrasp is pointing to the following as the issue.

Programming6_4.Java:143: error: incompatible types: double cannot be converted to JTextField averageScoreTF = (test1 * wght1 + test2 * wght2 + test3 * wght3 + test4 * wght4); ^ 1 error

Not sure why it is flagging the '+' as the item that cannot be converted. Any assistance would be appreciated.

import java.awt.*;
import java.awt.event.*;
import java.awt.FlowLayout;
import javax.swing.*;
import javax.swing.JFrame;
import javax.swing.JLabel;

   public class Programming6_4 extends JFrame
   {
      //declares variables
      private JLabel blankGrid1L, blankGrid2L, blankGrid3L, scoreL, weightL, testOneL, testTwoL, testThreeL, testFourL, averageScoreL;

      private JTextField  testOneTF, testTwoTF, testThreeTF, testFourTF, testOnewTF, testTwowTF, testThreewTF, testFourwTF, averageScoreTF;

      private JButton calculateScoreB, exitB;

      private CalculateButtonHandler cbHandler;

      private ExitButtonHandler ebHandler;

      //declare window size
      private static final int WIDTH = 400;
      private static final int HEIGHT = 200;

      public Programming6_4()
      {
         //name labels
         blankGrid1L = new JLabel ("", SwingConstants.CENTER);
         blankGrid2L = new JLabel ("", SwingConstants.CENTER);
         blankGrid3L = new JLabel ("", SwingConstants.CENTER);
         scoreL = new JLabel ("Score", SwingConstants.CENTER);
         weightL = new JLabel ("Weight", SwingConstants.CENTER);
         testOneL = new JLabel ("Test One Score: ", SwingConstants.CENTER);
         testTwoL = new JLabel ("Test Two Score: ", SwingConstants.CENTER);
         testThreeL = new JLabel ("Test Three Score: ", SwingConstants.CENTER);
         testFourL = new JLabel ("Test Four Score: ", SwingConstants.CENTER);
         averageScoreL = new JLabel ("Average Weighted Test Score: ", SwingConstants.CENTER);

         //create text fields 10 characters - Test Scores
         testOneTF = new JTextField(10);
         testTwoTF = new JTextField(10);
         testThreeTF = new JTextField(10);
         testFourTF = new JTextField(10);

         //create text fields 10 charaters - Weights
         testOnewTF = new JTextField(10);
         testTwowTF = new JTextField(10);
         testThreewTF = new JTextField(10);
         testFourwTF = new JTextField(10);
         averageScoreTF = new JTextField(10);

         //create buttons and handler
         calculateScoreB = new JButton ("Calculate");
         cbHandler = new CalculateButtonHandler();
         calculateScoreB.addActionListener(cbHandler);

         exitB = new JButton ("Exit");
         ebHandler = new ExitButtonHandler();
         exitB.addActionListener(ebHandler);

         //set grid size
         Container pane = getContentPane();
         pane.setLayout(new GridLayout (7, 3));

         //add elements to grid spaced by line
         pane.add (blankGrid1L);
         pane.add (scoreL);
         pane.add (weightL);

         pane.add (testOneL);
         pane.add (testOneTF);
         pane.add (testOnewTF);

         pane.add (testTwoL);
         pane.add (testTwoTF);
         pane.add (testTwowTF);

         pane.add (testThreeL);
         pane.add (testThreeTF);
         pane.add (testThreewTF);

         pane.add (testFourL);
         pane.add (testFourTF);
         pane.add (testFourwTF);

         pane.add (averageScoreL);
         pane.add (averageScoreTF);
         pane.add (blankGrid2L);

         pane.add (calculateScoreB);
         pane.add (blankGrid3L);
         pane.add (exitB);

         //set window title, window, and display
         setTitle ("Weighted Test Average Calculation");
         setSize (WIDTH, HEIGHT);
         setVisible (true);
         setDefaultCloseOperation (EXIT_ON_CLOSE);
         //setLayout (new Programming6_4());
      }
         //activates ActionListener
      private class CalculateButtonHandler implements ActionListener

         //Main calculation program
      {
      public void actionPerformed (ActionEvent e)  //public static void main (String[] args)
         {
            //declare varibles in 
            double test1, test2, test3, test4, wght1, wght2, wght3, wght4, avgscore /*avg1, avg2, avg3, avg4*/;

            //takes text entered by user and converts from string to decimal
            test1 = Double.parseDouble(testOneTF.getText());
            wght1 = Double.parseDouble(testOnewTF.getText());
            test2 = Double.parseDouble(testTwoTF.getText());
            wght2 = Double.parseDouble(testTwowTF.getText());
            test3 = Double.parseDouble(testThreeTF.getText());
            wght3 = Double.parseDouble(testThreewTF.getText());
            test4 = Double.parseDouble(testFourTF.getText());
            wght4 = Double.parseDouble(testFourwTF.getText());

            //calculations needed to get weighted average
            //avg1 = test1 * wght1;
            //avg2 = test2 * wght2;
            //avg3 = test3 * wght3;
            //avg4 = test4 * wght4;
            //avgscore = avg1 + avg2 + avg3 + avg4;

            averageScoreTF = (test1 * wght1 + test2 * wght2 + test3 * wght3 + test4 * wght4);
            averageScoreTF.setText("" + avgscore);
         }
      }

      private class ExitButtonHandler implements ActionListener
         {
            public void actionPerformed (ActionEvent e)
               {
                  System.exit(0);
               }
         }

      public static void maine (String[]args)
         {
            Programming6_4 testObject = new Programming6_4();
         }
   }

Answer:

Change this lines:

averageScoreTF = (test1 * wght1 + test2 * wght2 + test3 * wght3 + test4 * wght4);

to:

avgscore = (test1 * wght1 + test2 * wght2 + test3 * wght3 + test4 * wght4);

You cannot assign a double to averageScoreTF since averageScoreTF is not a numeric type (just like the error message said).

Question:

I am trying to compare value in JTextField for a validation part, to make sure user can not save progress if all TextFields don't have a value.

This Is my Method for Text Fields.

public void DrawBookAttributes() {
    lblBookName = new JLabel("Book Name :");
    lblBookName.setFont(getLblFont());
    lblBookName.setSize(140, 20);
    lblBookName.setLocation(280, 150);
    menuFrame.add(lblBookName);

    tfBookName = new JTextField();
    tfBookName.setSize(140, 20);
    tfBookName.setLocation(420, 150);
    menuFrame.add(tfBookName);

    lblBookID = new JLabel("Book ID :");
    lblBookID.setFont(getLblFont());
    lblBookID.setSize(140, 20);
    lblBookID.setLocation(280, 50);
    menuFrame.add(lblBookID);

    tfBookID = new JTextField();
    tfBookID.setSize(140, 20);
    tfBookID.setLocation(420, 50);
    tfBookID.setText("hello");
    tfBookID.setEditable(false);
    menuFrame.add(tfBookID);

    JLabel lblBookCost = new JLabel("Cost (£) :");
    lblBookCost.setFont(getLblFont());
    lblBookCost.setSize(140, 20);
    lblBookCost.setLocation(280, 200);
    menuFrame.add(lblBookCost);

    tfBookCost = new JTextField();
    tfBookCost.setSize(140, 20);
    tfBookCost.setLocation(420, 200);
    tfBookCost.addKeyListener(this);
    menuFrame.add(tfBookCost);

    lblBookYearOfPublication = new JLabel("Publication Date :");
    lblBookYearOfPublication.setSize(140, 20);
    lblBookYearOfPublication.setLocation(280, 250);
    lblBookYearOfPublication.setFont(getLblFont());
    menuFrame.add(lblBookYearOfPublication);

    JTextField tfBookYearOfPublication = new JTextField();
    tfBookYearOfPublication.setSize(140, 20);
    tfBookYearOfPublication.setLocation(420, 250);
    tfBookYearOfPublication.setText("DD-MM-YYYY");
    tfBookYearOfPublication.addActionListener(this);
    menuFrame.add(tfBookYearOfPublication);

    JLabel lblbookPublishngHouse = new JLabel("Publishing Orgaisation :");
    lblbookPublishngHouse.setSize(140, 20);
    lblbookPublishngHouse.setLocation(280, 300);
    lblbookPublishngHouse.setFont(getLblFont());
    menuFrame.add(lblbookPublishngHouse);

    JTextField tfBookPublishingHouse = new JTextField();
    tfBookPublishingHouse.setSize(140, 20);
    tfBookPublishingHouse.setLocation(420, 300);
    menuFrame.add(tfBookPublishingHouse);

    JLabel lblBookISBN = new JLabel("ISBN :");
    lblBookISBN.setSize(140, 20);
    lblBookISBN.setLocation(280, 350);
    lblBookISBN.setFont(getLblFont());
    menuFrame.add(lblBookISBN);

    JTextField tfBookISBN = new JTextField();
    tfBookISBN.setSize(140, 20);
    tfBookISBN.setLocation(420, 350);
    menuFrame.add(tfBookISBN);

    JLabel lblBookPages = new JLabel("Number of Pages :");
    lblBookPages.setSize(140, 20);
    lblBookPages.setLocation(280, 400);
    lblBookPages.setFont(getLblFont());
    menuFrame.add(lblBookPages);

    JTextField tfBookPages = new JTextField();
    tfBookPages.setSize(140, 20);
    tfBookPages.setLocation(420, 400);
    menuFrame.add(tfBookPages);

    menuFrame.setVisible(true);
}

And This is Validation part

    public void EntryCheck() {

        if (tfBookName.getText().equals("")) {
            EntryChecker++;
            System.out.println(EntryChecker);
        }
        if (tfBookISBN.getText().equals("")) {
            EntryChecker++;
        }
        if (tfBookCost.getText().equals("")) {
            EntryChecker++;
        }
        if (tfBookPages.getText().equals("")) {
            EntryChecker++;
        }
        if (tfBookPublishingHouse.getText().equals("")) {
            EntryChecker++;
        }
        if (tfBookYearOfPublication.getText().equals("")) {
            EntryChecker++;
        }
        if (tfBookCost.getText().equals("DD-MM-YYY")) {
            EntryChecker++;
        }
        System.out.println(EntryChecker);
}

EntryChecker is an Integer, I am Adding a value to it each time when user left TextField without Entering information in it.

Every time I debug the program, I am facing NullPointerException in this Validation Line.

if (tfBookISBN.getText().equals("")) {
        EntryChecker++; 

Any one have Idea where is the problem and how to fix it?

Thank you!


Answer:

If -as you sayin comments- you have

private JTextField tfBookISBN = new JTextField();

global scope in your class, then you have to remove that line

JTextField tfBookISBN = new JTextField();

from DrawBookAttributes()

in case it's not initialized (i think its not) at declaration, you need to keep that line in DrawBookAttributes() but as initialize, not declare, as below:

tfBookISBN = new JTextField();

because you are creating a new field in the method, and leaving the global one uninitialized which creates a NPE when EntryCheck() tries to access that object to invoke getText().

Question:

I am creating a GUI with some JCheckButtons (bold italic), these buttons will turn the text in the text field to bold, italic or both when selected through the use of action listeners. Here is how I implement this functionality in my action listener methods (this is for the bold method, I also have similar methods for italic and bold and italic).

class Bold implements ActionListener {

    private final FontSetter fontSetter;
    private final JTextField textfield;

    Bold(FontSetter fontSetter, JTextField textfield) {
        this.fontSetter = fontSetter;
        this.textfield = textfield;
    }

    Font font = new Font(textfield.getText(), Font.BOLD,12);

    public void actionPerformed(ActionEvent e) {
        fontSetter.setBold();
        textfield.setFont(font);
    }

}

error: the blank final field textfield may not have been initialised,how can I fix this?


Answer:

You have to initialize the textfield variable first before you use it. Since you have defined font as another instance variable, the reference to textfield may not have been initialized yet.

One possible approach is to initialize font on construction since it is dependent on textfield:

private final JTextField fontSetter;
private final JTextField textfield;
private final Font font;

Bold(JTextField fontSetter, JTextField textfield) {
    this.fontSetter = fontSetter;
    this.textfield = textfield;
    this.font = new Font(textfield.getText(), Font.BOLD, 12);
}

Question:

I'm working on shortest path alghoritm, and wanted to create a gui version for my program. This is my method creating fields to input distances between vertices. When all JTextFields are filled I want to convert all of it into two dimensional array and here is my problem. How to read all values from n amount of JTextFields if they're all created on the same variable which is tekst in my case.

void Wypelnij() {
int n = 1;
int x = 0;
for (int i = 1; i <= wierzcholki; i++) {

    if (x == 0) {
        mojPanel.add(new JLabel(""));
        for (int j = 1; j <= wierzcholki; j++) {
            if (n == wierzcholki) {
                mojPanel.add(new JLabel("" + j), "wrap");
                n = 1;
                x = 1;
            } else {
                mojPanel.add(new JLabel("" + j));
                n++;
            }
        }
    }
    mojPanel.add(new JLabel("" + i));
    for (int j = 1; j <= wierzcholki; j++) {
        JTextField tekst = new JTextField();
        tekst.setPreferredSize(new Dimension(20, 20));
        if (n == wierzcholki) {
            mojPanel.add(tekst, "wrap");
            n = 1;
        } else {
            mojPanel.add(tekst);
            n++;

        }
        if (i == j) {
            tekst.setText("0");
            tekst.setHorizontalAlignment(JTextField.CENTER);
            tekst.setEditable(false);
        }
    }
}

Answer:

You can create a List<JTextField> and iterate over that list to get text from all the JTextFields.

Other way is, you can use Components[] JPanel#getComponents() to get all components of panel(i.e. Container) and iterate over the components to read from the JTextFields. But in this case your panel may contain other components(better to use separate panel for JTextFields) and moreover you need to cast Component to JTextField. But, you can iterate over Components[] based on the indexes on which you have added JTextFields in your panel.

Question:

Perhaps this was already asked once but I am kinda stuck and cant find a solution by myself. I got text from first button using text fields. And now i need to get this text into second button OR text file.

Code below and i know that this one gives error.

System.out.println("Author's name: " + newauthor());
System.out.println("Book name: " + newbook());

import java.awt.GridLayout;
import java.awt.event.*;
import java.io.FileNotFoundException;
import javax.swing.*;

public class library extends JFrame 
{

private JPanel pnl;

public library() throws FileNotFoundException {

    pnl = (JPanel) getContentPane();
    JPanel panel = new JPanel();
    getContentPane().add(panel);

    panel.setLayout(null);

    JButton addbutton = new JButton("Add new book");
    addbutton.setBounds(75, 30, 150, 30);
    addbutton.addActionListener(new ActionListener() 
    {
        public void actionPerformed(ActionEvent event) 
        {
            JTextField authorfield = new JTextField(15);
            JTextField bookField = new JTextField(15);
            JPanel mypanel = new JPanel(new GridLayout(0, 1));
            mypanel.add(new JLabel("Type Author's Name and Book name:"));
            mypanel.add(new JLabel("Author's Name:"));
            mypanel.add(authorfield);
            mypanel.add(new JLabel("Book name:"));
            mypanel.add(bookField);


            int result = JOptionPane.showConfirmDialog(null, mypanel, 
            "Add a new book", JOptionPane.OK_CANCEL_OPTION);
            if (result == JOptionPane.OK_OPTION) 
                {
                String newauthor = authorfield.getText();
                String newbook = bookField.getText();
                if (!newauthor.isEmpty() && !newbook.isEmpty()) 
                        {       
                                JOptionPane.showMessageDialog(pnl, "Book "+bookField.getText()+"\nAuthor "+authorfield.getText()+"\nSuccessfully added to the list.",
                                "Book was added.", JOptionPane.INFORMATION_MESSAGE);


                        }
                else    
                        {
                                JOptionPane.showMessageDialog(pnl, "Both must be filled!",
                                "Error", JOptionPane.ERROR_MESSAGE);
                        }
                }
       }                
    });
    panel.add(addbutton);


    JButton listbutton = new JButton("List");
    listbutton.setBounds(75, 60, 150, 30);
    panel.add(listbutton);
    addbutton.addActionListener(new ActionListener() 
        {
            public void actionPerformed(ActionEvent event) 
                {

                        System.out.println("Author's name: " + newauthor());
                        System.out.println("Book name: " + newbook());
                }
        });
       JButton deletebutton = new JButton("Delete");
       deletebutton.setBounds(75, 90, 150, 30);
       panel.add(deletebutton);



       setTitle("Library Menu");
       setSize(300, 200);
       setLocationRelativeTo(null);
       setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    public static void main(String[] args) throws FileNotFoundException {
           library ex = new library();
           ex.setVisible(true);
    }
}

Answer:

Your code is having many issues.

1.Both should be declared inside of your class but outside of your any method.

String newauthor = "";
String newbook = "";

Now in the if condition

         if (result == JOptionPane.OK_OPTION) 
                {
                newauthor = authorfield.getText();
                newbook = bookField.getText();
                ..............................

2.

JButton listbutton = new JButton("List");
listbutton.setBounds(75, 60, 150, 30);
panel.add(listbutton);
listbutton.addActionListener(new ActionListener()// its listbutton not addbutton
    {
        public void actionPerformed(ActionEvent event) 
            {

                    System.out.println("Author's name: " + newauthor);
                    System.out.println("Book name: " + newbook);
            }
    });

Both newauthor and newbook are variables. But not methods.

Question:

I'm pretty new to Java and I thought I'd try to get my hands dirty and make a GUI but I can't seem to get it to work the way I want it to.

I wrote some code thinking that if I press the "Add" button on the GUI then a new JTextField will appear underneath where all the other textfields are but that doesn't happen. Only one new JTextField does appear but it appears next to my Add button instead of underneath all the other textfields I have and if I press it again, nothing happens. I tried playing around with other variables but it just doesn't seem to be working properly. I feel like something is wrong with my ActionListener but I don't know what.

public class TheGUI extends JFrame{
    List<JTextField> listOfTextFields = new ArrayList<JTextField>();

    private JTextField desc1;
    private JTextField instruct;
    private JTextField desc2;
    private JButton submit;
    private JButton addNew;

    public TheGUI() { //My GUI with the default fields & buttons that should be on there.
        super("Chili");
        setLayout(new GridBagLayout());
        GridBagConstraints c = new GridBagConstraints();


        instruct = new JTextField("Choose your words");
        instruct.setEditable(false);
        c.fill = GridBagConstraints.HORIZONTAL;
        c.weightx = 0.5;
        c.gridx = 0;
        c.gridy = 0;
        add(instruct, c);

        addNew = new JButton("Add");
        c.weightx = 0.0;
        c.gridx = 1;
        c.gridy = 0;
        add(addNew, c);

        submit = new JButton("Submit!");
        c.weightx = 0.5;
        c.gridwidth = 2;
        c.gridx = 0;
        c.gridy = GridBagConstraints.PAGE_END;
        add(submit, c);

        desc1 = new JTextField(10);
        c.fill = GridBagConstraints.HORIZONTAL;
        c.weightx = 0.5;
        c.gridwidth = 2;
        c.gridx = 0;
        c.gridy = 1;
        add(desc1, c);

        desc2 = new JTextField(10);
        c.fill = GridBagConstraints.HORIZONTAL;
        c.weightx = 0.5;
        c.gridwidth = 2;
        c.gridx = 0;
        c.gridy = 2;
        add(desc2, c);

        addNew.addActionListener(new Adder());


        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(300,300);
        setVisible(true);

    }

    private class Adder implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent event) {

            int i = 0;
            listOfTextFields.add(new JTextField());
            GridBagConstraints textFieldConstraints = new GridBagConstraints();

             //Give it a max of 9 text fields that can be created.
            while(i < 10) {
                textFieldConstraints.fill = GridBagConstraints.HORIZONTAL;
                textFieldConstraints.weightx = 0.5;
                textFieldConstraints.gridx = 0;
                textFieldConstraints.gridwidth = 2;
                textFieldConstraints.gridy = 3 + i;
                i++;

            }

            add(listOfTextFields.get(i), textFieldConstraints);
            revalidate();
            repaint();


        }

    }


}


Answer:

Your while loop is really strange.

Your ActionListener should look like:

 private class Adder implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent event) {
            if (listOfTextFields.size() == 9) {
                // Give it a max of 9 text fields that can be created.
                return;
            }

            JTextField textfield = new JTextField();

            listOfTextFields.add(textfield);
            GridBagConstraints textFieldConstraints = new GridBagConstraints();
            textFieldConstraints.fill = GridBagConstraints.HORIZONTAL;
            textFieldConstraints.weightx = 0.5;
            textFieldConstraints.gridx = 0;
            textFieldConstraints.gridwidth = 2;
            textFieldConstraints.gridy = 3 + listOfTextFields.size();

            add(textfield, textFieldConstraints);

            revalidate();
            repaint();

        }

    }

Question:

I have a number of buttons, that when clicked on will run a script and if successful will generate a Passed/Failed message displayed in a text field on a GUI using Swing. I have noticed that the text for the previous result is still displayed even after clicking on a new button to run a script. This text is displayed until the script has completed, generating a new result which is then displayed.

I would like to add some code so that when a new button is clicked the text field is reset and no text is displayed until the script has completed.

A button:

    Test1 = new JButton("Test1");
    Test1.setLocation(290, 30);
    Test1.setSize(120, 30);
    Test1.addActionListener(this);
    Test1.addMouseListener(new MouseAdapter() {
        public void mouseClicked(java.awt.event.MouseEvent e) {
            if (Test1.isEnabled()) {
                errorLabel.setText("");
                result = JUnitCore.runClasses(Test1.class);
                errorMessageDisplay(result);
            }
        }
    });
    buttonPanel.add(Test1);

The code for the error message:

public void errorMessageDisplay(Result resultPass) {
    errorLabel.addMouseListener(new MouseAdapter(){
        @Override
        public void mouseClicked(MouseEvent e){
            errorLabel.setText("");
            errorLabel.setVisible(true);
        }
    });


    if (result.getFailureCount() > 0) {
        errorLabel.setForeground(Color.red);
        errorLabel.setVisible(true);
        errorLabel.setText(" Failed");
    }

    else {
        errorLabel.setForeground(Color.green);
        errorLabel.setText(" Passed");
        errorLabel.setVisible(true);
    }
}

Answer:

The simplest solution is to create another thread.

if (Test1.isEnabled()) {
    errorLabel.setText("");
    new Thread(()->{
        Result result = JUnitCore.runClasses(Test1.class);
        EventQueue.invokeLater(()->errorMessageDisplay(result));
    }).start();
}

That is not a very good solution, look into using a SwingWorker or an ExecutorService.

A quick example of using an executor service would be to create an executor when you start.

ExecutorService service = Executors.newSingleThreadExecutor();

Then submit jobs to it.

if (Test1.isEnabled()) {
    errorLabel.setText("");
    service.submit(()->{
        Result result = JUnitCore.runClasses(Test1.class);
        EventQueue.invokeLater(()->errorMessageDisplay(result));
    });
}

This would allow you to submit more than one job, but they would be run serially. You can control the job flow through the gui too.

if (Test1.isEnabled()) {
    test1.setEnabled(false);
    errorLabel.setText("");
    service.submit(()->{
        Result result = JUnitCore.runClasses(Test1.class);
        EventQueue.invokeLater(()->{
            errorMessageDisplay(result);
            test1.setEnabled(true);
        });
    });
}

Question:

I'm trying to create a hangman game where dashes will display for the user and if they click on the correct button, a letter will replace the dashes. This worked when I was using the console to output all the data, but after I changed to GUI, it wouldn't work no matter what I tried. It seems that the JTextField won't accept a character array.

    private static JTextField txtDashes;
    static char [] dashes = {'-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-'};

            txtDashes = new JTextField();
            txtDashes.setBackground(Color.GRAY);
            txtDashes.setHorizontalAlignment(SwingConstants.CENTER);
            txtDashes.setBorder(javax.swing.BorderFactory.createEmptyBorder());
            txtDashes.setBounds(39, 207, 218, 46);
            gameScreen.add(txtDashes);
            txtDashes.setColumns(10);

            for (int i = 0; i < dashes.length; i++){
                   txtDashes.setText(dashes[i]); //Error occurs here
            } //End of for loop

I'm only experienced in about 5 months of java coding and can't seem to find a solution for this problem.


Answer:

you should pass a String to setText() method dashes is a char array.you can't set a char to a textfield .you have to convert char to String first

use

txtDashes.setText(String.valueOf(dashes[i])); 

or

txtDashes.setText(dashes[i] + ""); 

edit


setText() replace exiting text and set new text.if you want to show all array chars, first append it to a string throw a loop and from outside of loop setText()

like this

String s="";
for (int i = 0; i < dashes.length; i++){
    s+=dashes[i];
} 
txtDashes.setText(s); 

note .string append inside a loop is not good you can use StringBuilder for that

Question:

okay i have no problems until the addActionListener(this) statement. i don't know where to go to link the buttons to their respective strings to be entered in the textfield

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class GUI extends JFrame implements ActionListener {

    private JButton one, two, three, four, five, six, seven, eight, nine, zero, point, cancel;

    private JTextField t;

    private JFrame frame;

    private String number = "";



    public GUI() {

        //creating button objects

        JButton one = new JButton("1");

        JButton two = new JButton("2");

        JButton three = new JButton("3");

        JButton four = new JButton("4");

        JButton five = new JButton("5");

        JButton six = new JButton("6");

        JButton seven = new JButton("7");

        JButton eight = new JButton("8");

        JButton nine = new JButton("9");

        JButton zero = new JButton("0");

        JButton point = new JButton(".");

        JButton cancel = new JButton("cancel");

        //call addActionListener() method

        one.addActionListener(this);

        two.addActionListener(this);

        three.addActionListener(this);

        four.addActionListener(this);

        five.addActionListener(this);

        six.addActionListener(this);

        seven.addActionListener(this);

        eight.addActionListener(this);

        nine.addActionListener(this);

        //point.addActionListener(this);

        //cancel.addActionListener(this);

        //create jframe object

        JFrame frame = new JFrame("Vendor");

        //create text field

        JTextField t = new JTextField();

        frame.setSize(400, 400);

        setVisible(true);

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //remove this after creating other modules

        //creating panel object

        JPanel panel = new JPanel();

        GridLayout grid = new GridLayout(0, 3);

        panel.setLayout(grid);

        panel.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);

        //setting text field to the top of the frame

        add(t, BorderLayout.NORTH);

        //adding buttons to panel

        panel.add(one);

        panel.add(two);

        panel.add(three);

        panel.add(four);

        panel.add(five);

        panel.add(six);

        panel.add(seven);

        panel.add(eight);

        panel.add(nine);

        panel.add(zero);

        panel.add(point);

        panel.add(cancel);

        //adding panel to frame

        add(panel);

    }

    public void actionPerformed(ActionEvent e) {


        if (e.getSource() == one) {

            t.setText(t.getText().concat("1"));

        }

        if (e.getSource() == two) {

            t.setText(t.getText().concat("2"));

        }

        if (e.getSource() == three) {

            t.setText(t.getText().concat("3"));

        }

        if (e.getSource() == four) {

            t.setText(t.getText().concat("4"));

        }

        if (e.getSource() == five) {

            t.setText(t.getText().concat("5"));

        }

        if (e.getSource() == six) {

            t.setText(t.getText().concat("6"));

        }

        if (e.getSource() == seven) {

            t.setText(t.getText().concat("7"));

        }

        if (e.getSource() == eight) {

            t.setText(t.getText().concat("8"));

        }

        if (e.getSource() == nine) {

            t.setText(t.getText().concat("9"));

        }

        if (e.getSource() == zero) {

            t.setText(t.getText().concat("0"));

        }

        /*if(e.getSource() == point) {

     t.setText(t.getText().concat("."));

  }*/
    }

    public static void main(String[] args) {

        GUI object = new GUI();

    }
}

Answer:

You are declaring the Buttons locally in the constructor and thereby overriding your member variables. Your member variables one, two, three... will always be null. You can write your constructor like this:

public GUI() {

    //creating button objects

    one = new JButton("1");

    two = new JButton("2");
    .
    .
    .

Question:

Small error I can't manage to do. So right now my program GUI looks like this:

Now there is a TextField under the 'Mark' column were the user can input their data. I also want the same for the weight section were I want to insert a TextField right under 'Weight' column.

However when I try and put in a TextField, both the the Textfields turn like this when the window is small:

and this when the window is enlarged:

How can I make it so that there is a textfield under Mark AND Weight?

Code:

public class Gradeanalysis implements ActionListener {

public void actionPerformed (ActionEvent e){
     GridBagConstraints gbc = new GridBagConstraints();

    //Adding the JPanels. Panel for instructions
    JPanel panel = new JPanel();
    panel.setLayout(new GridBagLayout());

    //JLabel for the Instructions.
    JLabel label = new JLabel("<html> Instructions: Type in the grades you’ve received, along with the weights they’ll have in the determination of your overall average. <br> After you press ‘Calculate’, the results will show your average so far. <br> Every grade you enter must be a non-negative number, and every percentage/weight you enter must be a positive number :)</html>");
    gbc.fill = GridBagConstraints.HORIZONTAL;
    gbc.gridwidth = 2;
    gbc.gridy = 0;
    panel.add(label, gbc);


    //JLabel1 for Assingment/Grade/Weight(Percent)
    JLabel label1 = new JLabel("<html><pre>Assingment\t\t\t\t\t  Mark\t\t\t\t\tWeight</pre></html>");
    gbc.fill = GridBagConstraints.HORIZONTAL;
    gbc.gridx = 0;
    gbc.gridy = 1;
    gbc.anchor = GridBagConstraints.NORTH;
    panel.add(label1, gbc);

    //JLabel Numbers for the number list of assingments at the side.
    JLabel numbers = new JLabel("1");
    gbc.gridx = 0;
    gbc.gridy = 2;
    gbc.anchor = GridBagConstraints.NORTH;
    gbc.weighty = 1;
    panel.add(numbers, gbc);        

    //JTextfield for Mark
    JTextField mark = new JTextField(2);
    gbc.fill = GridBagConstraints.NONE;
    gbc.gridy = 2;
    panel.add(mark, gbc);


    //JTextfield for Weight
    JTextField weight = new JTextField(2);
    gbc.gridx = 2;
    panel.add(weight, gbc);


    //New frame set
    JFrame frame = new JFrame("Grade Calculator-- ");
    frame.setVisible(true);
    frame.setSize(750,700);
    frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
    frame.add(panel);




}

}

Thanks for reading.


Answer:

Here's the GUI I created.

  1. I don't know where your main method is, but you must always start a Swing application with a call to the SwingUtilities invokeLater method. The invokeLater method puts the creation and execution of the Swing components on the Event Dispatch thread (EDT).

  2. When I use the GridBagLayout, I use the addComponent method I created to create a unique GridBagConstraints for each Swing component. I don't like to remember defaults.

  3. The order of the JFrame methods is extremely important. Memorize the order of the JFrame methods in this example.

  4. I put the instructions in a JTextArea. This way, the instruction text splits based on the size of the JTextArea. There's no need to hard code the line breaks with HTML.

Here's the code.

package com.ggl.testing;

import java.awt.Component;
import java.awt.Container;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

public class GradeAnalysis implements Runnable {

    private static final Insets normalInsets = new Insets(10, 10, 0, 10);
    private static final Insets finalInsets = new Insets(10, 10, 10, 10);

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new GradeAnalysis());
    }

    @Override
    public void run() {
        JFrame frame = new JFrame("Grade Calculator");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(createMainPanel());
        frame.pack();
        frame.setVisible(true);
    }

    private JPanel createMainPanel() {
        GridBagConstraints gbc = new GridBagConstraints();

        // Adding the JPanels. Panel for instructions
        JPanel panel = new JPanel();
        panel.setLayout(new GridBagLayout());

        int gridy = 0;

        // JLabel for the Instructions.
        JTextArea instructionTextArea = new JTextArea(5, 30);
        instructionTextArea.setEditable(false);
        instructionTextArea.setLineWrap(true);
        instructionTextArea.setWrapStyleWord(true);
        instructionTextArea.setText(getInstructions());
        JScrollPane instructionScrollPane = new JScrollPane(instructionTextArea);
        addComponent(panel, instructionScrollPane, 0, gridy++, 3, 1,
                finalInsets, GridBagConstraints.CENTER,
                GridBagConstraints.HORIZONTAL);

        // JLabels for Assignment/Grade/Weight(Percent)
        JLabel label1 = new JLabel("Assignment");
        label1.setHorizontalAlignment(JLabel.CENTER);
        addComponent(panel, label1, 0, gridy, 1, 1, finalInsets,
                GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL);

        JLabel label2 = new JLabel("Mark");
        label2.setHorizontalAlignment(JLabel.CENTER);
        addComponent(panel, label2, 1, gridy, 1, 1, finalInsets,
                GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL);

        JLabel label3 = new JLabel("Weight");
        label3.setHorizontalAlignment(JLabel.CENTER);
        addComponent(panel, label3, 2, gridy++, 1, 1, finalInsets,
                GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL);

        // JLabel Numbers for the number list of assignments at the side.
        JLabel number = new JLabel("1");
        number.setHorizontalAlignment(JLabel.CENTER);
        addComponent(panel, number, 0, gridy, 1, 1, normalInsets,
                GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL);

        // JTextfield for Mark
        JTextField mark = new JTextField(20);
        mark.setHorizontalAlignment(JLabel.CENTER);
        addComponent(panel, mark, 1, gridy, 1, 1, normalInsets,
                GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL);

        // JTextfield for Weight
        JTextField weight = new JTextField(20);
        weight.setHorizontalAlignment(JLabel.CENTER);
        addComponent(panel, weight, 2, gridy++, 1, 1, normalInsets,
                GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL);

        return panel;
    }

    private String getInstructions() {
        return "Instructions: Type in the grades you’ve received, along with the weights "
                + "they’ll have in the determination of your overall average. After you "
                + "press ‘Calculate’, the results will show your average so far. Every "
                + "grade you enter must be a non-negative number, and every "
                + "percentage/weight you enter must be a positive number :)";
    }

    private void addComponent(Container container, Component component,
            int gridx, int gridy, int gridwidth, int gridheight, Insets insets,
            int anchor, int fill) {
        GridBagConstraints gbc = new GridBagConstraints(gridx, gridy,
                gridwidth, gridheight, 1.0D, 1.0D, anchor, fill, insets, 0, 0);
        container.add(component, gbc);
    }

}

Question:

I've made a JTextField that restricts characters being entered unless it's numbers, letter "e", or comma . But now I realised that it restricts backspace being pressed to. How can I change it? I'll add the code, where it checks what key is being pressed, below

for (JTextField tf : listOfFields)
         {
             String value = tf.getText();
             int n = value.length();
             if (ke.getKeyChar()>= '0' &&  ke.getKeyChar() <= '9' || ke.getKeyChar() == ','|| ke.getKeyChar() == 'e')
             {
                 tf.setEditable(true);
             }
             else
             {
               tf.setEditable(false);
             }
         }}});

Answer:

To have a text field accept a numeric entry, you should use a JFormattedTextField:

JFormattedTextField field = new JFormattedTextField(
    NumberFormat.getIntegerInstance());
field.setColumns(12);

To make it check both a localized number format (one that uses commas) and also the java.lang syntax (like 1e5), you can create a NumberFormatter which does both:

NumberFormatter formatter = new NumberFormatter() {
    @Override
    public Object stringToValue(String text)
    throws ParseException {
        try {
            return Double.valueOf(text);
        } catch (NumberFormatException ne) {
            return super.stringToValue(text);
        }
    }
};
JFormattedTextField field = new JFormattedTextField(formatter);
field.setColumns(12);

Each field’s value can be retrieved with the getValue method:

for (JFormattedTextField tf : listOfFields) {
    Number value = (Number) tf.getValue();
    // ...
}

Restricting the keys typed by the user is not the correct way to guarantee numeric entry. For instance, your code would allow a user to type 123,4,45,678.

There are many keys which allow editing. Home, End, Delete, and Ctrl-A are just a few. You shouldn't try to explicitly accommodate them all with a keystroke whitelist. Let JFormattedTextField do the work of verifying the input.

Question:

I have two JTextFields called field1 and field2, the goal is to type in a name and when I hit return, have those values become stored in nameArray[] at positions 0 and 1.

I'm not sure whether the cause is the logic of my action listener or the way I am declaring my array. If it is either of those things...

The array is declared like so, right below my class declaration:

public class TwoPlayer{
private String[] nameArray = {};

Here is my action listener and field1 initialization:

JTextField field1 = new JTextField("Left name");
    field1.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    String lValue = field1.getText();
    String leftValue = String.valueOf(lValue);
    nameArray[0] = (leftValue);
    }
  });  

field2:

JTextField field2 = new JTextField("Right name");   
    field2.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    String rValue = field2.getText();
    String rightValue = String.valueOf(rValue);
    nameArray[1] = (rightValue);
    }
  }); 

Obligatory Stack:

Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 0 at tests.TwoPlayer$1.actionPerformed(TwoPlayer.java:37) at javax.swing.JTextField.fireActionPerformed(JTextField.java:508) at javax.swing.JTextField.postActionEvent(JTextField.java:721) at javax.swing.JTextField$NotifyAction.actionPerformed(JTextField.java:836) at javax.swing.SwingUtilities.notifyAction(SwingUtilities.java:1663) at javax.swing.JComponent.processKeyBinding(JComponent.java:2882) at javax.swing.JComponent.processKeyBindings(JComponent.java:2929) at javax.swing.JComponent.processKeyEvent(JComponent.java:2845) at java.awt.Component.processEvent(Component.java:6312) at java.awt.Container.processEvent(Container.java:2236) at java.awt.Component.dispatchEventImpl(Component.java:4891) at java.awt.Container.dispatchEventImpl(Container.java:2294) at java.awt.Component.dispatchEvent(Component.java:4713) at java.awt.KeyboardFocusManager.redispatchEvent(KeyboardFocusManager.java:1954) at java.awt.DefaultKeyboardFocusManager.dispatchKeyEvent(DefaultKeyboardFocusManager.java:806) at java.awt.DefaultKeyboardFocusManager.preDispatchKeyEvent(DefaultKeyboardFocusManager.java:1074) at java.awt.DefaultKeyboardFocusManager.typeAheadAssertions(DefaultKeyboardFocusManager.java:945) at java.awt.DefaultKeyboardFocusManager.dispatchEvent(DefaultKeyboardFocusManager.java:771) at java.awt.Component.dispatchEventImpl(Component.java:4762) at java.awt.Container.dispatchEventImpl(Container.java:2294) at java.awt.Window.dispatchEventImpl(Window.java:2750) at java.awt.Component.dispatchEvent(Component.java:4713) at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758) at java.awt.EventQueue.access$500(EventQueue.java:97) at java.awt.EventQueue$3.run(EventQueue.java:709) at java.awt.EventQueue$3.run(EventQueue.java:703) at java.security.AccessController.doPrivileged(Native Method) at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76) at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:86) at java.awt.EventQueue$4.run(EventQueue.java:731) at java.awt.EventQueue$4.run(EventQueue.java:729) at java.security.AccessController.doPrivileged(Native Method) at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76) at java.awt.EventQueue.dispatchEvent(EventQueue.java:728) at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201) at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116) at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93) at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)


Answer:

It is the way you are initializing the array. You currently have private String[] nameArray = {}; which creates a new String[] with length 0 and explains the IndexOutOfBoundsException.

What you want instead is private String[] nameArray = new String[2]; which initializes a String[] that will hold two strings.

Question:

I have created a basic GUI which has 2 JCheckButtons (bold, italic) and 3JRadioButtons in a button group of font styles (times, helvetica, courier). There is also a textfield which will display a string of the font style, such as times, in that style, and if the bold or italic buttons are pressed then the text will also be bold or italic (or both). So far I have managed to add action listeners which copy the font name from the radio buttons to the textfield but I am having trouble making this text be in the associated font style. I also am having trouble with the functions of my bold and italic buttons.

Here is the code for my GUI layout (the layout is how I want it to be, only problem is with the functionality of my buttons:

package weekTwo;
import javax.swing.*;
import java.awt.*;
import java.awt.GridBagConstraints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class taskTwo {

public static void main(String[] args) {
    JFrame window = new JFrame("Font Chooser");
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.setSize(500, 100);

    FontSetter fontSetter = new FontSetter();

    Container pane = window.getContentPane();
    pane.setLayout(new GridBagLayout());

    GridBagConstraints gbc = new GridBagConstraints();

    JTextField text = new JTextField();
    gbc.gridx = 2;
    gbc.gridy = 2;
    gbc.weightx = 1;
    gbc.weighty = 1;
    gbc.insets = new Insets(0, 0, 5, 5); //padding constraints
    gbc.fill = GridBagConstraints.BOTH;   //text field fills cell
    pane.add(text, gbc);

    JCheckBox bold = new JCheckBox("Bold");
    gbc.gridx = 0; //sets x position to 0
    gbc.gridy = 1;
    bold.addActionListener(new Bold(fontSetter, text));
    pane.add(bold, gbc);

    JCheckBox italic = new JCheckBox("Italic");
    gbc.gridx = 0;
    gbc.gridy = 3;
    italic.addActionListener(new Italic(fontSetter, text));
    pane.add(italic, gbc);

    JRadioButton times = new JRadioButton("Times", true);
    gbc.gridx = 1;
    gbc.gridy = 0;
    times.addActionListener(new Times(fontSetter, text));
    pane.add(times, gbc);

    JRadioButton helvetica = new JRadioButton("Helvetica", false);
    gbc.gridx = 1;
    gbc.gridy = 2;
    helvetica.addActionListener(new Helvetica(fontSetter, text));
    pane.add(helvetica, gbc);

    JRadioButton courier = new JRadioButton("Courier", false);
    gbc.gridx = 1;
    gbc.gridy = 4;
    courier.addActionListener(new Courier(fontSetter, text));
    pane.add(courier, gbc);

    ButtonGroup fonts = new ButtonGroup();  //now only one of these buttons can be selected at once
    fonts.add(times);
    fonts.add(helvetica);
    fonts.add(courier);

    JButton ok = new JButton("OK");
    gbc.gridx = 3;
    gbc.gridy = 2;
    //ok.addActionListener();
    pane.add(ok, gbc);

    window.setVisible(true);
}
}

And here are my classes for my action listeners:

class Bold implements ActionListener {

private final FontSetter fontSetter;
private final JTextField textfield;

Bold(FontSetter fontSetter, JTextField textfield) {
    this.fontSetter = fontSetter;
    this.textfield = textfield;
}

Font font;

public void actionPerformed(ActionEvent e) {
    textfield.setFont(font.deriveFont(Font.BOLD));
}

}

class Italic implements ActionListener {

private final FontSetter fontSetter;
private final JTextField textfield;

Italic(FontSetter fontSetter, JTextField textfield) {
    this.fontSetter = fontSetter;
    this.textfield = textfield;
}

public void actionPerformed(ActionEvent e) {
    textfield.setText("");
}

}

class BoldItalic implements ActionListener {

private final FontSetter fontSetter;
private final JTextField textfield;

BoldItalic(FontSetter fontSetter, JTextField textfield) {
    this.fontSetter = fontSetter;
    this.textfield = textfield;
}

public void actionPerformed(ActionEvent e) {
    textfield.setText("");
}

}

class Times implements ActionListener {

private final FontSetter fontSetter;
private final JTextField textfield;

Times(FontSetter fontSetter, JTextField textfield) {
    this.fontSetter = fontSetter;
    this.textfield = textfield;
}

public void actionPerformed(ActionEvent e) {
    textfield.setText("Times");
}

}

class Helvetica implements ActionListener {

private final FontSetter fontSetter;
private final JTextField textfield;

Helvetica(FontSetter fontSetter, JTextField textfield) {
    this.fontSetter = fontSetter;
    this.textfield = textfield;
}

public void actionPerformed(ActionEvent e) {
    textfield.setText("Helvetica");
}

}

class Courier implements ActionListener {

private final FontSetter fontSetter;
private final JTextField textfield;

Courier(FontSetter fontSetter, JTextField textfield) {
    this.fontSetter = fontSetter;
    this.textfield = textfield;
}

public void actionPerformed(ActionEvent e) {
    textfield.setText("Courier");
}

}

I hope I have explained this clearly and would appreciate any help with my code, thanks.

p.s also my fontsetter class this doesnt have any function atm but it was how I originally intended to layout my action listeners

class FontSetter {

void setBold() {

}

void setItalic() {

}

void setBoldItalic() {

}

void setTimes() {

}

void setHelvetica() {

}

void setCourier() {

}
}

Answer:

You can define some variables in your FontSetter class to keep the current font name and style

Something like this

class FontSetter {

private final JTextField text;
private String fontName = "Times";
private boolean isBold = false;
private boolean isItalic = false;

FontSetter(JTextField text) {
    this.text = text;
}

void setBold(boolean flag) {
    isBold = flag;
    applyFontChanges();
}

void setItalic(boolean flag) {
    isItalic = flag;
    applyFontChanges();
}

void setFontName(String fontName) {
    this.fontName = fontName;
    applyFontChanges();
}

private void applyFontChanges(){
    Font font;
    int style;

    if(isBold && isItalic){
        style = Font.BOLD + Font.ITALIC;
    } else if(isBold){
        style = Font.BOLD;
    } else if(isItalic){
        style = Font.ITALIC;
    } else {
        style = Font.PLAIN;
    }

    font = new Font(fontName, style, 12);
    text.setFont(font );
}   
}

Then you can use it in your ActionListeners to change the font like this

fontSetter.setFontName("Courier");
textfield.setText("Courier");

And you can also change the style as follow

JCheckBox ch = (JCheckBox) e.getSource();
fontSetter.setBold(ch.isSelected());

--

Here is the complete code snippet

Question:

I have the following code which only allows one numerical value to allowed in the field:

try {
  MaskFormatter deckLevelEntry = new MaskFormatter("#");
  deckLevelEntry.setPlaceholderCharacter('_');

  deckLevelEntryField = new JFormattedTextField(deckLevelEntry);
  detailsPanel.add(deckLevelEntryField);
  wholeFramePanel.add(detailsPanel);
  frame3.add(wholeFramePanel);
  frame3.setVisible(true);
  } catch (Exception ex) {
  }

However, is there a way, if so how, to set the maximum numerical value to be entered? by this I mean I want the following value's to be accepted in the JFormattedTextField: 1,2,3 and 4. Anything above 4 should not be allowed to entered. The same applies for the value of 0.


Answer:

Use this:

NumberFormatter nf = new NumberFormatter();
nf.setMinimum(new Integer(30));
nf.setMaximum(new Integer(70));
final JFormattedTextField field = new JFormattedTextField(nf);

Question:

having subclassed JTextField, I noticed the paintComponent Method is called repeatedly (approximately every half-a-second) when the Field has Focus, even with no user interaction.

I read the Oracle article "Painting in AWT and Swing", but didn't find any enlightenment there.

Is this normal behaviour, or have a missed something?

Here's my example Proggy: (positioning the Cursor in the 2nd - not subclassed - JTextField which has no logging, causes the subclassed one with logging to lose Focus which stops being repeatedly repainted)

import java.awt.*;
import javax.swing.*;

public class SwingPaintDemo2 extends JFrame {

    public SwingPaintDemo2(final String title) {
        super(title);

        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        final Box box = new Box(BoxLayout.Y_AXIS);

        box.add(new JPanel() {
            @Override
            public Dimension getPreferredSize() {
                return new Dimension(250, 200);
            }
            @Override
            public void paintComponent(final Graphics g) {
                super  .paintComponent(               g);

                System.out.println("MyPanel.paintComponent......: " + g);

                g.drawString("This is my custom Panel!", 10, 20);
            }
        });
        box.add(new JTextField("JayTekst") {
            @Override
            public void paintComponent(final Graphics g) {
                super  .paintComponent(               g);

                System.out.println("JayTextField.paintComponent.: " + g);
            }
        });
        box.add(new JTextField("JText"));
        this.add(box);
        this.pack();
        this.setVisible(true);
    }
    public static void main(final String[] args) {
        SwingUtilities.invokeLater(() -> new SwingPaintDemo2("Swing Paint Demo"));
    }
}

Answer:

Of course it is normal. When the textfield has focus, you can see the cursor blinking which means you see the textfield with new a visual representation, which means paintComponent().

Question:

Here is the code:

String name = txtname.getText();
         int id = Integer.parseInt(txtid.getText());
        int pass = Integer.parseInt(txtpass.getText());
         String day = Date.getSelectedItem().toString();


    if (txtname.getText().isEmpty() ||txtid.getText().isEmpty()||Date.getSelectedIndex()==0 || event == null||time==null) {


        JOptionPane.showMessageDialog(null, "you should add all information", "error", JOptionPane.ERROR_MESSAGE);



    }                                       

    else {

        ((DefaultListModel) jList1.getModel()).addElement(txtname.getText() + " " + txtpass.getText() + "(" + Date.getSelectedItem() + ") "+event+", "+time);
   try{
               Statement stmt = con.createStatement();
                stmt.execute("INSERT INTO company(name,id) VALUES('"+name+"',"+id+");");
                stmt.execute("INSERT INTO events(pass,time,status,day,companyId) VALUES("+pass+",'"+time+"','"+event+"','"+day+"',"+id+");");

               JOptionPane.showMessageDialog(this, "Record Submit");

          }catch(Exception ex){
              JOptionPane.showMessageDialog(this, ex);

             } 


    }


    this.txtname.setText(null);
    this.txtpass.setText(null);
    this.txtid.setText(null);
    this.Date.setSelectedIndex(0);
    this.jCheckBox1.setSelected(false);
    this.jCheckBox2.setSelected(false);
    this.jCheckBox3.setSelected(false);


}

This is the error:

java.lang.NumberFormatException: For input string: ""

The code is work probably with string textFields but does not work with integer textField. It works probably if I remove:

 txtid.getText().isEmpty()

please show me how can I fix the code?


Answer:

It seems txtid.getText() is returning "". Is that correct? The string "" is not numeric and cannot be parsed by Integer.parseInt(). One thing you can do is use a try, catch. If it throws a NumberFormatException error, you can then handle it accordingly.

Question:

How do I set two JLabels separated by a JTextField in the same line? I am using MigLayout. I have the following code

		JPanel helper = new JPanel( new MigLayout() );
		helper.add( new JLabel( "Threshold:" ), "" );
		threshold = new JTextField();
		Icon thresholdIcon = UIManager.getIcon( "OptionPane.questionIcon" );
		JLabel thresholdIconLabel = new JLabel( thresholdIcon );
		thresholdIconLabel.setToolTipText( "Threshold for template matching" );
		helper.add( threshold, "wrap, width 100:20" );
		helper.add( thresholdIconLabel, "wrap, width 100:20" );

Answer:

Have you looked into using row/column constraints and using "cell" arguments when placing the Components? I've had a lot of success with that method.

    JPanel helper = new JPanel(
            new MigLayout(
                    "", 
                    "5[grow,fill]10[grow,fill,20:100]10[grow,fill,20:100]5",
                    "5[fill,grow]5"));
    helper.add( new JLabel( "Threshold:" ), "cell 0 0" );
    threshold = new JTextField();                  // Assuming this was declared earlier
    Icon thresholdIcon = UIManager.getIcon( "OptionPane.questionIcon" );
    JLabel thresholdIconLabel = new JLabel( thresholdIcon );
    thresholdIconLabel.setToolTipText( "Threshold for template matching" );
    helper.add( threshold, "cell 1 0" );
    helper.add( thresholdIconLabel, "cell 2 0" );

Make a point of reading both the MigLayout Whitepaper and MigLayout Quick Start Guide, as they do a really good job of explaining everything at your disposal.

Sidenotes:

  1. The reason it's not showing up in one line is because you're telling MigLayout it's okay to wrap the Components to fit in the space you're giving it, including making new lines to accommodate. You could also try increasing the size of the window.

  2. The size 100:20 translates to 100px minimum size, but a 20px preferred size, and I don't know how MigLayout would handle that. I changed it in my code.

(Disclaimer: code is untested and may be a little rough)

Question:

I have made this program and I want to print a message and the name of the button, when I click some button. But it does not print anything and does not make any error.

public class Example {

    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setTitle("Hello");
        frame.setSize(400, 200);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);

        frame.setLayout(new BorderLayout());

        JPanel buttonsPanel = new JPanel();
        buttonsPanel.setLayout(new GridLayout(2, 2));

        JTextArea txtArea = new JTextArea();
        HelloActionListener listen = new HelloActionListener(txtArea);
        JButton b1 = new JButton("TOP");
        b1.addActionListener(listen);
        JButton b2 = new JButton("LEFT");
        JButton b3 = new JButton("RIGHT");
        JButton b4 = new JButton("BOTTOM");
        b4.addActionListener(listen);
    }
}

And the class HelloActionListener:

public class HelloActionListener implements ActionListener {

    public JTextArea area;

    public HelloActionListener(JTextArea area) {
        this.area = area;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        JButton x = (JButton) e.getSource();
        area.setText("Hello Folks" + x.getText());
    }
}

Does anyone know where my error is?


Answer:

I see three main problems. The first one is that you aren't adding your Buttons to the Jpanel you've created (buttonsPanel), nor are you adding the buttonsPanel to your frame, and you also aren't adding the txtArea to the frame. Second, your order of operations is off. I recommend calling the frame.setVisible(true) after you've finished building the frame. The third issue is you're using the BorderLayout on your JFrame, which is just not a very good layout to work with (in my opinion). Your listener and the other code all looks fine.

Changing your code to this seems to make it run as desired:

public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setTitle("Hello");
    frame.setSize(400, 200);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLayout(new GridLayout(2,1));

    JPanel buttonsPanel = new JPanel();
    buttonsPanel.setLayout(new GridLayout(2, 2));

    JTextArea txtArea = new JTextArea("Place Holder");
    txtArea.setColumns(2);
    HelloActionListener listen = new HelloActionListener(txtArea);
    JButton b1 = new JButton("TOP");
    b1.addActionListener(listen);
    buttonsPanel.add(b1);
    JButton b2 = new JButton("LEFT");
    buttonsPanel.add(b2);
    JButton b3 = new JButton("RIGHT");
    buttonsPanel.add(b3);
    JButton b4 = new JButton("BOTTOM");
    b4.addActionListener(listen);
    buttonsPanel.add(b4);

    frame.add(txtArea);
    frame.add(buttonsPanel);

    frame.setVisible(true);
}

I'd recommend reading this guide about layout managers in Java though. Even though it works here, this isn't a great way to have your layout.

Question:

I want to somehow store the text from JTextField into array and then sum it.

btn.addActionListener(new ActionListener() {
  public void actionPerformed(ActionEvent e) {
    //fldi is the JTextField I want to get text from
    int ii = Integer.parseInt(fldi.getText());
  }
});

What should I do next? how can I split text from there, for example if user input is "256" I think it should be stored in array like "2", "5", "6".

EDIT: So after Jake Miller's help I've got:

String input = fldi.getText();
            int sum = 0; 

            int[] values = new int[input.length()];
            for(int i = 0; i < input.length(); i++) {
            int number;
            if(input.substring(i, i+1).equals("-")) {
                number = Integer.parseInt(input.substring(i, i+2));
            } else {
                number = Integer.parseInt(input.substring(i, i+1));
            }
            values[i] = number;         
                sum = sum + values[i];
            }

            fldwo.setText(Integer.toString(sum));

But when I try it for negative numbers like "-2" and "-1" values array stores 4 values "-2", "2", "-1", "1" and the sum at the end is 0, but it should be -3.


Answer:

Don't parse it right away. Store the input into a String, use a loop to use .substring() to go through each character in the String, and parse each individual number and store into an int array.

String input = fldi.getText();
int[] values = new int[input.length()];
for(int i = 0; i < input.length(); i++) {
    values[i] = Integer.parseInt(input.substring(i, i+1));
}

If they input 256, then the array will have 3 values: 2, 5, and 6

EDIT

For negative numbers, you'll need to have a check for the character "-" as it indicates a negative number. Then, you'll use substring(i, i+2) to take two characters as opposed to one (the - and the number itself). You also don't need the array. You can simply add each number you parse to the sum directly. You also should use a while loop and increment i on your own. If you find a negative number, you're using 2 characters, which means you need to increment i by two instead of 1.:

    int sum = 0;
    int i   = 0;
    while(i < input.length()) {
        int number;
        if(input.substring(i, i+1).equals("-")) {
            number = Integer.parseInt(input.substring(i, i+2));
            i += 2;
        } else {
            number = Integer.parseInt(input.substring(i, i+1));
            i++;
        }
        sum += number;
    }

An example:

A user inputs 125-35. The first three characters will NOT be equal to "-", therefore they'll simply be parsed and stored into the values array. Once you reach the 4th character (3rd index), the character will be a "-", so the if statement will cause number to be equal to -3 as the substring now returns two characters as opposed to one.

Question:

I have been searching through various tutorials for two days in order to finish this code, however none of them actually help me to understand the concept of what is wrong with my code.

I'm attempting to write to a text file, and then read from it into a Jtable. I'm using arrays. My instructor has told me that I was using too many lists- so I tried to use only the one 'constructorList' and now it won't compile.

The error that shows up is:

error: method readFile in class CQUPestGUI cannot be applied to given types;

        readFile();
required: ArrayList<String>
found: no arguments
reason: actual and formal argument lists differ in length
1 error

Any attempts to correct it on my part only seem to make it worse.

This is the section of code that seems to be related to the error.

 private void buttonLoadStoredContractsActionPerformed(java.awt.event.ActionEvent evt) {                                                          
        readFile();
}   

I've skipped some sections in order not to give a lot of code to read through

protected void readFile(ArrayList<String> listContractors)
{
   BufferedReader reader = null;
   //ArrayList showContract = new ArrayList();

   try
   {
       reader = new BufferedReader(new FileReader("Pest.txt"));
       String nLine = reader.readLine();


       while (nLine != null)
       {
           listContractors.add(nLine);
           String [] rows = nLine.split("-");
           for (String s: rows)
           {
                System.out.println(s);
           }
           nLine = reader.readLine();
       }
   }
   catch (FileNotFoundException e)
   {
       e.printStackTrace();
   }
   catch (IOException e)
   {
        e.printStackTrace();
   }
   displayStoredContracts(listContractors);
}

protected void displayStoredContracts(ArrayList<String> listContractors)
{
    for (int i = 0; i < listContractors.size(); i++)
    {
        txtAreaSavedContracts.append((String) listContractors.get(i));


    }
}

And if anyone does want to see the entire code, here it is in pastebin -- full code. I use the gui builder, since I'm just a beginner and with deadlines to meet- so a lot of this will be messy. I'm only putting it up in case it's wanted.


Answer:

It is very easy to find, your method signature says that, the method protected void readFile(ArrayList<String> listContractors) only accepts a java.util.ArrayList of String type. But when you call the method, you do not pass any parameter, you call the method by readFile();. You should have passed an ArrayList as method parameter.

  1. Create a ArrayList<String> list= new ArrayList<String>();
  2. Add some elements: list.add("asd"); (as you require)
  3. Call the method: readFile(list);

Hope, it helps you.

N.B. I do not think the definition of the method readFile is correct. It should not have that ArrayList<String> as formal parameter. It must create an instance of this ArrayList within the method block and add element to it within the method boundary.

Question:

I need help in how to get a textfield's text from a class and display it into a label which is from another class.

I just show the 2 classes, it is more easier to see/read what I'm trying to ask.

GameView.java

public void logIn()
    {
       loginFrame = new JFrame("FIshing Pair Game");
       loginFrame.setDefaultCloseOperation(EXIT_ON_CLOSE);
       loginFrame.setResizable(true);

       gridBag = new GridBagLayout();

       loginPanel = new JPanel();
       loginPanel.setBackground(Color.LIGHT_GRAY);
       loginPanel.setPreferredSize(new Dimension(400,400));
       loginPanel.setLayout(gridBag);

       loginTitleLbl = new JLabel("Login to Play!");
       loginTitleLbl.setFont(new Font("Britannic Bold",Font.PLAIN,22));

       nameLbl = new JLabel("Login name:");
       nameLbl.setFont(new Font("Agency FB",Font.BOLD,20));

       passLbl = new JLabel("Password:");
       passLbl.setFont(new Font("Agency FB",Font.BOLD,20));

       nameTxt = new JTextField();
       nameTxt.setPreferredSize(new Dimension(200,30));

       passTxt = new JPasswordField();
       passTxt.setPreferredSize(new Dimension(200,30));
       passTxt.setEchoChar('*');

       private class LoginBtnListener implements ActionListener
{
   public void actionPerformed(ActionEvent ae)
   {
       ArrayList<Player>players = new ArrayList<>();
       Scanner playerScan = null;

        try{
            playerScan = new Scanner(new File("players.dat"));
            while(playerScan.hasNextLine())
            {
                String playerData = playerScan.nextLine();
                String[] dataSplit = playerData.split("\\|");
                Player existingPlayer = new Player(dataSplit[0],dataSplit[1],dataSplit[2],Integer.parseInt(dataSplit[3]));
                players.add(existingPlayer);
            }
        }catch(FileNotFoundException ex){
            System.out.println("Error! File - players.dat not found!");
        }
        playerScan.close();

        boolean exist = false;

        String name = nameTxt.getText();
        String passWord = passTxt.getText();

        for(int i = 0; i < players.size(); i++)
        {
            if(players.get(i).getLoginName().equalsIgnoreCase(name))
            {
                exist = true;
            }
        }

        if(exist == true)
        {
            nameTxt.setText("");
            passTxt.setText("");
            JOptionPane.showMessageDialog(null,"Welcome back " + name + "!");
            javax.swing.UIManager.put("OptionPane.messageFont", new FontUIResource(new Font("Verdana", Font.ITALIC, 20))); 
            ShuffleCardsFrame fishingFrame = new ShuffleCardsFrame();
            fishingFrame.run();
            loginFrame.setVisible(false);
        }

        if(exist == false)
        {
            JOptionPane.showMessageDialog(null,"Error! Player " + name + " doesn't exist! Please try again.");
            javax.swing.UIManager.put("JOptionPane.messageFont", new FontUIResource(new Font("Baskerville Old Face", Font.BOLD, 20))); 
        }
   }

}

I need to get the name from the nametxt TextField and display it into this label from FishingPairFrame.java.

The name in the textfield is based on from the text file and the ArrayList.

FishingPairFrame.java

playerLbl = new JLabel("");

playerLbl.setFont(new Font("Agency FB",Font.BOLD,20));

UPDATED CODES

FishingPairFrame

playerName = gameView.getPlayerName();
playerLbl = new JLabel(playerName+" Matching Pair: 0");
playerLbl.setFont(new Font("Agency FB",Font.BOLD,20));

GameView.java

public String getPlayerName()
{
   return playerName;
}

public void setPlayerName(String playerName)
{
   this.playerName = playerName;
}
//in private loginbtnlistener class
playerName = nameTxt.getText();

Answer:

  1. Create a public method in GameView.java that returns a string:

    private String name;
    
    public String getName() {
        return name;
    }
    
  2. in GameView set the new variable "name" when the text field gets populated.

You can just make this

    String name = nameTxt.getText(); 

into this:

    name = nameTxt.getText(); )
  1. in FishingPairFrame.java, call:

    GameView gameView = new GameView();
    String name = gameView.getName();
    

Or make the method static if you do not have an instance of the GameView class in FishingPairFrame.

This technique is called encapsulation (where you make a private variable accessible with getters and setters. Read up on it, it's very useful.

Question:

I made a similar question before, but this one is more peculiar. Simply put, I have two classes, in the first class (DefineEquationQuadratic) I am passing a value to SelectSolutionQuadratic. In SelectSolutionQuadratic I am trying to set a TextField to display this value, but it does not work. However, what does work is outputting it to the console/output. I am very confused

public class DefineEquationQuadratic extends javax.swing.JFrame {

private void nextActionPerformed(java.awt.event.ActionEvent evt) {                                     
    this.setVisible(false);
    new SelectSolutionsQuadratic().setVisible(true);
    String dataSent = aQuadraticSpinner.getValue().toString() + " " + addSubQuadraticComboBox.getSelectedItem(); 
    SelectSolutionsQuadratic transferMe = new SelectSolutionsQuadratic();
    transferMe.displayText(dataSent);
}                                    

AND

public class SelectSolutionsQuadratic extends javax.swing.JFrame {

public void displayText(String textToSet) {
    displayQuadraticEquation.setText(textToSet);
    displayQuadraticEquation.setText("Help); //This doesn't work by the way
    System.out.println(textToSet);
}

I feel these are the relevant bits of code, I'll now just post the complete classes.

DefineEquationQuadratic:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package GUI;

/**
 *
 * @author MatthewAlanTroutman
 */
public class DefineEquationQuadratic extends javax.swing.JFrame {

/**
 * Creates new form DefineEquation
 */
public DefineEquationQuadratic() {
    initComponents();
}

public DefineEquationQuadratic(String transferData) {
    this.transferData = transferData;
    initComponents();
}
public String transferData;

/**
 * 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() {

    graphSelectedLabel = new javax.swing.JLabel();
    defineTextLabel = new javax.swing.JLabel();
    quadraticEquationTextField = new javax.swing.JTextField();
    defineLabel = new javax.swing.JLabel();
    xSquaredQuadraticLabel = new javax.swing.JLabel();
    addSubQuadraticComboBox = new javax.swing.JComboBox();
    xQuadraticLabel = new javax.swing.JLabel();
    addSubQuadraticComboBox2 = new javax.swing.JComboBox();
    aQuadraticSpinner = new javax.swing.JSpinner();
    cQuadraticSpinner = new javax.swing.JSpinner();
    bQuadraticSpinner = new javax.swing.JSpinner();
    help = new javax.swing.JButton();
    close = new javax.swing.JButton();
    next = new javax.swing.JButton();
    back = new javax.swing.JButton();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    setMaximumSize(new java.awt.Dimension(1280, 800));

    graphSelectedLabel.setFont(new java.awt.Font("Lucida Grande", 0, 36)); // NOI18N
    graphSelectedLabel.setText("You selected the Quadratic graph type");

    defineTextLabel.setFont(new java.awt.Font("Lucida Grande", 0, 24)); // NOI18N
    defineTextLabel.setText("Please define your graph as an equation in the form of:");

    quadraticEquationTextField.setEditable(false);
    quadraticEquationTextField.setFont(new java.awt.Font("Lucida Grande", 0, 24)); // NOI18N
    quadraticEquationTextField.setHorizontalAlignment(javax.swing.JTextField.CENTER);
    quadraticEquationTextField.setText("ax^2+bx+c");
    quadraticEquationTextField.setToolTipText("");
    quadraticEquationTextField.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));

    defineLabel.setFont(new java.awt.Font("Lucida Grande", 0, 24)); // NOI18N
    defineLabel.setText("Define:");

    xSquaredQuadraticLabel.setFont(new java.awt.Font("Lucida Grande", 0, 24)); // NOI18N
    xSquaredQuadraticLabel.setText("x^2");

    addSubQuadraticComboBox.setFont(new java.awt.Font("Lucida Grande", 0, 24)); // NOI18N
    addSubQuadraticComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "+", "-" }));

    xQuadraticLabel.setFont(new java.awt.Font("Lucida Grande", 0, 24)); // NOI18N
    xQuadraticLabel.setText("x");

    addSubQuadraticComboBox2.setFont(new java.awt.Font("Lucida Grande", 0, 24)); // NOI18N
    addSubQuadraticComboBox2.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "+", "-" }));

    aQuadraticSpinner.setFont(new java.awt.Font("Lucida Grande", 0, 24)); // NOI18N
    aQuadraticSpinner.setModel(new javax.swing.SpinnerNumberModel(Double.valueOf(0.0d), null, null, Double.valueOf(1.0d)));
    aQuadraticSpinner.addChangeListener(new javax.swing.event.ChangeListener() {
        public void stateChanged(javax.swing.event.ChangeEvent evt) {
            aQuadraticSpinnerStateChanged(evt);
        }
    });

    cQuadraticSpinner.setFont(new java.awt.Font("Lucida Grande", 0, 24)); // NOI18N
    cQuadraticSpinner.setModel(new javax.swing.SpinnerNumberModel(Double.valueOf(0.0d), null, null, Double.valueOf(1.0d)));
    cQuadraticSpinner.addChangeListener(new javax.swing.event.ChangeListener() {
        public void stateChanged(javax.swing.event.ChangeEvent evt) {
            cQuadraticSpinnerStateChanged(evt);
        }
    });

    bQuadraticSpinner.setFont(new java.awt.Font("Lucida Grande", 0, 24)); // NOI18N
    bQuadraticSpinner.setModel(new javax.swing.SpinnerNumberModel(Double.valueOf(0.0d), null, null, Double.valueOf(1.0d)));
    bQuadraticSpinner.addChangeListener(new javax.swing.event.ChangeListener() {
        public void stateChanged(javax.swing.event.ChangeEvent evt) {
            bQuadraticSpinnerStateChanged(evt);
        }
    });

    help.setFont(new java.awt.Font("Lucida Grande", 0, 48)); // NOI18N
    help.setText("Help");

    close.setFont(new java.awt.Font("Lucida Grande", 0, 48)); // NOI18N
    close.setText("Close");
    close.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            closeActionPerformed(evt);
        }
    });

    next.setFont(new java.awt.Font("Lucida Grande", 0, 48)); // NOI18N
    next.setText("Next");
    next.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            nextActionPerformed(evt);
        }
    });

    back.setFont(new java.awt.Font("Lucida Grande", 0, 48)); // NOI18N
    back.setText("Back");
    back.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            backActionPerformed(evt);
        }
    });

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
            .addGap(0, 0, Short.MAX_VALUE)
            .addComponent(defineTextLabel)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
            .addComponent(quadraticEquationTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 178, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(154, 154, 154))
        .addGroup(layout.createSequentialGroup()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(26, 26, 26)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(graphSelectedLabel)
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(defineLabel)
                            .addGap(18, 18, 18)
                            .addComponent(aQuadraticSpinner, javax.swing.GroupLayout.PREFERRED_SIZE, 246, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                            .addComponent(xSquaredQuadraticLabel)
                            .addGap(18, 18, 18)
                            .addComponent(addSubQuadraticComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGap(18, 18, 18)
                            .addComponent(bQuadraticSpinner, javax.swing.GroupLayout.PREFERRED_SIZE, 246, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGap(12, 12, 12)
                            .addComponent(xQuadraticLabel)
                            .addGap(18, 18, 18)
                            .addComponent(addSubQuadraticComboBox2, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGap(18, 18, 18)
                            .addComponent(cQuadraticSpinner, javax.swing.GroupLayout.PREFERRED_SIZE, 246, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addGroup(layout.createSequentialGroup()
                    .addGap(233, 233, 233)
                    .addComponent(help, javax.swing.GroupLayout.PREFERRED_SIZE, 255, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(18, 18, 18)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(back, javax.swing.GroupLayout.PREFERRED_SIZE, 255, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(close, javax.swing.GroupLayout.PREFERRED_SIZE, 255, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGap(18, 18, 18)
                            .addComponent(next, javax.swing.GroupLayout.PREFERRED_SIZE, 255, javax.swing.GroupLayout.PREFERRED_SIZE)))))
            .addContainerGap(39, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGap(77, 77, 77)
            .addComponent(graphSelectedLabel)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(defineTextLabel)
                .addComponent(quadraticEquationTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 84, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGap(77, 77, 77)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(defineLabel)
                .addComponent(xSquaredQuadraticLabel)
                .addComponent(addSubQuadraticComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(xQuadraticLabel)
                .addComponent(addSubQuadraticComboBox2, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(aQuadraticSpinner, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(bQuadraticSpinner, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(cQuadraticSpinner, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 211, Short.MAX_VALUE)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(help, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(close, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(next, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGap(18, 18, 18)
            .addComponent(back, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(65, 65, 65))
    );

    pack();
}// </editor-fold>                        

private void closeActionPerformed(java.awt.event.ActionEvent evt) {                                      
    System.exit(0);
}                                     

private void nextActionPerformed(java.awt.event.ActionEvent evt) {                                     
    this.setVisible(false);
    new SelectSolutionsQuadratic().setVisible(true);
    String dataSent = aQuadraticSpinner.getValue().toString() + " " + addSubQuadraticComboBox.getSelectedItem(); 
    SelectSolutionsQuadratic transferMe = new SelectSolutionsQuadratic();
    transferMe.displayText(dataSent);
}                                    

private void backActionPerformed(java.awt.event.ActionEvent evt) {                                     
    this.setVisible(false);
    new GraphEquationSolverGUI().setVisible(true);
}                                    

private void aQuadraticSpinnerStateChanged(javax.swing.event.ChangeEvent evt) {                                               
    String aQuadraticSpinnerValue = (String)aQuadraticSpinner.getValue().toString();
    if (!"0.0".equals(aQuadraticSpinnerValue))
    {
        aQuadraticSpinnerValue = aQuadraticSpinnerValue + "x^2";

    }
    else
    {
        aQuadraticSpinnerValue = "";
    }
    System.out.println(aQuadraticSpinnerValue);
    transferData = (String)addSubQuadraticComboBox.getSelectedItem();
    System.out.println(transferData);
}                                              

private void bQuadraticSpinnerStateChanged(javax.swing.event.ChangeEvent evt) {                                               
    String bQuadraticSpinnerValue = (String)bQuadraticSpinner.getValue();
}                                              

private void cQuadraticSpinnerStateChanged(javax.swing.event.ChangeEvent evt) {                                               
    String cQuadraticSpinnerValue = (String)cQuadraticSpinner.getValue();
}     
/**
 * @param args the command line arguments
 */
public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(DefineEquationQuadratic.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(DefineEquationQuadratic.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(DefineEquationQuadratic.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(DefineEquationQuadratic.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>
    //</editor-fold>

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new DefineEquationQuadratic().setVisible(true);
        }


    });
}

// Variables declaration - do not modify                     
private javax.swing.JSpinner aQuadraticSpinner;
private javax.swing.JComboBox addSubQuadraticComboBox;
private javax.swing.JComboBox addSubQuadraticComboBox2;
private javax.swing.JSpinner bQuadraticSpinner;
private javax.swing.JButton back;
private javax.swing.JSpinner cQuadraticSpinner;
private javax.swing.JButton close;
private javax.swing.JLabel defineLabel;
private javax.swing.JLabel defineTextLabel;
private javax.swing.JLabel graphSelectedLabel;
private javax.swing.JButton help;
private javax.swing.JButton next;
private javax.swing.JTextField quadraticEquationTextField;
private javax.swing.JLabel xQuadraticLabel;
private javax.swing.JLabel xSquaredQuadraticLabel;
// End of variables declaration                   
}

SelectSolutionsQuadratic:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package GUI;

/**
 *
 * @author MatthewAlanTroutman
 */
public class SelectSolutionsQuadratic extends javax.swing.JFrame {
    /**
     * Creates new form SelectSolutionsQuadratic
     */
public SelectSolutionsQuadratic() {
    initComponents();
}

public SelectSolutionsQuadratic(String theData) {
    this.theData = theData;
    initComponents();
}

public String theData;

/**
 * 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() {

    displayQuadraticEquation = new javax.swing.JTextField();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    setSize(new java.awt.Dimension(1280, 800));

    displayQuadraticEquation.setEditable(false);
    displayQuadraticEquation.setColumns(1);
    displayQuadraticEquation.setToolTipText("");
    displayQuadraticEquation.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            displayQuadraticEquationActionPerformed(evt);
        }
    });

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGap(568, 568, 568)
            .addComponent(displayQuadraticEquation, javax.swing.GroupLayout.PREFERRED_SIZE, 290, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap(422, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGap(75, 75, 75)
            .addComponent(displayQuadraticEquation, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap(697, Short.MAX_VALUE))
    );

    pack();
}// </editor-fold>                        

private void displayQuadraticEquationActionPerformed(java.awt.event.ActionEvent evt) {                                                         
    // TODO add your handling code here:
}                                                        
public void displayText(String textToSet) {
    displayQuadraticEquation.setText(textToSet);
    displayQuadraticEquation.setText("Help); //This doesn't work by the way
    System.out.println(textToSet);
}


/**
 * @param args the command line arguments
 */
public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(SelectSolutionsQuadratic.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(SelectSolutionsQuadratic.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(SelectSolutionsQuadratic.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(SelectSolutionsQuadratic.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new SelectSolutionsQuadratic().setVisible(true);
        }
    });

}

// Variables declaration - do not modify                     
public javax.swing.JTextField displayQuadraticEquation;
// End of variables declaration                   
}

Answer:

You are creating two different instances of JFrame specifically SelectSolutionsQuadratic

    new SelectSolutionsQuadratic().setVisible(true);//1 
    ... 
    SelectSolutionsQuadratic transferMe = new SelectSolutionsQuadratic();//2

This will create two different instances.

  • First one is visible but you are not calling displayText.
  • You are setting value to second one but it's not visible.

So only create single instance and call jFrame.setVisible(true).


SOLUTION :

DefineEquationQuadratic#nextActionPerformed

//new SelectSolutionsQuadratic().setVisible(true);//REMOVE THIS LINE
String dataSent = aQuadraticSpinner.getValue().toString() + " " +   
                    addSubQuadraticComboBox.getSelectedItem(); 
SelectSolutionsQuadratic transferMe = new SelectSolutionsQuadratic();
transferMe.displayText(dataSent);
transferMe.setVisible(true);//ADD THIS LINE

Question:

I made a submit button but it will only be set enabled if there is text in the field. And the submit button will disable if there's no text in the field. However when I enter a, the submit button doesn't become enable and it requires me entering another character for it to do so. And I have to press the delete button again even thought I deleted all the character in the box for the button to disable.

I don't understand why this is happening, I put a print statement to see what happens as I enter characters. I noticed it prints out what I entered before the last key press.

public void keyPressed(KeyEvent e) {
    System.out.println(inputField.getText()); // test input
    if(inputField.getText().trim().length() == 0) 
        submit.setEnabled(false);

    if(e.getKeyCode() == KeyEvent.VK_ENTER) {
        if(inputField.getText().trim().length() == 0)
             JOptionPane.showMessageDialog(this, "Invalid input.", "Error", JOptionPane.ERROR_MESSAGE);
        else
            displayMessage();
        return;
    } 

    if(inputField.getText().trim().length() > 0) {
        submit.setEnabled(true);
    }
}

Answer:

Use keyReleased instead of keyPressed and keyTyped. Looks like the event triggers when the key is pressed, but before the field is updated. With keyTyped, it works for deleting characters that are currently in the field, but you would still need to enter 2 characters to get your button to work again.

import java.awt.GridLayout;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextArea;


public class TextField extends JFrame {

        JTextArea inputField;
        JButton    submit;

        public TextField()
        {
                this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                inputField = new JTextArea("hi");
                submit = new JButton("Submit");
                inputField.addKeyListener(new KeyListener() {

                        @Override
                        public void keyPressed(KeyEvent arg0) {
                                //func(arg0);
                        }

                        @Override
                        public void keyReleased(KeyEvent arg0) {
                                func(arg0);
                        }

                        @Override
                        public void keyTyped(KeyEvent arg0) {
                                //func(arg0);
                        }
                });
                this.setLayout(new GridLayout(0,1));
                this.add(inputField);
                this.add(submit);
                this.pack();
                this.setVisible(true);
        }

        void func(KeyEvent arg0)
        {
            System.out.println(inputField.getText() + "length: " + inputField.getText().trim().length()); // test input
            if(inputField.getText().trim().length() == 0)
                submit.setEnabled(false);

            if(arg0.getKeyCode() == KeyEvent.VK_ENTER) {
                if(inputField.getText().trim().length() == 0)
                        System.out.println("error");
                else
                    System.out.println("success");
                return;
            }
            if(inputField.getText().trim().length() > 0) {
                submit.setEnabled(true);
            }
        }

        public static void main(String [] args)
        {
                new TextField();
        }
}

Question:

I am trying to increment the value of a JTextfield (tenSecs) by one for every instance that my other JTextfield (oneSecs) reaches 0. I am having difficulty trying to increase the value of my tenSecs JTextfield as it is always 0. When manually changing the number, as soon as oneSecs reaches 0, tenSecs reverts to 0.

javax.swing.Timer tm = new javax.swing.Timer(1000, new ActionListener() {
    public void actionPerformed(ActionEvent evt) {
        AddOneActionPerformed(evt);
    } 
});

private void StartStopTimerActionPerformed(java.awt.event.ActionEvent evt) {                                               

    if (!tm.isRunning()) {
        tm.start();
    } else {
        tm.stop();
    }

    ScheduledExecutorService e= Executors.newSingleThreadScheduledExecutor(); //Start new scheduled executor service to invoke a timer that start wehn button is pressed
    e.scheduleAtFixedRate(new Runnable() {

        @Override
        public void run() {
            //Follow this Override to do task
            SwingUtilities.invokeLater(new Runnable() {
                //Override will let the task run                

                @Override
                public void run() {
                    oneSecsDisplay.setIcon(new ImageIcon("images\\" + TextGrabber() + ".png"));
                    oneSecs.setText( DigitValue.getText());

                    int i = 0;

                    if (Integer.parseInt(oneSecs.getText()) == i) {
                        tenSecs.setText(Integer.toString(i++));
                    }
                }
            });
        }
    }, 0, 100, TimeUnit.MILLISECONDS); //Update will be for every 100 milliseconds concurrent to system time
} 

// Variables declaration - do not modify   
private javax.swing.JTextField oneSecs;
private javax.swing.JTextField tenSecs;
// End of variables declaration

I am sure that the error is occurring around the line int i = 0;. I am also sure that my way of increasing the value is not the best way to do this, if someone could kindly point me in the correct direction


Answer:

If I'm understanding you correctly, try tenSecs.setText(String.valueOf(Integer.parseInt(tenSecs.getText()) + 1));

Question:

I'm creating a little program for my self to learn Java now I did make a GUI with 12 JTextFields and now I want to use the text that's in the text fields in another class where I print them out.

When I press the button class print is successful, summand I get the last System.out.println("Test if class is triggerd") in my console but I don't get the JTextFields output in the console

Class Frame1

import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JTextField;
import java.awt.Color;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;

public class Frame1 {

    public JFrame frmCratingRecipieGenerator;
    public JTextField txtSlot;
    public JTextField textField_1;
    public JTextField textField_2;
    public JTextField textField_3;
    public JTextField textField_4;
    public JTextField textField_5;
    public JTextField textField_6;
    public JTextField textField_7;
    public JTextField textField_8;
    public JTextField textField_9;
    public JTextField textField_10;
    public JTextField textField_11;
    public JLabel lblNewLabel;
    public String slot1;
    public String slot2;
    public String slot3;
    public String slot4;
    public String slot5;
    public String slot6;
    public String slot7;
    public String slot8;
    public String slot9;
    public String output;
    public String output_count;
    public String file_num;


    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    Frame1 window = new Frame1();
                    window.frmCratingRecipieGenerator.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the application.
     */
    public Frame1() {
        initialize();
    }

    /**
     * Initialize the contents of the frame.
     */
    public void initialize() {
        frmCratingRecipieGenerator = new JFrame();
        frmCratingRecipieGenerator.setResizable(false);
        frmCratingRecipieGenerator.setTitle("Crating Recipie Generator Alpha 1");
        frmCratingRecipieGenerator.getContentPane().setBackground(new Color(192, 192, 192));
        frmCratingRecipieGenerator.setBounds(100, 100, 452, 248);
        frmCratingRecipieGenerator.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frmCratingRecipieGenerator.getContentPane().setLayout(null);

        txtSlot = new JTextField();
        txtSlot.setBounds(10, 19, 86, 20);
        frmCratingRecipieGenerator.getContentPane().add(txtSlot);
        txtSlot.setColumns(10);

        textField_1 = new JTextField();
        textField_1.setBounds(106, 19, 86, 20);
        frmCratingRecipieGenerator.getContentPane().add(textField_1);
        textField_1.setColumns(10);

        textField_2 = new JTextField();
        textField_2.setBounds(202, 19, 86, 20);
        frmCratingRecipieGenerator.getContentPane().add(textField_2);
        textField_2.setColumns(10);

        textField_3 = new JTextField();
        textField_3.setBounds(10, 50, 86, 20);
        frmCratingRecipieGenerator.getContentPane().add(textField_3);
        textField_3.setColumns(10);

        textField_4 = new JTextField();
        textField_4.setBounds(106, 50, 86, 20);
        frmCratingRecipieGenerator.getContentPane().add(textField_4);
        textField_4.setColumns(10);

        textField_5 = new JTextField();
        textField_5.setBounds(202, 50, 86, 20);
        frmCratingRecipieGenerator.getContentPane().add(textField_5);
        textField_5.setColumns(10);

        textField_6 = new JTextField();
        textField_6.setBounds(10, 81, 86, 20);
        frmCratingRecipieGenerator.getContentPane().add(textField_6);
        textField_6.setColumns(10);

        textField_7 = new JTextField();
        textField_7.setBounds(106, 81, 86, 20);
        frmCratingRecipieGenerator.getContentPane().add(textField_7);
        textField_7.setColumns(10);

        textField_8 = new JTextField();
        textField_8.setBounds(202, 81, 86, 20);
        frmCratingRecipieGenerator.getContentPane().add(textField_8);
        textField_8.setColumns(10);

        textField_9 = new JTextField();
        textField_9.setBounds(351, 19, 86, 20);
        frmCratingRecipieGenerator.getContentPane().add(textField_9);
        textField_9.setColumns(10);

        textField_10 = new JTextField();
        textField_10.setBounds(351, 81, 46, 20);
        frmCratingRecipieGenerator.getContentPane().add(textField_10);
        textField_10.setColumns(10);

        textField_11 = new JTextField();
        textField_11.setText("1");
        textField_11.setBounds(351, 50, 46, 20);
        frmCratingRecipieGenerator.getContentPane().add(textField_11);
        textField_11.setColumns(10);

        JLabel lblFileId = new JLabel("File ID");
        lblFileId.setFont(new Font("Tahoma", Font.PLAIN, 16));
        lblFileId.setHorizontalAlignment(SwingConstants.LEFT);
        lblFileId.setBounds(298, 82, 86, 14);
        frmCratingRecipieGenerator.getContentPane().add(lblFileId);

        JLabel lblOutput = new JLabel("Output");
        lblOutput.setFont(new Font("Tahoma", Font.PLAIN, 16));
        lblOutput.setBounds(298, 20, 58, 14);
        frmCratingRecipieGenerator.getContentPane().add(lblOutput);

        JLabel lblCount = new JLabel("Count");
        lblCount.setFont(new Font("Tahoma", Font.PLAIN, 16));
        lblCount.setBounds(298, 51, 52, 14);
        frmCratingRecipieGenerator.getContentPane().add(lblCount);


        JLabel lblThisJavaProgram = new JLabel("This Java program is coded by Jason");
        lblThisJavaProgram.setFont(new Font("Tahoma", Font.PLAIN, 16));
        lblThisJavaProgram.setBounds(10, 179, 270, 20);
        frmCratingRecipieGenerator.getContentPane().add(lblThisJavaProgram);

        JLabel TestLabel = new JLabel("");
        TestLabel.setFont(new Font("Tahoma", Font.PLAIN, 16));
        TestLabel.setBounds(391, 179, 46, 19);
        frmCratingRecipieGenerator.getContentPane().add(TestLabel);

        JButton btnNewButton = new JButton("Generate the McFunction File's");
        btnNewButton.setBounds(10, 108, 427, 60);
        btnNewButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                TestLabel.setText(textField_10.getText());              
                print name = new print();
                name.Print();
            }
        });
        frmCratingRecipieGenerator.getContentPane().add(btnNewButton);

        lblNewLabel = new JLabel("Last File num");
        lblNewLabel.setFont(new Font("Tahoma", Font.PLAIN, 16));
        lblNewLabel.setBounds(287, 182, 110, 14);
        frmCratingRecipieGenerator.getContentPane().add(lblNewLabel);


        this.slot1 = txtSlot.getText();
        this.slot2 = textField_1.getText();
        this.slot3 = textField_2.getText();;
        this.slot4 = textField_3.getText();;
        this.slot5 = textField_4.getText();;
        this.slot6 = textField_5.getText();;
        this.slot7 = textField_6.getText();;
        this.slot8 = textField_7.getText();;
        this.slot9 = textField_8.getText();;
        this.output = textField_9.getText();
        this.output_count = textField_11.getText();
        this.file_num = textField_10.getText();



        }


}

Class print

package example;

public class print {
    public void Print() {
        Frame1 slots =  new Frame1();
        String slot1 = slots.slot1;
        String slot2 = slots.slot2;
        String slot3 = slots.slot3;
        String slot4 = slots.slot4;
        String slot5 = slots.slot5;
        String slot6 = slots.slot6;
        String slot7 = slots.slot7;
        String slot8 = slots.slot8;
        String slot9 = slots.slot9;
        String output = slots.output;
        String output_count = slots.output_count;
        String file_num = slots.file_num;

        System.out.println(slot1);
        System.out.println(slot2);
        System.out.println(slot3);
        System.out.println(slot4);
        System.out.println(slot5);
        System.out.println(slot6);
        System.out.println(slot7);
        System.out.println(slot8);
        System.out.println(slot9);
        System.out.println(output);
        System.out.println(output_count);
        System.out.println(file_num);
        System.out.println("Test if class is triggerd");
    }


}

Answer:

This is happening because you create on the print class a new Object of frame1 so the variables by default are null. You can add on the Print method a list parameter that stores all the Strings in that list.

public void Print(List<String> slots) {
    System.out.println(slots.get(0));
    System.out.println(slots.get(1));
    System.out.println(slots.get(2));
    System.out.println(slots.get(3));
    System.out.println(slots.get(4));
    System.out.println(slots.get(5));
    System.out.println(slots.get(6));
    System.out.println(slots.get(7));
    System.out.println(slots.get(8));
    System.out.println(slots.get(9));
    System.out.println(slots.get(10));
    System.out.println(slots.get(11));
}

and redefine before the method call all the variables and store them in the list.

You can learn some things about Java's lists here

If you are struggling finding the code I made it for you

            slot1 = txtSlot.getText();
            slot2 = textField_1.getText();
            slot3 = textField_2.getText();;
            slot4 = textField_3.getText();;
            slot5 = textField_4.getText();;
            slot6 = textField_5.getText();;
            slot7 = textField_6.getText();;
            slot8 = textField_7.getText();;
            slot9 = textField_8.getText();;
            output = textField_9.getText();
            List<String> slots = new ArrayList<String>();
            slots.add(slot1);
            slots.add(slot2);
            slots.add(slot3);
            slots.add(slot4);
            slots.add(slot5);
            slots.add(slot6);
            slots.add(slot7);
            slots.add(slot8);
            slots.add(slot9);
            slots.add(output);
            slots.add(output_count);
            slots.add(file_num);
            output_count = textField_11.getText();
            file_num = textField_10.getText();
            TestLabel.setText(textField_10.getText());     

            print name = new print();

            name.Print(slots);

and Print class:

public void Print(List<String> slots) {


    System.out.println(slots.get(0));
    System.out.println(slots.get(1));
    System.out.println(slots.get(2));
    System.out.println(slots.get(3));
    System.out.println(slots.get(4));
    System.out.println(slots.get(5));
    System.out.println(slots.get(6));
    System.out.println(slots.get(7));
    System.out.println(slots.get(8));
    System.out.println(slots.get(9));
    System.out.println(slots.get(10));
    System.out.println(slots.get(11));
    System.out.println("Test if class is triggerd");
}

Question:

im making a loan calculator for a school project and i cant figure out how to change the background colour of txtMonthlyPayment and txtTotalPayment to yellow once I press the button ComputePayment. And as a bonus if you can, how do you change the font size of the text that you enter in a textfield.

thanks heaps ! ;)

import java.awt.*; //enables java GUI
import java.awt.event.*;//enables the user to respond, such as using the mouse and keyboard
import javax.swing.*;//more awt and swing imports to be associated with components / objects
import javax.swing.border.TitledBorder; //title of the JFrame window
import java.awt.event.ActionListener; // used to set actions for certain components / objects
import java.awt.Color; // used to alter colour of components / objects
import java.awt.Font; // used to change font size / style

public class LoanCalculator extends JFrame {



//create text fields for interest rate, years, loan amount, monthly pmt and total pmt
private JTextField txtAnnualInterestRate = new JTextField();//text fields that appear, their names
private JTextField txtNumberOfYears = new JTextField();
private JTextField txtLoanAmount = new JTextField();
private JTextField txtMonthlyPayment = new JTextField();//define the control here, then add to the panel, below
private JTextField txtTotalPayment = new JTextField();

//create a compute payment button
private JButton jbtComputeLoan = new JButton("Compute Payment"); //text appears on the button

public LoanCalculator()
{
    //craft a panel to hold labels and text fields
    JPanel p1 = new JPanel(new GridLayout(5, 2));//dimensions specified

    p1.add(new JLabel("Annual Interest Rate"));
    p1.add(txtAnnualInterestRate);

    p1.add(new JLabel("Number of Years"));
    p1.add(txtNumberOfYears);

    p1.add(new JLabel("Loan Amount"));
    p1.add(txtLoanAmount);

    p1.add(new JLabel("Monthly Payment"));
    p1.add(txtMonthlyPayment);

    p1.add(new JLabel("Total Payment"));
    p1.add(txtTotalPayment);

    p1.setBorder(new TitledBorder("Enter loan amount, interest rate, and years"));

    //create another panel, to hold the button
    JPanel p2 = new JPanel(new FlowLayout(FlowLayout.RIGHT));
    p2.add(jbtComputeLoan); //remember defining this in the private section, earlier?

    //add your panels to the frame
    add(p1, BorderLayout.CENTER);
    add(p2, BorderLayout.SOUTH);

    //register a listener, who will 'listen' to updates to the frame, and interactions with it
    jbtComputeLoan.addActionListener(new ButtonListener());
}//end constructor

/**
 handle the compute payment buttons events
 */
private class ButtonListener implements ActionListener
{
    @Override
    public void actionPerformed(ActionEvent e )
    {


        //get values from the text fields
        double interest = Double.parseDouble(txtAnnualInterestRate.getText());

        int  year =  Integer.parseInt(txtNumberOfYears.getText());

        double loanAmount = Double.parseDouble(txtLoanAmount.getText());

        Loan loan = new Loan(interest, year, loanAmount);//see page 376 for source for loan object

        //display the monthly total payment and monthly payment
        txtMonthlyPayment.setText(String.format("%.2f", loan.getMonthlyPayment()));


        txtTotalPayment.setText(String.format("%.2f", loan.getTotalPayment()));
    }//end action performed
}

/**     craft a loan class, to store loan details */
public class Loan
{
    private double annualInterestRate;
    private int numberOfYears;
    private double loanAmount;
    private java.util.Date loanDate;

    /** default constructor */
    public Loan()
    {
        this(2.5, 1, 1000); //the default takes effect when other constructors are not used
    }

    /** construct a loan with a specified annual interest rate, number of years, and loan amount
     * @param annualInterestRate
     * @param numberOfYears
     * @param loanAmount */
    public Loan(double annualInterestRate, int numberOfYears, double loanAmount)
    {
        this.annualInterestRate = annualInterestRate;//the users determine / specify the interest rate
        this.numberOfYears = numberOfYears;
        this.loanAmount = loanAmount;
        loanDate = new java.util.Date();
    }

    /** return the annual interest rate
     * @return  */
    public double getAnnualInterestRate()
    {
        return annualInterestRate;
    }

    //set the annual interest rate
    public void setAnnualInterestRate(double annualInterestRate)
    {
        this.annualInterestRate = annualInterestRate;//from the incoming data to the function
    }

    //return the number of years
    public int getNumberOfYears()
    {
        return numberOfYears;//private variable, which needs a get/set couplet
    }

    public void setNumberOfYears(int numberOfYears)
    {
        this.numberOfYears = numberOfYears;
    }

    public double getLoanAmount()
    {
        return loanAmount;
    }

    public double getMonthlyPayment()
    {
        double monthlyInterestRate = annualInterestRate / 1200;

        double monthlyPayment = loanAmount * monthlyInterestRate / (1-(1 / Math.pow(1+monthlyInterestRate, numberOfYears * 12)));

        return monthlyPayment;
    }

    public double getTotalPayment()
    {
        double  totalPayment = getMonthlyPayment() * numberOfYears *12;
        return totalPayment;
    }

    public java.util.Date getLoanDate()
    {
        return loanDate;//conveys a private variable, loan date, to any accessing class, who wants to know
    }

}//end of loan class
public static void main(String[] args) {
    LoanCalculator frame = new LoanCalculator();
    frame.pack();

    frame.setTitle("Loan Calculator");

    frame.setLocationRelativeTo(null); //forces the new window to appear in the center

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//what happens when you touch the X in the above left corner

    frame.setVisible(true);//so it appears
 }
}

Answer:

You need to do this in actionPerformed.

public void actionPerformed(ActionEvent e )
{


    //get values from the text fields
    double interest = Double.parseDouble(txtAnnualInterestRate.getText());

    int  year =  Integer.parseInt(txtNumberOfYears.getText());

    double loanAmount = Double.parseDouble(txtLoanAmount.getText());

    Loan loan = new Loan(interest, year, loanAmount);//see page 376 for source for loan object

    //display the monthly total payment and monthly payment
    txtMonthlyPayment.setText(String.format("%.2f", loan.getMonthlyPayment()));
    txtMonthlyPayment.setBackground(Color.YELLOW);

    txtTotalPayment.setText(String.format("%.2f", loan.getTotalPayment()));
    txtTotalPayment.setBackground(Color.YELLOW);
}//end action performed

For your second issue,you may use java.awt.Font to set font.For example,

txtMonthlyPayment.setFont(new Font("font name",font_style(int),size(int));

Question:

I want to make the text automatically as wide as the window. I tried using text.setSize(window.getWidth(),20) and text.setBounds(window.getWidth(),20), (where text is JTextfield), but the only way that seems to work is: static JTextField text = new JTextField(int numberOfColumns); I'm using GridBag layout.


Answer:

EDIT: I have edited example according to GridBagLayout.

Use layout manager. It will automatically expands component according to window. For example;

Jpanel panel = new JPanel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.fill = GridBagConstraints.HORIZONTAL;
c.gridwidth = GridBagConstraints.REMAINDER;
panel.add(textfield,c);

Question:

New to Java, so any help would be greatly appreciated. Have a small problem with data validation in a JTextField. A user is asked to enter their Age, Whether they smoke, and whether they are overweight. Validation for smoking and weight works fine, so does the age limit I have set.

However if I enter a letter in the ageField JTextField it seems to get stuck and doesn't print the other validation errors. (E.g. It will correctly print "Age must be an integer", however if I also typed 'h' in smokesField, "Smoke input should be Y, y, N or n" would not be printed.)

Sorry, that's a long and bloated explanation!

Anyway here is the code I'm having difficulties with, thankyou:

public void actionPerformed(ActionEvent e)
{
String ageBox = ageField.getText();
int age = 0;

if (e.getSource() == reportButton)
{
    if (ageBox.length() != 0)
        {
            try
            {
            age = Integer.parseInt(ageBox);
            }
            catch (NumberFormatException nfe)
            {
            log.append("\nError reports\n==========\n");    
            log.append("Age must be an Integer\n");
            ageField.requestFocus();
            }        
        }
    if (Integer.parseInt(ageBox) < 0 || Integer.parseInt(ageBox) > 116)
    {
      log.append("\nError reports\n==========\n");  
      log.append("Age must be in the range of 0-116\n");
      ageField.requestFocus();
    }
    if (!smokesField.getText().equalsIgnoreCase("Y") && !smokesField.getText().equalsIgnoreCase("N"))
    {
        log.append("\nError reports\n==========\n");
        log.append("Smoke input should be Y, y, N or n\n");
        smokesField.requestFocus();
    }
    if (!overweightField.getText().equalsIgnoreCase("Y") && !overweightField.getText().equalsIgnoreCase("N"))
    {
        log.append("\nError reports\n==========\n");
        log.append("Over Weight input should be Y, y, N or n\n");
        smokesField.requestFocus();
    }
    }

Answer:

From the situation you described, it's likely that the line

    if (Integer.parseInt(ageBox) < 0 || Integer.parseInt(ageBox) > 116)
{
...

is throwing an unhandled NumberFormatException, since you've entered a letter in ageBox. You get the correct output of "Age must be an Integer" the first time since your exception is being caught by your try/catch handler, but this second occurrence has no such handling.

To fix this, I would simply move that particular if statement inside the try block, like so:

    try
    {
        if (Integer.parseInt(ageBox) < 0 || Integer.parseInt(ageBox) > 116)
        {
            log.append("\nError reports\n==========\n");  
            log.append("Age must be in the range of 0-116\n");
            ageField.requestFocus();
        }
    }
    catch (NumberFormatException nfe)
    ...

This way, you'll still get the output of "Age must be an Integer" if ageBox has an invalid entry, and everything else should run fine.

Question:

I keep getting an error (Will post error below) When I press enter on my text field. I want the text field to save the data to a globally defined variable. The actionListener works whenever I don't include 'name' in my code, for example if I put int a = 3 then there are no errors. I have also declared name globally (on the main gui) because if I don't I get an error saying the variable is not in the scope, maybe this is an issue?

    //Declared inside the main gui (the others are nested in this)
    JTextField name;
    JLabel nameLabel;

    //Name text field defined inside the gui jInternalFrame
    TextField name = new TextField("Enter Name..", 20);
    JLabel nameLabel = new JLabel();
    nameLabel.setText("Name: ");
    name.addActionListener(new nameListener());
    addRoomPanel.add(nameLabel);
    addRoomPanel.add(name);`

    //ActionListener defined outside of the text field gui
    class nameListener implements ActionListener{
        public void actionPerformed(ActionEvent e){
            nameString = name.getText();
            name.setText("saved");
            name.selectAll();
         }
    }

ERROR MESSAGE:
    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at InternalFrame$dobListener.actionPerformed(InternalFrame.java:445)
    at java.awt.TextField.processActionEvent(TextField.java:617)
    at java.awt.TextField.processEvent(TextField.java:585)
    at java.awt.Component.dispatchEventImpl(Component.java:4872)
    at java.awt.Component.dispatchEvent(Component.java:4698)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:747)
    at java.awt.EventQueue.access$300(EventQueue.java:103)
    at java.awt.EventQueue$3.run(EventQueue.java:706)
    at java.awt.EventQueue$3.run(EventQueue.java:704)
    at java.security.AccessController.doPrivileged(Native Method)
    at  java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
    at java.awt.EventQueue$4.run(EventQueue.java:720)
    at java.awt.EventQueue$4.run(EventQueue.java:718)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:717)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:91)

Answer:

The Components of the UI are defined twice. Once in the GUI-class as variables, once in the (i suppose) constructor. Due to this two variables with name name and nameLabel exist. The constructor will access the ones declared in the constructor, thus the variables of the GUI-class remain uninitialized (null). The ActionListener access the variable in the GUI-class, which is null and throws a NullPointerException. You'll have to use one variable instead of two. For a more precise answer, i'll need a bit more code (or atleast something more useable than the snippets posted above).

Question:

I have this simple GUI in JAVA and i want to put inside the JTextField a string that contains the IP of my local machine.

I tried to get the IP with this command :

InetAddress.getLocalHost().getHostAddress();

and to store it inside a string , and to put the string inside the JTextField I have tried using gettext() and settext(), but without success.

The code :

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;

import java.awt.FlowLayout;

public class GuiLearn extends JFrame {
    private JLabel label;
    private JTextField textfield;

    public GuiLearn () {
        setLayout (new FlowLayout());

        textfield = new JTextField("This is where the IP address should be...");
        add(textfield);
    }

    public static void main (String args[]) {
        GuiLearn yuvi = new GuiLearn();

        yuvi.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        yuvi.setSize(400,400);
        yuvi.setVisible(true);
        yuvi.setTitle("guiiiiiii");
    }
}

please help..


Answer:

When you instantiate your JTextField, the String argument you pass into the constructor will set the text for you. Since InetAddress.getLocalHost().getHostAddress() returns a String, you can simply pass it in as a constructor argument to the JTextField.

this.textfield = new JTextField(InetAddress.getLocalHost().getHostAddress());

Or you can simply call this.textField.setText(InetAddress.getLocalHost().getHostAddress()) at any point after you have instantiated the object.

Question:

I have created a program where I can input data in JTextField and on hitting save button I use a JFileChooser to save the data in a .txt file where each JTextField is in a new line. I also created a button that pops up a JFileChooser to browse for that file and populate its corresponding cells.

I am new to GUIs, the code I wrote is not working. I tried different variations and cannot seem to get it. Can someone point me in the right direction please.

The input is

 john
Doe
st. Jude
100

Here is the code

import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.table.DefaultTableModel;

import java.util.Scanner
import java.util.Vector;
import java.awt.event.*;
import java.awt.*;
import java.text.DecimalFormat;
import java.io.*;

//import javax.swing.filechooser;
import javax.swing.filechooser.FileFilter;

public class Charity 
{
@SuppressWarnings("deprecation")
public static void main(String[] args) 
{
    JFrame frame = new JFrame("Learning Team Charity Program");
    Container cp = frame.getContentPane();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    // Charities
    final String[] charityArray = {"St.Jude", "CHOC", "Cancer Research", "AIDs Foundation", "Crohns Foundation"};
    final JComboBox selector = new JComboBox(charityArray);
    JPanel first = new JPanel();
    first.setLayout(new FlowLayout());
    first.add(selector);

    // User input JLabels and JTextFields
    JLabel nameLabel = new JLabel("First Name: ");
    final JTextField name = new JTextField();
    JLabel lastLabel = new JLabel("Last Name: ");
    final JTextField lastname = new JTextField();
    JLabel donationAmount = new JLabel("Donation Amount: ");
    final JTextField donation = new JTextField();


    JPanel second = new JPanel();
    second.setLayout(new GridLayout(4,2));
    second.add(nameLabel); second.add(name);
    second.add(lastLabel); second.add(lastname);
    second.add(donationAmount); second.add(donation);


    // Donate & Exit Buttons
    JButton donateButton = new JButton("Donate");
    JButton saveButton = new JButton("Save");
    JButton exitButton = new JButton("Exit");
    JButton openButton=  new JButton("Open File");
    JPanel third = new JPanel();
    third.setLayout(new FlowLayout());
    third.add(donateButton);
    third.add(saveButton);
    third.add(openButton);
    third.add(exitButton);

    // JTable display
    final DefaultTableModel model = new DefaultTableModel();
    JTable table = new JTable(model);
    model.addColumn("First Name");
    model.addColumn("Last Name");
    model.addColumn("Charity");
    model.addColumn("Donation");

    table.setShowHorizontalLines(true);
    table.setRowSelectionAllowed(true);
    table.setColumnSelectionAllowed(true);      
    JScrollPane scrollPane = JTable.createScrollPaneForTable(table);

    JPanel fourth = new JPanel();
    fourth.setLayout(new BorderLayout());
    fourth.add(scrollPane, BorderLayout.CENTER);

    // Button Events
    exitButton.addActionListener(new ActionListener() 
    {
        public void actionPerformed(ActionEvent e) 
        {
            System.exit(1); 
        }
    });

    openButton.addActionListener(new ActionListener()
    {
    public void actionPerformed(ActionEvent e){
    JFileChooser openChooser = new JFileChooser();
    int openStatus = openChooser.showOpenDialog(null);
    if(openStatus == JFileChooser.APPROVE_OPTION){
        try{
            File myFile = openChooser.getSelectedFile();
            BufferedReader br = new BufferedReader(new FileReader(myFile));

            String line;        
        while((line = br.readLine())!= null){
                             model.addRow(line.split(","));           

                    }//end while
                      br.close();
                }//end try

                catch(Exception e2){
                     JOptionPane.showMessageDialog(null, "Buffer Reader Error");
                }//end catch
            }
        }


        private void setValueAt(String line, int row, int col) {
            // TODO Auto-generated method stub

        }

    });

    saveButton.addActionListener(new ActionListener()
    {
        public void actionPerformed(ActionEvent e){
            JFileChooser fileChooser = new JFileChooser();
            int status = fileChooser.showSaveDialog(null);
            if (status == JFileChooser.APPROVE_OPTION)
            {
                fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("Text", ".txt", "txt"));
                //fileChooser.setFileFilter(new FileFilter("txt"));
                PrintWriter output;
                try {
                    File file = fileChooser.getSelectedFile();
                    output = new PrintWriter(file +".txt");
                    for(int row = 0; row<table.getRowCount(); row++){
                        for(int col = 0; col<table.getColumnCount();col++){
                            output.println(table.getValueAt(row, col).toString());

                        }
                        output.println();
                    }

                    output.close();

                } catch (IOException e1) {
                    e1.printStackTrace();
                }

            }
        }

});
    donateButton.addActionListener(new ActionListener() 
    {
        public void actionPerformed(ActionEvent e) 
        {

            DecimalFormat df = new DecimalFormat("##,###.00");
            try 
            {

                Object[] rows = new Object[]{name.getText(), lastname.getText(), selector.getSelectedItem(),
                    donation.getText()};
                    model.addRow(rows);
                    name.setText("");
                    lastname.setText("");
                    donation.setText("");
            } 
            catch (Exception ex) 
            {
                JOptionPane.showMessageDialog(null, "Enter a Dollar Amount", "Alert", JOptionPane.ERROR_MESSAGE);
                return;
            }
        }
    });

    // Frame Settings
    frame.setSize(470,300);
    //frame.setLocation(300,200);
    cp.setLayout(new BoxLayout(cp, BoxLayout.Y_AXIS));
    cp.add(first);
    cp.add(second);
    cp.add(third);
    cp.add(fourth);
    frame.setVisible(true);

    }   
}

Answer:

I understand I have to pass a value in the parenthesis after the addRow.

People don't know what that means because the code you posted here doesn't have an addRow(...) method.

I see you posted a second question 2 hours later: https://stackoverflow.com/questions/30951407/how-to-properly-read-a-txt-file-into-a-a-row-of-a-jtable.

Keep all the comments in one place so people understand what is going on.

Also, posting a few random lines of code doesn't help us because we don't know the context of how the code is used. For example, I have no idea what how you created the "model" variable. I don't know if you ever added the model to the table.

Post a proper SSCCE when posting a question so we have the necessary information. The file chooser is irrelevant to the problem because we don't have access to your real file. So instead you need to post hard coded data. An easy way to do this is to use a StringReader.

Here is a working example that shows how to read/parse/load a file into a JTable:

import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;
import java.io.*;

public class SSCCE extends JPanel
{
    public SSCCE()
    {
        try
        {
            DefaultTableModel model = new DefaultTableModel(0, 4);

            String data = "1 2 3 4\na b c d\none two three four";
            BufferedReader br = new BufferedReader( new StringReader( data ) );
            String line;

            while ((line = br.readLine()) != null)
            {
                String[] split = line.split(" ");
                model.addRow( split );
            }

            JTable table = new JTable(model);
            add( new JScrollPane(table) );
        }
        catch (IOException e) { System.out.println(e); }
    }

    private static void createAndShowGUI()
    {
        JFrame frame = new JFrame("SSCCE");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(new SSCCE());
        frame.setLocationByPlatform( true );
        frame.pack();
        frame.setVisible( true );
    }

    public static void main(String[] args)
    {
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                createAndShowGUI();
            }
        });
    }
}

All you need to do is change the code to use a FileReader instead of the StringReader.

Question:

Code:

char[] charData;
int[] data;    
JTextField message = new JTextField(60);
charData = message.getText().toUpperCase().toCharArray();
for(int i = 0; i < charData.length; i++){
    data[i] = (int) charData[i];             //line 62
}
for(int i : data){
    System.out.println(i);
}

I am given this error:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException 
    at Main$1.actionPerformed(Main.java:62)

Line 62 is data[i] = (int) charData[i];

Can anyone figure it out? I guess we will find out!


Answer:

You're forgetting to initialize your data variable, so you should move and modify its declaration to:

charData = message.getText().toUpperCase().toCharArray();
int[] data = new int[charData.length];

Now data will be initialized to an empty array of equal size to your array of characters.

However, of note is since you are leaving data uninitialized, your program should not be able to compile. Are you sure you are compiling successfully, and that this is the most up-to-date version of the code?

Question:

how can I position a JTextField? I have searched through many examples but unfortunately none worked for me. Can someone help me? I want to position it using absolute coordinates.

Code:

public static class TextDemo extends JPanel implements ActionListener {
  protected JTextField textField;
  static public String text;

  public TextDemo() {
    super(new GridBagLayout());

    textField = new JTextField(20);
    textField.addActionListener(this);

    textField.setBounds(10,10,200,40);
    //textField.setSize(500,500);

    //Add Components to this panel.
    GridBagConstraints c = new GridBagConstraints();
    c.gridwidth = GridBagConstraints.REMAINDER;

    c.fill = GridBagConstraints.HORIZONTAL;
    add(textField, c);

    c.fill = GridBagConstraints.BOTH;
    c.weightx = 1.0;
    c.weighty = 1.0;
  }

  public void actionPerformed(ActionEvent evt) {
    text = textField.getText();
  }

  public static void createAndShowGUI() {
    //Create and set up the window.
    JFrame frame = new JFrame("TextDemo");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    //Add contents to the window.
    frame.add(new TextDemo());

    //Display the window.
    frame.pack();
    frame.setVisible(true);
  }
}

Answer:

I am not sure what you are trying to achieve exactly, but if your will is to position the textfield in position 10,10, you can simply do it this way:

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

public class TextDemo extends JPanel implements ActionListener {
    private JTextField textField;
    private String text;

    public TextDemo() {
        super(new GridBagLayout());

        textField = new JTextField(20); // Here 20 gives a hint on the width of the textfield
        textField.addActionListener(this);

        // Add Components to this panel.
        GridBagConstraints c = new GridBagConstraints();
        c.gridwidth = GridBagConstraints.REMAINDER;
        c.insets = new Insets(10, 10, 10, 10);
        c.fill = GridBagConstraints.HORIZONTAL;
        add(textField, c);
    }

    @Override
    public void actionPerformed(ActionEvent evt) {
        text = textField.getText();
    }

    public static void main(String[] args) {
        // Create and set up the window.
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame frame = new JFrame("TextDemo");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

                // Add contents to the window.
                frame.add(new TextDemo());

                // Display the window.
                frame.pack();
                frame.setMinimumSize(frame.getPreferredSize());
                frame.setVisible(true);

            }
        });
    }
}

Question:

I am working on a app that reads from a database and fills a Table(Each row has a Title, Author, Publisher. etc) . I have a set of TextFields that has extra information for each row(location, copies, price). now when i select a single row, and change any fields the change is reflected perfectly. However, when i select multiple rows, and changes only one filed(e.g price) instead of refelcting only that field, all the information on the textfields are stored in all the selected rows.this is a screenshot of my program http://i.imgur.com/YMw7iy5.png

In summary, my problem is how to determine what field the user actually changed? (so i can modify only that attribute for the object, without overwriting the previous ones).

This is how i get the info from the Table to update the book in DB

ArrayList<Title> books = getAll(rowindex);
        int index=0;
        for(Title b:books){
        b.setIsbn((String) recTable.getValueAt(rowindex[index], 0));
        b.setTitle((String) recTable.getValueAt(rowindex[index], 1));
        b.setAuthor((String) recTable.getValueAt(rowindex[index], 2));
        b.setCountry((String) recTable.getValueAt(rowindex[index], 3));
        b.setPub((String) recTable.getValueAt(rowindex[index], 4));
        b.setYear((int) recTable.getValueAt(rowindex[index], 5));
        b.setEd((String) recTable.getValueAt(rowindex[index], 6));
        b.setPrice((Double) recTable.getValueAt(rowindex[index], 7));
        b.setCopies((int) recTable.getValueAt(rowindex[index], 8));
       Title_Record titlerecord = new Title_Record();
        titlerecord.setRecord(createRecord(b,rowindex[index++]));
        b.setRecord(titlerecord);
        ctrl.updateTitle(b);`

for each book i call create record, where it creates the book record and get the info from text fields, which is why the previos info in the recored gets overwritten.

field = factory.newDataField("960",' ',' '); // field.setTag("960"); sf1 = factory.newSubfield('a'); sf1.setData(acqType.getText()); sf2 = factory.newSubfield('g'); sf2.setData(format.getText()); sf3 = factory.newSubfield('i'); sf3.setData(ordType.getText()); Subfield sf4 = factory.newSubfield('k'); sf4.setData(rloc.getText()); Subfield sf5 = factory.newSubfield('l'); sf5.setData(bloc.getText()); Subfield sf6 = factory.newSubfield('m'); sf6.setData(status960.getText()); Subfield sf7 = factory.newSubfield('o'); sf7.setData(copies960.getText()); Subfield sf8 = factory.newSubfield('s'); sf8.setData(price960.getText()); Subfield sf9 = factory.newSubfield('t'); sf9.setData(location.getText()); Subfield sf10 = factory.newSubfield('u'); sf10.setData((String) fundcambo.getSelectedItem()); Subfield sf11 = factory.newSubfield('v'); sf11.setData(vendor.getText()); Subfield sf12 = factory.newSubfield('w'); sf12.setData(lang.getText()); Subfield sf13 = factory.newSubfield('x'); sf13.setData(cCode.getText());

i want a way to change only the fields the user has changed in case he selected multiple rows.


Answer:

Define a Map where the String key is subfield's name and Boolean value is the field's changed state flag.

Add a DocumentListener to each the subfield and on any change (insert/delete) set the flag for the field to true in the map.

To apply changed fields only get all true flags from the map and use the subfields' values only to update table data.

UPDATE: Or even easier to keep changed fields' names in a Set.

Question:

I want to build an application where a user inserts a String into a textfield and when he clicks a search button it redirects them to google with the search results displayed in google that match the string entered in the jtextfield in the application.

So for example if I type on the jtextfield "Java" and then press a search button, I want it to be equivalent to me typing "Java" directly on to Google. Is this possible?

Also, is it possible to have a dropdown list with suggestions? And when you click a suggestion it either fills the textfield in with the suggestion or automatically searches that suggestion (either one of those not both)

Note that I'm a fairly new programmer :)


Answer:

  try {
         String search = "#q="+jTextField.getText().toString().trim();
         search = search.replaceAll(" ","+");
         String url = "http:////www.google.com//"+search;
         java.awt.Desktop.getDesktop().browse(java.net.URI.create(url));
       }
       catch (java.io.IOException e) {
           System.out.println(e.getMessage());
       }

Question:

i want to get my full resultset to display into my JTxtField, but i dotn know how to do it.

This is my code At the moment:

    try{
        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
        conn3 =     DriverManager.getConnection("jdbc:sqlserver://ARTURO-LAPTOP;user=sa;password=sacompusis;database=PDV");
        st3 = conn3.createStatement();
        rs3= st3.executeQuery("SELECT Nombre_Pdv, SUM(Total) AS Expr1 FROM   VENTA_PLATILLOS GROUP BY Nombre_Pdv");

        while(rs3.next()){
            txt.setText(rs3.getString(1));
        }

    }
    catch(Exception e){
        e.printStackTrace();
    }

However this only gives me the first string of the resultset, how can i get the full result set?


Answer:

Your while loop may be setting many Strings to the JTextField, but only one will show -- the last one set as the JTextField's text, since it will over-write all text added before.

If you must show all Strings in the JTextField, then create a StringBuilder object, and within the while loop, append the ResultSet text you get into the StringBuilder, and then after the while loop, use the toString() from the StringBuilder as the text for the JTextField. e.g.,

StringBuilder sb = new StringBuilder();
while(rs3.next()){
    sb.append(rs3.getString(1) +"; ");
}
txt.setText(sb.toString());

Better: display the text in a JTextArea, appending it in the while loop with "\n".

StringBuilder sb = new StringBuilder();
while(rs3.next()){
    sb.append(rs3.getString(1) +"\n");
}
myTextArea.setText(sb.toString());

Even better still: display the whole ResultSet data in a JTable by creating a TableModel, either derived from AbstractTableModel for flexibility or DefaultTableModel for ease, and adding rows from the ResultSet into the model using your while loop, and then setting a JTable's TableModel with this created and filled model.

Question:

I have a simple program just need to set the character whose Unicode value larger the character data type (supplementary character) on JTextField when the button is click .Tell me i am really fed up and how i will do it .This problem have already taken my 4 days.

 //importing the packages
import java.awt.event.*;
import javax.swing.*;

import java.util.*;
import java.awt.*;

//My own custom class 
public class UnicodeTest implements ActionListener
{
JFrame jf;
JLabel jl;
JTextField jtf;
JButton jb;
UnicodeTest()
{
    jf=new JFrame();// making a frame
    jf.setLayout(null); //seting the layout null of this frame container
    jl=new JLabel("enter text"); //making the label 
    jtf=new JTextField();// making a textfied onto which a character will be shown
    jb=new JButton("enter");
//setting the bounds 
    jl.setBounds(50,50,100,50);
    jtf.setBounds(50,120,400,100);
    jb.setBounds(50, 230, 100, 100);
    jf.add(jl);jf.add(jtf);jf.add(jb);
    jf.setSize(400,400);
    jf.setVisible(true); //making frame visible
    jb.addActionListener(this); //  registering the listener object
}
public void actionPerformed(ActionEvent e) // event generated on the button click
{   try{

           int x=66560; //to print the character of this code point

           jtf.setText(""+(char)x);// i have to set the textfiled with a code point character which is supplementary in this case 

         }
     catch(Exception ee)// caughting the exception if arrived
        { ee.printStackTrace(); // it will trace the stack frame where exception arrive 
        }   
}
   // making the main method the starting point of our program
  public static void main(String[] args)
   {

    //creating and showing this application's GUI.
      new UnicodeTest();     
  }
}

Answer:

Since you are not giving enough information on what's wrong, I can only guess that either or both:

  1. You are not using a font that can display the character.
  2. You are not giving the text field the correct string representation of the text.
Setting a font that can display the character

Not all fonts can display all characters. You have to find one (or more) that can and set the Swing component to use that font. The fonts available to you are system dependent, so what works for you might not work for others. You can bundle fonts when you deploy your application to ensure it works for everyone.

To find a font on your system that can display your character, I used

Font[] fonts = GraphicsEnvironment.getLocalGraphicsEnvironment().getAllFonts();
for (Font f : fonts) {
    if (f.canDisplay(66560)) {
        System.out.println(f);
        textField.setFont(f.deriveFont(20f));
    }
}

The output (for me) is a single font, so I allowed myself to set it in the loop:

java.awt.Font[family=Segoe UI Symbol,name=Segoe UI Symbol,style=plain,size=1]

as also noted in the comments to the question by Andrew Thompson.

Giving the text field the correct string representation

The text fields require UTF-16. Supplementary characters in UTF-16 are encoded in two code units (2 of these: \u12CD). Assuming you start from a codepoint, you can convert it to characters and then make a string from them:

int x = 66560;
char[] chars = Character.toChars(x); // chars [0] is \uD801 and chars[1] is \uDC00
textField.setText(new String(chars)); // The string is "\uD801\uDC00"
// or just
textField.setText(new String(Character.toChars(x)));

as notes by Andrew Thompson in the comments to this answer (previously I used a StringBuilder).

Question:

I'm making a GUI. In which user enter year in integers form and that year display on GUI. But the problem is i want to only enter 4 integers from user. If user enter 5 integers value then it show JOptionPane message please type again. But i don't know how to do it. Code:

public class A extends JFrame{


    private JTextField tx;
    private JLabel year;
    private JButton bt;
    private JLabel at;


    public A(){
        super("Frame");


        getContentPane().setLayout(null);


        tx= new JTextField();
        tx.setBounds(150, 165, 128, 27);
        getContentPane().add(tx);   

        year= new JLabel("Enter Year :");
        year.setBounds(178, 133, 69, 27);
        getContentPane().add(year);


        at= new JLabel();
        at.setFont(new Font("Tahoma", Font.PLAIN, 17));
        at.setBounds(165, 295, 189, 27);
        getContentPane().add(at);


        bt= new JButton("Submit");
        bt.setBounds(178, 203, 84, 27);
        getContentPane().add(bt);
        bt.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent arg0) {

                String w = tx.getText();
                int p = Integer.parseInt(w);

                 at.setText(""+p);

            }

        });

        setSize(450,450);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        setResizable(false);
        setVisible(true);


    }

}

Main

public class Main {

    public static void main(String[] args) {

        A obj = new A();


    }

} 

Answer:

Here is the code, for your quick review, but please try to implement thingies by yourself, in future.

import java.awt.*;
import javax.swing.*;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
import javax.swing.text.DocumentFilter.FilterBypass;

public class MyDocumentFilterExample {

    private static final int MAX_CHARACTERS = 4;
    private JTextField tField;

    private void displayGUI () {
        JFrame frame = new JFrame("Input Integer Example");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        JPanel contentPane = new JPanel();
        contentPane.setBorder(
            BorderFactory.createEmptyBorder(5, 5, 5, 5));
        tField = new JTextField(10);
        ((AbstractDocument)tField.getDocument()).setDocumentFilter(
                new MyDocumentFilter ( MAX_CHARACTERS ));        
        contentPane.add(tField); 

        frame.setContentPane(contentPane);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    public static void main ( String[] args ) {
        Runnable runnable = new Runnable () {
            @Override
            public void run () {
                new MyDocumentFilterExample ().displayGUI ();
            }
        };
        EventQueue.invokeLater ( runnable );
    }
}

class MyDocumentFilter extends DocumentFilter {

    private int max_Characters;
    private boolean DEBUG;

    public MyDocumentFilter(int max_Chars) {
        max_Characters = max_Chars;
        DEBUG = false;
    }

    public void insertString(FilterBypass fb
                                    , int offset
                                    , String str
                                    , AttributeSet a) 
                                    throws BadLocationException {
        if (DEBUG) {
            System.out.println("In DocumentSizeFilter's insertString method");
        }
        int length = fb.getDocument ().getLength () + str.length ();
        if (length <= max_Characters && isValid ( str ) ) 
            super.insertString(fb, offset, str, a);
        else 
            Toolkit.getDefaultToolkit().beep();
    }

    public void replace(FilterBypass fb
                            , int offset, int length
                            , String str, AttributeSet a)
                                throws BadLocationException {
        if (DEBUG) {
            System.out.println("In DocumentSizeFilter's replace method");
        }
        int len = fb.getDocument ().getLength () + str.length ();
        if (len - length <= max_Characters && isValid ( str ) ) 
            super.replace(fb, offset, length, str, a);
        else
            Toolkit.getDefaultToolkit().beep();
    }

    private boolean isValid ( String string ) {
        int len = string.length();
        boolean isValidInteger = true;

        for (int i = 0; i < len; i++)
        {
            if (!Character.isDigit(string.charAt(i)))
            {
                isValidInteger = false;
                break;
            }
        }
        return isValidInteger;
    }
}

Question:

Whenever I compile this, I get an error reading "non-static variable french cannot be referenced from a static context". I have just started working with GUIs, but I cannot find an answer to this. I'm sure it's something simple, but I cannot figure it out!

Any help would be very greatly appreciated.

 public class ReportCard {
 JTextField french = new JTextField ("French Grade") ;
 public static void main (String args[]) {
    JFrame frame = new JFrame ("Report Card") ;
    frame.setSize(400 , 600) ;
    frame.setVisible(true) ;
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) ;

    JPanel bigPanel = new JPanel() ;
    frame.getContentPane().add(bigPanel) ;

    bigPanel.add(french) ;   

Answer:

I would strongly suggest reading up on how static works there are many people who can explain it much better than i can.For now you can do a couple of things. make french static

 static JTextField french = new JTextField ("French Grade") ;

or put it in to the main method which will inherently make it static since its already in a static context.

public class ReportCard {
 public static void main (String args[]) {
    JTextField french = new JTextField ("French Grade") ;
    JFrame frame = new JFrame ("Report Card") ;
    frame.setSize(400 , 600) ;
    frame.setVisible(true) ;
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) ;

    JPanel bigPanel = new JPanel() ;
    frame.getContentPane().add(bigPanel) ;

    bigPanel.add(french) ;  

Question:

I am fairly new to some intermediate concepts in Java. Recently I made a text adventure game called DazzleQuest that runs entirely in the developer console/terminal. It involves my friends as characters so I wanted to show it to them and gain experience with Java by transferring the functionality of the command line and output from the console to a simple Swing interface comprised of a JTextArea to show the game's output and a JTextField, with ActionListener, to handle commands from the user.

My main DazzleQuest class contains methods called run() and handleCommand(), which I figure I need to integrate with my Frame class and its subclass TextFieldHandler [which extends ActionListener]. I am wondering, in general, what is the best way to integrate these methods and classes. My current attempts have been confusing and though I have a basic grasp on how to make different classes and methods communicate, it is tentative.

Apologies for the wordiness and lack of specificity. I would share my code but am unsure of how much and exactly what to give. If you think you can answer my question but need an example of what I have, please say so. Even pseudocode as an answer would be appreciated. Thank you! Understanding this could be very helpful for my education as a programmer.

EDIT: Here are simplified examples of my code from the version of the game that runs entirely in the developer console. This is my main class DazzleQuest:

public class DazzleQuest {

public void run() {
    listCommands();
    for (;;) {
        StdOut.println(new StringBuilder("You are in ").append(currentRoom.getName()).append(".").toString());
        StdOut.println(new StringBuilder("You can go to: ").append(currentRoom.listExits()).toString());
        StdOut.print("> ");
        handleCommand(StdIn.readLine());
        StdOut.println();
    }

public void handleCommand(String line) {
        String[] words = line.split(" ");
        if (words[0].equals("look"))
            look();
        }
    }

}

And here is my current JFrame setup, in the Frame class:

import java.awt.FlowLayout;

import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JTextArea;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class Frame extends JFrame {

    public static JTextField field;
    public JTextArea area;

    public Frame() {
        setLayout(new FlowLayout());

        area = new JTextArea(20, 40);
        area.setEditable(false);

        field = new JTextField(20);
        add(area);
        add(field);
        pack();
        setVisible(true);

         TextFieldHandler handler = new TextFieldHandler();

            field.addActionListener(handler);
        }

        public class TextFieldHandler implements ActionListener{

            public void actionPerformed(ActionEvent event)
            {
                String line = field.getText();
                area.append(line + "\n");
                field.setText("");
            }
        }


    public static void main(String args[]) {

        Frame test = new Frame();
        test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

I know how to print output to the JTextArea instead of to the console. My issue is how exactly to get handleCommand() to work with actionPerformed() in the Frame class, or whether I should set up an action listener in the main class or something like that. Any examples of implementation would be greatly appreciated.

Thanks again for anything you can tell me!


Answer:

First, regarding including code, you should take a look at https://stackoverflow.com/help/mcve for how to help us help you.

Now, given that you haven't provided any code (yet!) giving suggestions on how you should structure your program is a bit tricky. But I'll make an attempt anyways and might edit the answer when you've provided a MWE.

In your case, JTextArea is really just a fancy System.out.print as you will only use it to display the text that your adventure game outputs (if I'm understanding you correctly). So basically, you can write a method that accepts a string, and that method will append that string to your JTextArea. Then just replace your current output-lines with this method.

Then you have your JTextField which you want to replace your (I'm guessing) Scanner(System.in) with. I assume you know how to set up an action listener that responds to Enter or a submit-button. How to set these up is not all that strange, and lots of guides talk about how to do it. https://docs.oracle.com/javase/tutorial/uiswing/components/textfield.html gives a good example.

Now, in general regarding the structure of your program. You do not want to be dependent on how the user enters the text or how you display it. What I mean with this is that you do not want input- or display-logic to meddle with your game (business) logic. Your game logic should just receive input, from where ever, and output it to where ever. How and what the calling functions then decide to do with the information is not for the game logic to care about.

So, applied to the method names you posted. I assume run() is where you kick things off. As you have output that you always want to display, you might want to pass in an interface here that has the method print(string) (or the like) which should be a method that prints the text to whatever text-element is used to display the text, be it System.out or JTextArea. The run() method never needs to know. handleCommand() should also just accept a value (I assume a String) and handle it like it should, no matter who or what called it.

I'm having trouble giving you more advice with no code. But my general recommendation is: Don't mix presentation logic with business logic. And give each method as little info as possible, because giving them more than they actually need usually leads to a less flexible flow and structure.


EDIT now that some code has been added.

I know how to print output to the JTextArea instead of to the console. My issue is how exactly to get handleCommand() to work with actionPerformed() in the Frame class

Go with the actionPerformed() approach. I recommend this because you won't have to bother with as much if you decide to Thread your application sometime in the future (multiplayer?). https://docs.oracle.com/javase/tutorial/uiswing/events/actionlistener.html gives some good info about how to write your listener. But I'll give you some suggestion code as well.

...
area.setEditable(false);

field = new JTextField(20);
field.addActionListener(new SendText());    
....

class SendText implements ActionListener{
    public void actionPerformed(ActionEvent ae){
        if(ae.getSource() == field){
            String str = field.getText();
            if(!str.equals("")){
                commandHandler.handle(str);
            }
        }
    }
}

And then rewrite your run() method

public void run(){
   ui.print(commandHandler.listCommands());

   while(true){
       if(commandHandler.continue()){
           ui.print(commandHandler.events());
       }
   }
}

So now you have a very small run() method that has no real tie-in to either the logic or the display. ui.print(str) is a method that your UI class (Frame in your case) that just appends what ever string is sent to it to it's drawing area, be it System.out or a JTextArea.

commandHandler is new. This is where your game logic should be. It has a method handle(string) which is your old handleCommand(string). It has a continue() method that returns a boolean. The boolean should be set to true whenever you want the story to continue, eg when the user enters a command. And finally events() (which is a bad name) that returns what has happened since the last command was sent in and gives the users options on what to do next. I've not done an implementation of that, as I just want to give the concept to you. The UI doesn't do any logic processing. The run() method doesn't expect anything, it just keeps checking if continue() is true. commandHandler is where all the bizz is.

Now, you do have a infinite loop running. So if you get any performance issues you could look into Thread. This model should support a move to it.

Question:


Answer:

If you're trying to add ints into an array:

Your code sets the text from the JTextField, and this seems the opposite of what you wish to do. Instead get the text from the JTextField via getText(), convert it to an int via Integer.parseInt(...), and then put it into your array.

Something like:

public void actionPerformed(ActionEvent evt) {
   String text = myTextField.getText();
   int myInt = Integer.parseInt(text); // better to surround with try/catch
   myArray[counter] = myInt;
   counter++; // to move to the next counter
}

If you're trying to do numeric calculations, then there is no need for an array, and your question would be very confusing.


Edit Regarding your comment:

So i cant split a string of numbers from a text field and say add them together ?

You could use a Scanner object to parse it:

public void actionPerformed(ActionEvent evt) {
   String text = myTextField.getText();
   Scanner scanner = new Scanner(text);
   // to add:
   int sum = 0;
   while (scanner.hasNextInt()) {
      sum += scanner.nextInt();
   }
   scanner.close();
   outputField.setText("Sum: " + sum);
}

or...

public void actionPerformed(ActionEvent evt) {
   List<Integer> list = new ArrayList<Integer>();
   String text = myTextField.getText();
   Scanner scanner = new Scanner(text);
   // to add to a list
   while (scanner.hasNextInt()) {
      list.add(scanner.nextInt());
   }
   scanner.close();

   // now you can iterate through the list to do all sorts of math operations
   // outputField.setText();
}

Question:

It replaces the num variable in text field every time I click a new button. I want it to show every new number one after another when I click different buttons and then eventually I will add/subtract/multiply and divide them and if possible you can give me an idea on how to do math operation on two different blocks of numbers. your help will be appreciated

private class TheHandler implements ActionListener{

    public void actionPerformed(ActionEvent e) {

        //add values to buttons
        String num = "";
        if(e.getSource()==btn[0]){
            //tDisplay.setText("7");
            num = "7";
        }else if(e.getSource()==btn[1]){
            //tDisplay.setText("8");
            num = "8";
        }else if(e.getSource()==btn[2]){
            //tDisplay.setText("9");
            num = "9";
        }else if(e.getSource()==btn[5]){
            //tDisplay.setText("4");
            num = "4";
        }else if(e.getSource()==btn[6]){
            //tDisplay.setText("5");
            num = "5";
        }else if(e.getSource()==btn[7]){
            //tDisplay.setText("6");
            num = "6";
        }else if(e.getSource()==btn[10]){
            //tDisplay.setText("1");
            num = "1";
        }else if(e.getSource()==btn[11]){
            //tDisplay.setText("2");
            num = "2";
        }else if(e.getSource()==btn[12]){
            //tDisplay.setText("3");
            num = "3";
        }else if(e.getSource()==btn[15]){
            //tDisplay.setText("0");
            num = "0";
        }

        //set the values to the text field

        tDisplay.setText(num);

    }

}

Answer:

Here is the code

tDisplay.setText(tDisplay.getText()+num);

Verifying if 0 was pressed first to avoid a number like this "015"

if (tDisplay.getText().equals("0"))
    tDisplay.setText(num);
else
    tDisplay.setText(tDisplay.getText()+num);

When you press an operator button must store the value and modify a flag, and when press the equal button store the second value written and perform the operation selected (with the value of the flag).

Question:

I am trying to validate integer values from a JTextField. I want to make sure the user only enters integer values between a set range. I tried working with a JFormattedTextField but so far no luck.


Answer:

One good option is to use an InputVerifier - your text field will not yield focus unless the input conditions are met. A JFormattedTextField won't do here since your restriction is not solely format, but also mathematical.

public class NumRange extends JFrame {

    public static void main(String[] args) {

        new NumRange();
    }

    NumRange() {

        final int MIN = 0;
        final int MAX = 100;

        JTextField textField = new JTextField();
        textField.setInputVerifier(new InputVerifier() {

            @Override
            public boolean verify(JComponent input) {
                String text = ((JTextField) input).getText();
                int num;
                try {
                    num = Integer.parseInt(text);
                } catch (NumberFormatException e) {
                    return false;
                }
                if (num <= MAX && num >= MIN)
                    return true;
                return false;
            }
        });

        getContentPane().add(textField);
        getContentPane().add(new JTextField(), BorderLayout.PAGE_END);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        pack();
        setVisible(true);
    }
}

Try to switch focus to the bottom text field after entering various inputs to the top one.