Hot questions for Using JTextField in jbutton

Question:

    private void vote1ActionPerformed(java.awt.event.ActionEvent evt) {                                      
    int vote1 = 0;
    int vote2 = 0;
    if (koonchk.isSelected()){
        vote1++;
    koontf.setText(Integer.toString(vote1));

    }
    else if (baamchk.isSelected()){
        vote2++;
    baamtf.setText(Integer.toString(vote2));

    }


}                                     

How do I increase the number in the JTextField every time I press the JButton?


Answer:

You need to store int vote1 and vote2 outside of your method for vote1ActionPerformed, so that you dont reset the vote count to 0 every time.

That way its really easy to update it to a bigger number each time. For example this would work:

//Moved vote1/2 here outside of the method
static int vote1 = 0;
static int vote2 = 0;

    private void vote1ActionPerformed(java.awt.event.ActionEvent evt){                                      
        //We removed vote1 and vote2 from here and put them above
        if (koonchk.isSelected()){
        vote1++;
        koontf.setText(Integer.toString(vote1));
        }
        else if (baamchk.isSelected()){
        vote2++;
        baamtf.setText(Integer.toString(vote2));
        }
    }

Question:

I have my three JButtons located where I want them (at the top center of the frame), and when the user clicks one, a JTextField pops up in the BoxLayout like wanted.

The problem is, when the JTextField shows up, it is to the left of the buttons, and it moves them.

I tried setting the alignment of the JTextField and using various glues, but the JTextField doesn't move.

If I want to have the JTextField pop up below my JButtons and in the center of the screen, what should I use?

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;

public class Library extends JFrame implements ActionListener {

    private JFrame jf1;
    private JPanel jp1;
    private JTextField jtf1;
    private JButton jb1;
    private JButton jb2;
    private JButton jb3;

    public Library() {
        try {
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch(Exception q) {
        q.printStackTrace();
        }
    JFrame.setDefaultLookAndFeelDecorated(false);
    jf1 = new JFrame("Library");
    jf1.setVisible(true);
    jf1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    jf1.setSize(1080, 900);
    jf1.setResizable(true);

    Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
    jf1.setLocation(dim.width/2-jf1.getSize().width/2, dim.height/2-jf1.getSize().height/2);

    jp1 = (JPanel) jf1.getContentPane();
    jp1.setLayout(new BoxLayout(jp1, BoxLayout.LINE_AXIS));

    jb1 = new JButton("Genre");
    jb1.addActionListener(this);
    jb1.setMinimumSize(new Dimension(140, 60));
    jb1.setPreferredSize(new Dimension(150, 60));
    jb1.setMaximumSize(new Dimension(150, 60));
    jb1.setAlignmentY(-70.0f);
    jb2 = new JButton("Author");
    jb2.addActionListener(this);
    jb2.setMinimumSize(new Dimension(140, 60));
    jb2.setPreferredSize(new Dimension(150, 60));
    jb2.setMaximumSize(new Dimension(150, 60));
    jb2.setAlignmentY(-70.0f);
    jb3 = new JButton("Title");
    jb3.addActionListener(this);
    jb3.setMinimumSize(new Dimension(140, 60));
    jb3.setPreferredSize(new Dimension(150, 60));
    jb3.setMaximumSize(new Dimension(150, 60));
    jb3.setAlignmentY(-70.0f);



    jp1.add(Box.createHorizontalGlue());
    jp1.add(jb1);
    jp1.add(jb2);
    jp1.add(jb3);
    jp1.add(Box.createHorizontalGlue());

    jf1.validate();
}

@Override
public void actionPerformed(ActionEvent e) {
    Object code = e.getSource();
    if (code == jb1) {
        jtf1 = new JTextField("Enter Text");
        jtf1.setPreferredSize(new Dimension(200,20));
        jtf1.setMaximumSize(new Dimension(200,20));
        jtf1.setMinimumSize(new Dimension(10,10));
        jp1.add(jtf1);

        jp1.validate();
    }
    else if (code == jb2) {

    }
    else if (code == jb3) {

    }
}

public static void main(String[] args) {
    Library shoe = new Library();
    }
}

Answer:

Suggestion: do not add/remove UI elements dynamically. Just add all of those things initially, and simply call setVisible(false) on your text field then.

(instead of adding/removing fields using your action listener)

Question:

I am trying to create connection between the JTextField , JButton and url that if i click the button the code opens the url for count purposes. I tried several way down below one of my attempt.

I get an error. How to fix that ?

 @Override
            public void actionPerformed(ActionEvent event) {
                String input  =   textField.getText();
                URL book = null;
                try {
                    book = new URL("input");
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                }
                BufferedReader in = null;
                try {
                    in = new BufferedReader(new InputStreamReader(book.openStream(), StandardCharsets.ISO_8859_1));
                } catch (IOException e) {
                    e.printStackTrace();
                }

I get a very long error message here is a part of it:

java.net.MalformedURLException: no protocol: input
at java.net.URL.<init>(URL.java:593)
at java.net.URL.<init>(URL.java:490)
at java.net.URL.<init>(URL.java:439)
at Main$1.actionPerformed(Main.java:44)

Answer:

You are trying to open the URL "input" (a String) instead of what you read from the textfield. PLease compare

book = new URL("input");

to

book = new URL(input);

Question:

I'm really struggling to find the functionality (if it even exists), to move a JTextFields cursor by clicking a Button, instead of using the mouse.

For instance, I have my text field with a string added. By clicking a back button, the cursor will move back through the string, 1 position at a time or forward depending on which button is pressed.

I can do it with the mouse, just click and type, but I actually need to have it button based so that the user can choose to use the keypad to enter a name or just click into the JTextArea and type away.

Is it possible? What methods should I look for if so.

Thank you.


Answer:

These are sample buttons that are doing what you're asking for:

btnMoveLeft = new JButton("-");
btnMoveLeft.setFocusable(false);
btnMoveLeft.addActionListener(new ActionListener() {
  public void actionPerformed(ActionEvent arg0) {
    txtAbc.setCaretPosition(txtAbc.getCaretPosition() - 1); // move the carot one position to the left
  }
});
// omitted jpanel stuff

btnmoveRight = new JButton("+");
btnmoveRight.setFocusable(false);
btnmoveRight.addActionListener(new ActionListener() {
  public void actionPerformed(ActionEvent e) {
    txtAbc.setCaretPosition(txtAbc.getCaretPosition() + 1); // move the carot one position to the right
  }
});
// omitted jpanel stuff

They are moving the carot in the textfield txtAbc with 1 position per click. Notice, that you need to disable the focusable flag for both buttons, or the focus of your textfield will be gone if you click one of these buttons and you can't see the carot anymore.

To avoid exceptions if you're trying to move the carot out of the textfield boundaries (-1 or larger than the text length), you should check the new values (for example in dedicated methods):

private void moveLeft(int amount) {
    int newPosition = txtAbc.getCaretPosition() - amount;
    txtAbc.setCaretPosition(newPosition < 0 ? 0 : newPosition);
}

private void moveRight(int amount) {
    int newPosition = txtAbc.getCaretPosition() + amount;
    txtAbc.setCaretPosition(newPosition > txtAbc.getText().length() ? txtAbc.getText().length() : newPosition);
}

Question:

I am trying to create a password vault, but whenever I try to run it, the JTextFields are extremely small and the panel is somewhat being covered by the JTable.

I have tried playing with the dimensions and the positions of the GridBag but nothing works.

This is for my IB Computer Science IA. Any help would be great.

    JFrame passwordVault;
    JTable passwordTable;
    Object[] columnNames = {"Name of Application", "Application Password", "Description"};
    JTextField appName, appPass, appDesc;
    JButton add, delete, update;
    JLabel nameOfApp, passOfApp, descOfApp;

    passwordVault = new JFrame("Password Vault");
    passwordTable = new JTable();
    JPanel passwordPanel = new JPanel();

    DefaultTableModel tableModel = new DefaultTableModel();
    tableModel.setColumnIdentifiers(columnNames);
    passwordTable.setModel(tableModel);

    nameOfApp = new JLabel("App Name: ");
    passOfApp = new JLabel("App Password: ");
    descOfApp = new JLabel("Description: ");    

    appName = new JTextField();
    appPass = new JTextField();
    appDesc = new JTextField();

    add = new JButton("Add");
    delete = new JButton("Delete");
    update = new JButton("Update");  

    appName.setBounds(400, 220, 100, 25);
    appPass.setBounds(400, 250, 100, 25);
    appDesc.setBounds(400, 280, 100, 25);

    add.setBounds(530, 220, 100, 25);
    update.setBounds(530, 250, 100, 25);
    delete.setBounds(530, 280, 100, 25);

    JScrollPane scrollPane = new JScrollPane(passwordTable);
    scrollPane.setBounds(0, 0, 1000, 200);
    passwordVault.add(scrollPane);

    passwordPanel.add(add);
    passwordPanel.add(update);
    passwordPanel.add(delete);

    passwordPanel.setLayout(new GridBagLayout());

    passwordPanel.add(nameOfApp, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0,
        GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
    passwordPanel.add(appName, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0,
        GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
    passwordPanel.add(passOfApp, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0,
        GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
    passwordPanel.add(appPass, new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0,
        GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
    passwordPanel.add(descOfApp, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0,
        GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
    passwordPanel.add(appDesc, new GridBagConstraints(2, 2, 1, 1, 0.0, 0.0,
        GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
    passwordPanel.add(add, new GridBagConstraints(3, 3, 1, 1, 0.0, 0.0,
            GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
    passwordPanel.add(update, new GridBagConstraints(4, 3, 1, 1, 0.0, 0.0,
            GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
    passwordPanel.add(delete, new GridBagConstraints(5, 3, 1, 1, 0.0, 0.0,
            GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));

    passwordVault.add(passwordPanel);
    passwordVault.setSize(1000,500);
    passwordVault.setLocationRelativeTo(null);
    passwordVault.setVisible(true);

Answer:

Here is an edited version of your program that formats the layout how I think you were trying to:

        JFrame passwordVault;
        JTable passwordTable;
        Object[] columnNames = {"Name of Application", "Application Password", "Description"};
        JTextField appName, appPass, appDesc;
        JButton add, delete, update;
        JLabel nameOfApp, passOfApp, descOfApp;

        passwordVault = new JFrame("Password Vault");
        passwordTable = new JTable();
        JPanel passwordPanel = new JPanel();

        DefaultTableModel tableModel = new DefaultTableModel();
        tableModel.setColumnIdentifiers(columnNames);
        passwordTable.setModel(tableModel);

        nameOfApp = new JLabel("App Name: ");
        passOfApp = new JLabel("App Password: ");
        descOfApp = new JLabel("Description: ");    

        appName = new JTextField();
        appPass = new JTextField();
        appDesc = new JTextField();

        add = new JButton("Add");
        delete = new JButton("Delete");
        update = new JButton("Update");  

        // Used setPreferredSize and setLocation instead of setBounds
        appName.setLocation(new Point(400, 220));
        appName.setPreferredSize(new Dimension(100, 25));
        appPass.setLocation(new Point(400, 250));
        appPass.setPreferredSize(new Dimension(100, 25));
        appDesc.setLocation(new Point(400, 280));
        appDesc.setPreferredSize(new Dimension(100, 25));

        add.setLocation(new Point(530, 220));
        add.setPreferredSize(new Dimension(100, 25));
        update.setLocation(new Point(530, 250));
        update.setPreferredSize(new Dimension(100, 25));
        delete.setLocation(new Point(530, 280));
        delete.setPreferredSize(new Dimension(100, 25));

        JScrollPane scrollPane = new JScrollPane(passwordTable);
        scrollPane.setBounds(0, 0, 1000, 200);

        // Create a JPanel to contain the scrollPane and passwordPanel
        JPanel framePanel = new JPanel();
        framePanel.setLayout(new GridLayout(2, 1));

        framePanel.add(scrollPane);

        passwordPanel.setLayout(new GridBagLayout());

        passwordPanel.add(nameOfApp, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0,
            GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
        passwordPanel.add(appName, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0,
            GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
        passwordPanel.add(passOfApp, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0,
            GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
        passwordPanel.add(appPass, new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0,
            GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
        passwordPanel.add(descOfApp, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0,
            GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
        passwordPanel.add(appDesc, new GridBagConstraints(1, 2, 1, 1, 0.0, 0.0,
            GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
        passwordPanel.add(add, new GridBagConstraints(0, 3, 1, 1, 0.0, 0.0,
                GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
        passwordPanel.add(update, new GridBagConstraints(1, 3, 1, 1, 0.0, 0.0,
                GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
        passwordPanel.add(delete, new GridBagConstraints(2, 3, 1, 1, 0.0, 0.0,
                GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));

        framePanel.add(passwordPanel);

        // Add the framePanel (which contains the other 2 panels) to the JFrame
        passwordVault.add(framePanel);

        passwordVault.setSize(1000,500);
        passwordVault.setLocationRelativeTo(null);
        passwordVault.setVisible(true);

So, the main changes were:

  1. Used setPreferredSize and setLocation, instead of setBounds for the JTextFields and JButtons
  2. Created a main JPanel (called it framePanel) to contain the scrollPane and passwordPanel, and then added framePanel to the JFrame

It helps to organize the different elements in a JFrame by creating a main JPanel, instead of just adding multiple JPanels to the JFrame itself. That way, the one main JPanel decides the overall layout of the frame.

Question:

I am experimenting JButton's action and I am trying to clear a textfield in class Test2 using a button in class Test1. Here is the code

public class Test2 {
private JFrame frame;
private JTextField t1;
private JTextField t2;

/**
 * Launch the application.
 */
public void start() {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                test2 window = new test2();
                window.frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the application.
 */
public test2() {
    initialize();
}
public void Reset(){
    t1 = new JTextField();
    t1.setText("");

}
/**
 * Initialize the contents of the frame.
 */
private void initialize() {
    frame = new JFrame();
    frame.setBounds(100, 100, 450, 300);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    t1 = new JTextField();
    t1.setColumns(10);
    t1.setText("Start");


    GroupLayout groupLayout = new GroupLayout(frame.getContentPane());
    groupLayout.setHorizontalGroup(
        groupLayout.createParallelGroup(Alignment.LEADING)
            .addGroup(groupLayout.createSequentialGroup()
                .addGap(35)
                .addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
                    .addComponent(t2, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                    .addComponent(t1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
                .addContainerGap(281, Short.MAX_VALUE))
    );
    groupLayout.setVerticalGroup(
        groupLayout.createParallelGroup(Alignment.LEADING)
            .addGroup(groupLayout.createSequentialGroup()
                .addGap(38)
                .addComponent(t1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                .addGap(75)
                .addComponent(t2, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                .addContainerGap(98, Short.MAX_VALUE))
    );
    frame.getContentPane().setLayout(groupLayout);
}

}

public class Test1 {

private JFrame frame;



/**
 * Launch the application.
 */
static test1 window = new test1();
static test2 window2 = new test2();
private JTextField textField;
private JTextField ownText;
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                window2.start();
                window.frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the application.
 * @wbp.parser.entryPoint
 */
public test1() {
    initialize();
}

/**
 * Initialize the contents of the frame.
 */
private void initialize() {
    frame = new JFrame();
    frame.setBounds(100, 100, 450, 300);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JButton btnNewButton = new JButton("New button");
    btnNewButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            String test ="";
            window2.Reset(test);

        }
    });
    frame.getContentPane().add(btnNewButton, BorderLayout.WEST);

    ownText = new JTextField();
    frame.getContentPane().add(ownText, BorderLayout.EAST);
    ownText.setColumns(10);


}

}

At the moment, when I click the button in Test1 class, the textfield in Test2 class is not cleared. Hope to have advice from all the seniors here. Let me know too if my questions has any shortcomings. Thank you so much.


Answer:

Updated your Reset() method with this

public void Reset(){
        t1.setText("");     
}

You can't instantiate the Text Field again in Reset method.Because frame contain text field.Please read the Java Coding rule use reset() instead of Reset()

UPDATED Also one thing is you use two instant of Test2. So you make your start() method in Test2 like that

public void start() {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                //test2 window = new test2();
                 frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

Question:

I'm newbie in Java programming.

I'm trying to test a program where there is at least four(4) JButton and there are at least three(3) JTextField. Let say Button A,B,C, and D, then Textfield 1, 2, and 3.

What I want to happen is that: when I click any of the Button. The first Textfield, let's say 1 will hold a string text. And when I click another button the second Textfield will now hold the string since 1 already holds a string text. However the tricky part is when all the textfields holds a string. When i click a button again, "textfield 1" will be overwritten from the clicked button. Then 2 and the cycle will be repeated.

package testing;


public class NewJFrame extends javax.swing.JFrame {


public NewJFrame() {
    initComponents();
}

 private void initComponents() {

    jButton1 = new javax.swing.JButton();
    jButton2 = new javax.swing.JButton();
    jButton3 = new javax.swing.JButton();
    jButton4 = new javax.swing.JButton();
    jTextField1 = new javax.swing.JTextField();
    jTextField2 = new javax.swing.JTextField();
    jTextField3 = new javax.swing.JTextField();
    jTextField4 = new javax.swing.JTextField();

}                 

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
   jTextField1.setText("A");

}                                        

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    jTextField1.setText("B");
}                                        

private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    jTextField1.setText("C");
}                                        

private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    jTextField1.setText("D");
}                                        


public static void main(String args[]) {

    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new NewJFrame().setVisible(true);
        }
    });
}

Answer:

Please note that this code was written before the OP posted his code, but I think it will still solve the issue and therefore be worth an answer


I just created an example that should help you with this, it will work with any amount of buttons and textfields (except it's <= 0).

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;

public class Examplerino {

    ArrayList<JTextField> tfs = new ArrayList<JTextField>();
    ArrayList<JButton> bts = new ArrayList<JButton>();

    int counter = 0;

    int amountBts = 4;
    int amountTfs = 3;

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new Examplerino();
            }
        });
    }

    public Examplerino() {

        JFrame frame = new JFrame();
        frame.getContentPane().setLayout(new FlowLayout());

        // Add new buttons to bts
        for (int i = 0; i < amountBts; i++) {
            bts.add(new JButton("b" + (i + 1)));
        }

        // Add new textfields to tfs
        for (int i = 0; i < amountTfs; i++) {
            tfs.add(new JTextField(3));
        }

        // Add buttons with action listener to the frame
        for (JButton b : bts) {
            b.addActionListener(new ButtonActionListener());
            frame.getContentPane().add(b);
        }

        // Add textfields to frame
        for (JTextField tf : tfs) {
            tf.setEditable(false);
            frame.getContentPane().add(tf);
        }

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(500, 500);
        frame.setVisible(true);

    }

    public class ButtonActionListener implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {
            if (counter >= tfs.size()) {
                counter = 0;
            }
            tfs.get(counter).setText(((JButton) e.getSource()).getText());
            counter++;
        }
    }

}

Question:

I'm developing a swing application. In that I've a JFrame which add JTextfield and JButton dynamically on the button click.and remove the created components if the user clicks the same button.

In the below screen image , when user clicks ADD button new row was added, and text was changed to REMOVE like in 2nd image.

New Row added and previous button text changed to REMOVE.

Now, if I click the REMOVE button, then the newly added row has to dispose and then button has to change the text again to ADD.

I've tried till adding the components, but I stuck up with removing the newly added row.

Anyone please guide me to achieve this.

Below is my code.

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.util.ArrayList;
 import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRootPane;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class ButtonAddDynamic implements ActionListener {

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

private JFrame frame;
private JPanel panel = new JPanel(new GridBagLayout());
private GridBagConstraints constraints = new GridBagConstraints();

private List fields = new ArrayList();
private List fieldButton = new ArrayList();
private List fieldFile = new ArrayList();

private static int countReport = 0;
String files = null;
int y = 2;

protected void createAndShowGUI() {
    try {
        UIManager
                .setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
    } catch (UnsupportedLookAndFeelException ex) {
        ex.printStackTrace();
    } catch (InstantiationException ex) {
        ex.printStackTrace();
    } catch (ClassNotFoundException ex) {
        ex.printStackTrace();
    } catch (IllegalAccessException ex) {
        ex.printStackTrace();
    }

    String[] labels = { "VALIDATION FORM" };
    for (String label : labels)
        addColumn(label);

    frame = new JFrame("Add Button Dynamically");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.add(new JScrollPane(panel));
    frame.setLocationRelativeTo(null);
    frame.setResizable(false);
    frame.pack();
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);

    // Set the default button to button1, so that when return is hit, it
    // will hit the button1

    frame.addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent we) {
            System.exit(0);
        }
    });
}

private void addColumn(String labelText) {
    constraints.gridx = fields.size();
    constraints.gridy = 1;
    panel.add(new JLabel(labelText), constraints);
    constraints.gridy = 2;
    final JTextField field = new JTextField(40);
    field.setEditable(false);
    panel.add(field, constraints);
    fields.add(field);

    // constraints.gridy=3;
    constraints.gridx = fields.size() + fieldButton.size();
    final JButton button = new JButton("ADD");
    button.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ae) {

            if (button.getText().equals("ADD")) {
                button.setText("REMOVE");
                addRowBelow();
                frame.pack();
            } else if (button.getText().equals("REMOVE")) {
                button.setText("ADD");

                frame.pack();
            }

        }
    });
    panel.add(button, constraints);
    fieldButton.add(button);
    panel.revalidate(); // redo layout for extra column
}

private void addRowBelow() {
    y++;
    constraints.gridy = y;

    // System.out.println(fields.size());
    for (int x = 0; x < fields.size(); x++) {
        constraints.gridx = x;
        final JTextField field = new JTextField(40);
        field.setEditable(false);
        panel.add(field, constraints);
        constraints.gridx = x + 1;
        final JButton button = new JButton("ADD");
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                if (button.getText().equals("ADD")) {
                    button.setText("REMOVE");
                    addRowBelow();
                    frame.pack();
                } else if (button.getText().equals("REMOVE")) {
                    button.setText("ADD");

                    frame.pack();
                }
            }
        });
        panel.add(button, constraints);
    }
}

public void actionPerformed(ActionEvent ae) {
    if ("Add Another TextField and Button".equals(ae.getActionCommand())) {
        addRowBelow();
        frame.pack();
        frame.setLocationRelativeTo(null);
    }
}
}

Answer:

Trying to use GridBagLayout is making this very complicated for you. A nested layout scheme is much easier to work with when you are doing this type of thing.

See this MCVE:

I'm not sure I understood your intended functionality 100% correct but I don't think it's as important as the layouts.

My layout scheme is as follows:

This is nice because BoxLayout will handle the vertical listing without much hullabaloo. Instead of having to wrangle with GridBagConstraints, the text field and button are contained together by a panel.

import javax.swing.*;
import java.awt.event.*;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Insets;

public class FieldList implements Runnable, ActionListener {
    public static void main(String... args) {
        SwingUtilities.invokeLater(new FieldList());
    }

    final int maxFields = 2;

    JFrame frame;
    JPanel listing;

    @Override
    public void run() {
        frame = new JFrame("Text Field Listing");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel content = new JPanel(new BorderLayout());
        content.add(new JLabel("Input Form", JLabel.CENTER), BorderLayout.NORTH);

        listing = new JPanel();
        listing.setLayout(new BoxLayout(listing, BoxLayout.Y_AXIS));

        content.add(listing, BorderLayout.CENTER);
        frame.setContentPane(content);

        addNewField();

        frame.pack();
        frame.setResizable(false);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    void addNewField() {
        FieldButtonPair field = new FieldButtonPair();
        field.button.addActionListener(this);
        listing.add(field);
        frame.pack();
    }

    void removeLastField() {
        listing.remove(listing.getComponentCount() - 1);
        frame.pack();
    }

    @Override
    public void actionPerformed(ActionEvent ae) {
        AddRemoveButton source = (AddRemoveButton)ae.getSource();

        if(source.state == AddRemoveButton.State.ADD) {
            if(listing.getComponentCount() < maxFields) {
                addNewField();
                source.setState(AddRemoveButton.State.REMOVE);
            }
        } else if(source.state == AddRemoveButton.State.REMOVE) {
            removeLastField();
            source.setState(AddRemoveButton.State.ADD);
        }
    }
}

class FieldButtonPair extends JPanel {
    JTextField field;
    AddRemoveButton button;

    FieldButtonPair() {
        super(new BorderLayout());
        field = new JTextField();
        add(field, BorderLayout.CENTER);
        button = new AddRemoveButton();
        add(button, BorderLayout.EAST);
    }

    @Override
    public Dimension getPreferredSize() {
        Dimension pref = super.getPreferredSize();
        pref.width = Math.max(480, pref.width);
        return pref;
    }
}

class AddRemoveButton extends JButton {
    enum State { ADD, REMOVE }

    State state = State.ADD;

    AddRemoveButton() {
        setText(state.name());
    }

    void setState(State state) {
        setText(state.name());
        this.state = state;
    }

    @Override
    public Dimension getPreferredSize() {
        Dimension pref = super.getPreferredSize();

        Font f = getFont();
        FontMetrics fm = getFontMetrics(f);
        int w = fm.stringWidth(State.REMOVE.name());
        Insets ins = getInsets();

        pref.width = (ins.left + w + ins.right);
        return pref;
    }
}

Question:

I have a JTextField and a JButton. I'm trying to get what user types in the textfield when they click the button.

public String insideTextField;

public void login() {

    loginFrame = new JFrame("Test");
    loginFrame.setIconImage(imageIcon.getImage());
    loginFrame.setSize(400,400);
    loginFrame.setLayout(new GridLayout(12, 3));

    loginFrame.add(usernameField);
    loginFrame.add(loginButton);

    loginButton.addActionListener(e -> {

        insideTextField = usernameField.getText();
        loginFrame.setVisible(false);
    });

    loginFrame.setVisible(true);
}

and I expect the insideTextField to be what user types in the text field after I called this method. but it is null. However, the loginFrame will be hidden because of loginFrame.setVisible(false); so the button is working !

what am I doing wrong?


Answer:

Your expectations involve magical thinking. Understand that insideTextField holds a String object, an object which in fact is immutable (cannot be changed). Yes, when you create the insideTextField you assign to it the String that just so happens to be residing within the JTextField, likely an empty "" String, but understand that when the JTextField's text properties change, the insideTextField will not, and in fact cannot magically change on its own. The solution is to not have a insideTextField field, and instead give the class a getter method that extracts the current String within the JTextField when it is needed. For example:

public String getUserName() {
    return usernameField.getText();
}

Side note: I usually use a modal JDialog and not a JFrame to get log-in credentials. This way since the dialog is modal, I know when the user is done using it. And in fact a JOptionPane works as a quick and dirty modal dialog creator. For example if we had a login JPanel like so:

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

import javax.swing.BorderFactory;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

@SuppressWarnings("serial")
public class LoginPanel extends JPanel {
    private static final int GAP = 3;
    private JTextField usernameField = new JTextField(10);
    private JPasswordField passwordField = new JPasswordField(10);

    public LoginPanel() {
        setLayout(new GridBagLayout());
        GridBagConstraints gbc = getGbc(0, 0);
        add(new JLabel("User Name:"), gbc);
        gbc = getGbc(1, 0);
        add(usernameField, gbc);
        gbc = getGbc(0, 1);
        add(new JLabel("Password:"), gbc);
        gbc = getGbc(1, 1);
        add(passwordField, gbc);
        setBorder(BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP));
    }

    private static GridBagConstraints getGbc(int x, int y) {
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridx = x;
        gbc.gridy = y;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.weightx = 1.0;
        gbc.weighty = 1.0;
        gbc.insets = new Insets(GAP, GAP, GAP, GAP);
        gbc.anchor = x == 0 ? GridBagConstraints.WEST : GridBagConstraints.EAST;        

        return gbc;
    }

    public String getUserName() {
        return usernameField.getText();
    }

    public char[] getPassword() {
        return passwordField.getPassword();
    }
}

again one that uses getter methods to extract the text in the JTextField, we could display it in a JOptionPane like so:

JFrame frame = new JFrame("LoginExample");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// fill the JFrame with the main GUI
// .... 

frame.pack();

// create the LoginPanel JPanel here
LoginPanel loginPanel = new LoginPanel();

// and display it in a JOptionPane here
int result = JOptionPane.showConfirmDialog(frame, loginPanel, 
        "User Log-In", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
if (result == JOptionPane.OK_OPTION) {
    String userName = loginPanel.getUserName();
    char[] password = loginPanel.getPassword();

    // test to make sure code is working
    System.out.println("User Name: " + userName);

    // check for name/password validity here
    // ... if name/password OK, then show JFrame:
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
}

Question:

My program is meant to display 4 buttons each with a number, then depending on the button pressed the next screen will show a different number of JTextFields, but when any of the buttons are pressed the next panel is blank? Any help and suggestions are greatly appreciated thanks.

public class TestGui {

  static int playersSelected = 0;

    public static void main(String[] args) {
    JFrame gameWindow = new JFrame("Trivial Pursuit");
    gameWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    gameWindow.setSize(800, 650);
    gameWindow.setVisible(true);

    JPanel mainMenu = new JPanel();

    //create layout for main menu
    mainMenu.setLayout(new FlowLayout(FlowLayout.CENTER));

    //add the contents of the main menu panel to the application window
    gameWindow.add(mainMenu);

    JButton[] playerButton = new JButton[4];
    for (int i = 0; i < playerButton.length; i++) {
        final int FinalI = i;
        playerButton[i] = new JButton("Button " + i);
        mainMenu.add(playerButton[i]);
        playerButton[i].setOpaque(true);
        playerButton[i].setPreferredSize(new Dimension(271, 123));
        playerButton[i].setContentAreaFilled(true);
        playerButton[i].setBorder(BorderFactory.createEmptyBorder());

        playerButton[i].addMouseListener(new java.awt.event.MouseAdapter() {
            @Override
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                playerButton[FinalI].setBorder(BorderFactory.createLoweredBevelBorder());
            }

            @Override
            public void mouseExited(java.awt.event.MouseEvent evt) {
                playerButton[FinalI].setBorder(BorderFactory.createEmptyBorder());
            }
        });
    }

    JLabel[] playerNumberText = new JLabel[5];
    JTextField[] createPlayers = new JTextField[5];

    JPanel createPlayersPanel = new JPanel();
    createPlayersPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
    createPlayersPanel.setVisible(true);

    for (int i = 1; i <= playersSelected; i++) {
        final int finalI = i;
        createPlayers[i] = new JTextField("Player " + i + " input name here");
        createPlayers[i].setPreferredSize(new Dimension(160, 20));

        playerNumberText[i] = new JLabel();
        playerNumberText[i].setText("Player " + i);
        playerNumberText[i].setPreferredSize(new Dimension(350, 100));
        playerNumberText[i].setHorizontalAlignment(SwingConstants.CENTER);
        createPlayersPanel.add(playerNumberText[i]);

        createPlayers[i].addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (createPlayers[finalI].getText().equals("Player " + finalI + " input name here")) {
                    createPlayers[finalI].setText("");
                }
            }
        });
    }

    for (int i = 0; i < playerButton.length; i++) {
        final int finalI = i;
        playerButton[i].addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent ae) {
                gameWindow.remove(mainMenu);
                gameWindow.add(createPlayersPanel);
                switch (finalI) {
                    case 0:

                        playersSelected = 2;
                        break;
                    case 1:

                        playersSelected = 3;

                        break;
                    case 2:

                        playersSelected = 4;

                        break;
                    case 3:

                        break;
                }
                gameWindow.revalidate();
                gameWindow.repaint();
                System.out.println(playersSelected);
            }
          });
      }
  }
}

Answer:

At creation time, your createPlayersPanel JPanel is empty since playerSelected is 0.

In your action listener, this panel is never updated, so it remains an empty panel.

What you could do is create a method to dynamically build the panel instead of building it only on startup. As playerSelected is only used here, you can remove this static variable and pass the value directly from your action listener.

    private static JPanel buildPlayersPanel(int playerSelected) { 

        JPanel createPlayersPanel = new JPanel();
        createPlayersPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
        createPlayersPanel.setVisible(true);

        for (int i = 1; i <= playersSelected; i++) {
            final int finalI = i;
            createPlayers[i] = new JTextField("Player " + i + " input name here");
            createPlayers[i].setPreferredSize(new Dimension(160, 20));

            playerNumberText[i] = new JLabel();
            playerNumberText[i].setText("Player " + i);
            playerNumberText[i].setPreferredSize(new Dimension(350, 100));
            playerNumberText[i].setHorizontalAlignment(SwingConstants.CENTER);
            createPlayersPanel.add(playerNumberText[i]);
            createPlayersPanel.add(createPlayers[i]);

            createPlayers[i].addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    if (createPlayers[finalI].getText().equals("Player " + finalI + " input name here")) {
                        createPlayers[finalI].setText("");
                    }
                }
            });
        }

   return createPlayersPanel;

}

And inside the action listener :

            @Override
            public void actionPerformed(ActionEvent ae) {

                int playersSelected  = 0;

                switch (finalI) {
                    case 0:

                        playersSelected = 2;
                        break;
                    case 1:

                        playersSelected = 3;

                        break;
                    case 2:

                        playersSelected = 4;

                        break;
                    case 3:

                        break;
                }
                gameWindow.remove(mainMenu);
                gameWindow.add(buildPlayersPanel(playersSelected));
                gameWindow.revalidate();
                gameWindow.repaint();
                System.out.println(playersSelected);
            }

Question:

I have just started programming in Swing. I am making a Fitness application using Swing. I have 2 questions:

  1. Whenever I click 'Calculate Scales' it should display the results only once, but it is displaying as many times as I click. How can I solve this?
  2. How can I set limit of JTextField up to 3 digits in my code?

Here is my code. Correct me if I am going wrong somewhere. Suggest me where I can make improvements.


import javax.swing.*;
import java.awt.*;
import java.awt.event.*;//since obsolete
class H1 extends JFrame implements ActionListener
{
 JLabel l1,l2,l3,l4,l5;
 JTextField t1,t2,t3;
 JRadioButton r1,r2;
ButtonGroup bg1;
JLabel bmr;
  JLabel bmi;
int click=0;
JButton b1,b2;Container c1;
 public static void main(String args[])
 {

  H1 j1 =new H1();
  j1.setTitle("Personal  Scales ");
  j1.setSize(1000,1000);
  j1.setVisible(true);
  j1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  j1.pack();
 }

H1()
{

c1=this.getContentPane();
setLayout(new BoxLayout(c1,BoxLayout.Y_AXIS));


JPanel j1 = new JPanel();
j1.setLayout(new FlowLayout());
t1 = new JTextField(10);
l1=new JLabel("Height");
j1.add(l1);
j1.add(t1);
c1.add(j1);


JPanel j2 = new JPanel();
j2.setLayout(new FlowLayout());
l2=new JLabel("Weight");
t2 = new JTextField(10);
j2.add(l2);
j2.add(t2);
c1.add(j2);



JPanel j3 = new JPanel();
j3.setLayout(new FlowLayout());
l3=new JLabel("Age");
t3 = new JTextField(10);
j3.add(l3);
j3.add(t3);
c1.add(j3);


JPanel j4 = new JPanel();
j4.setLayout(new FlowLayout());
l4=new JLabel("Sex");
bg1=new ButtonGroup();
r1=new JRadioButton("M");
r2=new JRadioButton("F");
bg1.add(r1);//button grouping is done to avoid multiple selection of radio button
bg1.add(r2);
j4.add(l4);
j4.add(r1);
j4.add(r2);
c1.add(j4);


JPanel j5 = new JPanel();
j5.setLayout(new FlowLayout());

b1=new JButton("Calculate Scales");//creating instance of JButton  
j5.add(b1);
c1.add(j5);
b1.addActionListener(this);

}

public void actionPerformed(ActionEvent e)
 { 

  click +=1;
  //JLabel bmr;
  //JLabel bmi;
  long ht=Long.parseLong(t1.getText());
  long wt=Long.parseLong(t2.getText());
  long age=Long.parseLong(t3.getText());
  //JPanel j6 = new JPanel();

  //j6.setLayout(new FlowLayout());


  double bmi1 = wt/Math.pow((ht * 0.01),2);

  String bmi2 = Double.toString(bmi1);//since double  cant be added to container 

  bmi=new JLabel("BMI     "+bmi2); 

  //c1.add(j6);
 // JPanel j7 = new JPanel();
  //j7.setLayout(new FlowLayout());

  double bmr1;String bmr2;

if(r1.isSelected())
  bmr1 = 66.47 +(13.75 * wt) + (5.003 * ht) - (6.775 * age);

else

  bmr1 = 655.1 +(9.563 * wt) + (1.85 * ht) - (4.676 * age);


 bmr2=Double.toString(bmr1);
 bmr=new JLabel("BMR     "+bmr2);

if(click>1)
  {
   c1.remove(bmi);
   c1.remove(bmr);
  }

/*j6.add(bmi);
j6.add(bmr);*/

  c1.add(bmi);
  c1.add(bmr);

}
}

Answer:

I'm also newer to java, so correct me if I'm wrong and cause of that, I can't write you a comment and have to write an answer ;)

As I can see it, you make a new JLabel each time you click the Button. Try to use eg. bmi.setText("BMI here" + bmi2); for your result description through setText() you only change the Text in this label. And also as variable declaration use JLabel bmi = null;

Maybe you also can add a JPanel to display your result to get the JLabel a fixed position and initializing it.

I hope that I can help you ;) Zorian

Question:

I just want to know how to do a new frame via typing a specific character then if you click the Jbutton, all the information (of that character) will pop up - for example a picture or a text.

For example, if I type the word "Dog", a picture of a dog and the information about it will pop out on a new window. Is this possible without database?

I want to do it without a database if it's possible.

Here's my code:

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

 import java.awt.event.ActionListener;
 import java.awt.event.ActionEvent;

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

 //Bago
 import java.awt.GridBagLayout; // Para mahatihati yung panel
 import java.awt.GridBagConstraints; // para customize yung pagkahati ng panel

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(true);
            gui.pack();

            gui.setVisible(true);
        }
    });
}
}

class ProgDraft extends JFrame {

private ImageIcon image1;
private JLabel label1;
private JTextField textField1;
private JButton butones;
private JTextField textField;

ProgDraft() {


    JPanel mainPanel = new JPanel(new BorderLayout());


    JLabel title = new JLabel("Dog Check", JLabel.CENTER);
    Font font = new Font("Gigi", Font.BOLD, 50);
    title.setFont(font);
    mainPanel.add(title, BorderLayout.NORTH);   


    String text = "Dogs" + "<br>"
            + "Cute dogs are everywhere" + "<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);   

    ImageIcon pics = new ImageIcon(getClass().getResource("Capture.png"));

    JLabel logo = new JLabel(pics);
    logo.setHorizontalAlignment(JLabel.CENTER);
    logo.setBorder(BorderFactory.createEmptyBorder(10, 0, 10, 0));
    logo.setToolTipText("PIcture.");




    JPanel iconFieldPanel = new JPanel(); 
    iconFieldPanel.setLayout( new GridBagLayout() );


    GridBagConstraints gc = new GridBagConstraints();



    gc.anchor = GridBagConstraints.CENTER; // Saan ikakabit yung component
    gc.weightx = 0.5; // (left and right)Space between sa edge nung panel at component
    gc.weighty = 0.5; // (top and bottom)^ 
    gc.gridx = 0; //saang cell x-axis
    gc.gridy = 0; //^ y axis naman


    iconFieldPanel.add(logo, gc);



    gc.gridy = 1;
    JLabel titleBut = new JLabel("Enter Dog Code:");
    iconFieldPanel.add(titleBut, gc);    


    gc.gridy = 2; 
    textField = new JTextField(10);
    iconFieldPanel.add(textField, gc );


    JButton buton1 = new JButton("OK");           

    gc.gridy = 3;

    iconFieldPanel.add( buton1, gc);





    JPanel iconFieldWrapper = new JPanel();
    iconFieldWrapper.add(iconFieldPanel);



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


    getContentPane().add(mainPanel);



}



}

Answer:

It is possible to write a program without database but you have to think about a way to store the data. For database concern, I guess you mean how to store the code and picture of these dogs.

Question:

I have a question. Is it possible that all of the values entered on those JTextFields, Radio Buttons and Checkboxes can be printed/displayed on a new window if you press the "Submit" button? Please help me to know more.

I am making a simple enrollment form here with the use of a Spring Layout because I think it fits for it.

Here's my code:

  import java.awt.Component;
   import java.awt.Container;
   import java.awt.Font;
   import java.awt.BorderLayout;
   //import java.awt.GridLayout;

   import javax.swing.JFrame;
   import javax.swing.JLabel;
   import javax.swing.JTextField;
   import javax.swing.SpringLayout;
   import javax.swing.JRadioButton;
   import javax.swing.ButtonGroup;
   import javax.swing.JButton;
   import javax.swing.JComboBox;
   import javax.swing.JCheckBox;
   import javax.swing.JPanel;

   import java.awt.event.ItemEvent;
   import java.awt.event.ItemListener;



   class SpringSample {
   public static void main(String args[]) {
   JComboBox bDay;
   JComboBox days;
   JComboBox taon;
   JButton butones;

   JFrame frame = new JFrame("Enrollment Form");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   Container contentPane = frame.getContentPane();

   //JLabel title = new JLabel("Enrollment Registration");

   SpringLayout layout = new SpringLayout();
   contentPane.setLayout(layout);

   JPanel mainPanel = new JPanel(new BorderLayout());

   /*JLabel titles = new JLabel("Enrollan na!");
   Font font = new Font("Agency FB", Font.BOLD, 50);
   titles.setFont(font);
   mainPanel.add(titles, BorderLayout.PAGE_START); */


   //last name
   Component last = new JLabel("Last Name:");
   Component last2 = new JTextField(15);
   contentPane.add(last);
   contentPane.add(last2);
   layout.putConstraint(SpringLayout.WEST, last, 10, SpringLayout.WEST,   
   contentPane);//pweto nugn name
   layout.putConstraint(SpringLayout.NORTH, last2, 25, SpringLayout.NORTH, 
   contentPane);//gaano kataas o kababa yung box
   layout.putConstraint(SpringLayout.NORTH, last, 25, SpringLayout.NORTH, 
   contentPane);//gaano kataas o kababa yung label
   layout.putConstraint(SpringLayout.WEST, last2, 20, SpringLayout.EAST, 
   last);//pwesto nung box

   //first name
   Component first = new JLabel("First Name:");
   Component first2 = new JTextField(15);
   contentPane.add(first);
   contentPane.add(first2);
   layout.putConstraint(SpringLayout.WEST, first, 10, SpringLayout.WEST, contentPane);
   layout.putConstraint(SpringLayout.NORTH, first2, 45, SpringLayout.NORTH, contentPane);
   layout.putConstraint(SpringLayout.NORTH, first, 45, SpringLayout.NORTH, contentPane);
layout.putConstraint(SpringLayout.WEST, first2, 20, SpringLayout.EAST, first);

   //middle
Component middle = new JLabel("M.I:");
Component middle2 = new JTextField(15);
contentPane.add(middle);
contentPane.add(middle2);
layout.putConstraint(SpringLayout.WEST, middle, 10, SpringLayout.WEST, contentPane);
layout.putConstraint(SpringLayout.NORTH, middle, 68, SpringLayout.NORTH, contentPane);
layout.putConstraint(SpringLayout.NORTH, middle2, 65, SpringLayout.NORTH, contentPane);
layout.putConstraint(SpringLayout.WEST, middle2, 65, SpringLayout.EAST, middle);

//gender
Component gender = new JLabel("Gender:");
contentPane.add(gender);
layout.putConstraint(SpringLayout.WEST, gender, 10, SpringLayout.WEST, contentPane);
layout.putConstraint(SpringLayout.NORTH, gender, 95, SpringLayout.NORTH, contentPane);

//radiohead:
ButtonGroup group = new ButtonGroup();

//male
JRadioButton option = new JRadioButton("Male", true);
group.add(option);
contentPane.add(option);
layout.putConstraint(SpringLayout.WEST, option, 90, SpringLayout.WEST, contentPane);
layout.putConstraint(SpringLayout.NORTH, option, 90, SpringLayout.NORTH, contentPane);
//female
JRadioButton option2 = new JRadioButton("Female", true);
group.add(option2);
contentPane.add(option2);
layout.putConstraint(SpringLayout.NORTH, option2, 90, SpringLayout.NORTH, contentPane);
layout.putConstraint(SpringLayout.WEST, option2, 150, SpringLayout.WEST, contentPane);

//birthday
JLabel biday = new JLabel("Birth Date:");
//months
bDay = new JComboBox();
bDay.addItem("January");
bDay.addItem("February"); 
bDay.addItem("March");
bDay.addItem("April");
bDay.addItem("May");
bDay.addItem("June");
bDay.addItem("July");
bDay.addItem("August");
bDay.addItem("September");
bDay.addItem("October");
bDay.addItem("November");
bDay.addItem("December");
contentPane.add(biday);
contentPane.add(bDay);
layout.putConstraint(SpringLayout.NORTH, biday, 125, SpringLayout.NORTH, contentPane);
layout.putConstraint(SpringLayout.WEST, biday, 10, SpringLayout.WEST, contentPane);
layout.putConstraint(SpringLayout.NORTH, bDay, 120, SpringLayout.NORTH, contentPane);
layout.putConstraint(SpringLayout.WEST, bDay, 95, SpringLayout.WEST, contentPane);

//days
days = new JComboBox();
days.addItem("1");
days.addItem("2"); 
days.addItem("3");
days.addItem("4");
days.addItem("5");
days.addItem("6");
days.addItem("7");
days.addItem("8");
days.addItem("9");
days.addItem("10");
days.addItem("11");
days.addItem("12");
days.addItem("13");
days.addItem("14");
days.addItem("15");
days.addItem("16");
days.addItem("17");
days.addItem("18");
days.addItem("19");
days.addItem("20");
days.addItem("21");
days.addItem("22");
days.addItem("23");
days.addItem("24");
days.addItem("25");
days.addItem("26");
days.addItem("27");
days.addItem("28");
days.addItem("29");
days.addItem("30");
days.addItem("31");
contentPane.add(days);
layout.putConstraint(SpringLayout.NORTH, days, 120, SpringLayout.WEST, contentPane);
layout.putConstraint(SpringLayout.WEST, days, 200, SpringLayout.WEST, contentPane);

//years
taon = new JComboBox();
taon.addItem("1994");
taon.addItem("1995");
taon.addItem("1996");
taon.addItem("1997");
taon.addItem("1998");
taon.addItem("1999");
taon.addItem("2000");
contentPane.add(taon);
layout.putConstraint(SpringLayout.NORTH, taon, 120, SpringLayout.WEST, contentPane);
layout.putConstraint(SpringLayout.WEST, taon, 255, SpringLayout.WEST, contentPane);

//address
Component address = new JLabel("Address: ");
Component address2 = new JTextField(25);
contentPane.add(address);
contentPane.add(address2);
layout.putConstraint(SpringLayout.NORTH, address, 158, SpringLayout.NORTH, contentPane);
layout.putConstraint(SpringLayout.WEST, address, 10, SpringLayout.WEST, contentPane);
layout.putConstraint(SpringLayout.NORTH, address2, 160, SpringLayout.NORTH, contentPane);
layout.putConstraint(SpringLayout.WEST, address2, 94, SpringLayout.WEST, contentPane);

//contact number
Component cNumber = new JLabel("Contact No.: ");
Component cNumber2 = new JTextField(15);
contentPane.add(cNumber);
contentPane.add(cNumber2);
layout.putConstraint(SpringLayout.NORTH, cNumber, 182, SpringLayout.NORTH, contentPane);
layout.putConstraint(SpringLayout.WEST, cNumber, 10, SpringLayout.WEST, contentPane);
layout.putConstraint(SpringLayout.NORTH, cNumber2, 180, SpringLayout.NORTH, contentPane);
layout.putConstraint(SpringLayout.WEST, cNumber2, 94, SpringLayout.WEST, contentPane);

//father's name
Component fName = new JLabel("Father's Name: ");
Component fName2 = new JTextField(20);
contentPane.add(fName);
contentPane.add(fName2);
layout.putConstraint(SpringLayout.NORTH, fName, 212, SpringLayout.NORTH, contentPane);
layout.putConstraint(SpringLayout.WEST, fName, 10, SpringLayout.WEST, contentPane);
layout.putConstraint(SpringLayout.NORTH, fName2, 210, SpringLayout.NORTH, contentPane);
layout.putConstraint(SpringLayout.WEST, fName2, 105, SpringLayout.WEST, contentPane);

//mother's name
Component mName = new JLabel("Mother's Name: ");
Component mName2 = new JTextField(20);
contentPane.add(mName);
contentPane.add(mName2);
layout.putConstraint(SpringLayout.NORTH, mName, 232, SpringLayout.NORTH, contentPane);
layout.putConstraint(SpringLayout.WEST, mName, 10, SpringLayout.WEST, contentPane);
layout.putConstraint(SpringLayout.NORTH, mName2, 230, SpringLayout.NORTH, contentPane);
layout.putConstraint(SpringLayout.WEST, mName2, 105, SpringLayout.WEST, contentPane);

//elementary
Component eSchool = new JLabel("Elementary School: ");
Component eSchool2 = new JTextField(20);
contentPane.add(eSchool);
contentPane.add(eSchool2);
layout.putConstraint(SpringLayout.NORTH, eSchool, 262, SpringLayout.NORTH, contentPane);
layout.putConstraint(SpringLayout.WEST, eSchool, 10, SpringLayout.WEST, contentPane);
layout.putConstraint(SpringLayout.NORTH, eSchool2, 260, SpringLayout.NORTH, contentPane);
layout.putConstraint(SpringLayout.WEST, eSchool2, 125, SpringLayout.WEST, contentPane);

//hayskul
Component hiSchool = new JLabel("Secondary School: ");
Component hiSchool2 = new JTextField(20);
contentPane.add(hiSchool);
contentPane.add(hiSchool2);
layout.putConstraint(SpringLayout.NORTH, hiSchool, 282, SpringLayout.NORTH, contentPane);
layout.putConstraint(SpringLayout.WEST, hiSchool, 10, SpringLayout.WEST, contentPane);
layout.putConstraint(SpringLayout.NORTH, hiSchool2, 280, SpringLayout.NORTH, contentPane);
layout.putConstraint(SpringLayout.WEST, hiSchool2, 125, SpringLayout.WEST, contentPane);

//interests with checkbox
Component interest = new JLabel("Interests: ");
Component interest_arts = new JCheckBox("Arts");
Component interest_sci = new JCheckBox("Science");
Component interest_cook = new JCheckBox("Cooking");
Component interest_sports = new JCheckBox("Sports");
contentPane.add(interest);
contentPane.add(interest_arts);
contentPane.add(interest_sci);
contentPane.add(interest_cook);
contentPane.add(interest_sports);
layout.putConstraint(SpringLayout.NORTH, interest, 312, SpringLayout.NORTH, contentPane);
layout.putConstraint(SpringLayout.WEST, interest, 10, SpringLayout.WEST, contentPane);
layout.putConstraint(SpringLayout.NORTH, interest_arts, 310, SpringLayout.NORTH, contentPane);
layout.putConstraint(SpringLayout.WEST, interest_arts, 125, SpringLayout.WEST, contentPane);
layout.putConstraint(SpringLayout.NORTH, interest_sci, 310, SpringLayout.NORTH, contentPane);
layout.putConstraint(SpringLayout.WEST, interest_sci, 200, SpringLayout.WEST, contentPane);
layout.putConstraint(SpringLayout.NORTH, interest_cook, 330, SpringLayout.NORTH, contentPane);
layout.putConstraint(SpringLayout.WEST, interest_cook, 125, SpringLayout.WEST, contentPane);
layout.putConstraint(SpringLayout.NORTH, interest_sports, 330, SpringLayout.NORTH, contentPane);
layout.putConstraint(SpringLayout.WEST, interest_sports, 200, SpringLayout.WEST, contentPane);

Component button = new JButton("Submit");
contentPane.add(button);
layout.putConstraint(SpringLayout.NORTH, button, 400, SpringLayout.NORTH, contentPane);
layout.putConstraint(SpringLayout.WEST, button, 170, SpringLayout.WEST, contentPane);



frame.setSize(500, 550);    
frame.setVisible(true);
}
}

This code only shows the interface program. A simple interface.


Answer:

if you just want to display the content in the JTextFiled on a new window , u can try JOptionPane.ShowMessageDialog(null,"text here");

this would pop up a msg box containing w.e text u put ... so the text you want would be :

address1.getText()+"\n"+.... 

and in order to make that happen when you click the submit button , you need to add an ActionListenner to that button , so it would be something like :

 submitButton.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent evt){

  JOptionPane.ShowMessageDialog(null,"text here");
  }
 });

Question:

I need help adding a scrollbar to an empty textbox that will output the information that i input into the required textboxes by then clicking the buttons. My issue is im not sure how to implement the scrollbar correctly with the textbox that is in the code, it just goes over and it and does nothing like in the picture shown. I need it to align with the textbox and not mess with the Jtextfield so that it can properly scroll the textbox, i will handle the events after i finish the design.

Code:

    // Display box for all the inputs
    JTextField outputBox = new JTextField(5);
    wv.add(outputBox, 39, 575, 800, 150);
    JScrollBar outputBoxScrollBar = new JScrollBar(JScrollBar.VERTICAL, 30, 20, 0, 500);
    wv.add(outputBoxScrollBar, 790, 300, 50 , 250);

Output:


Answer:

  1. A JTextField is single-line, I guess you are looking for JTextArea.
  2. You need to wrap JTextArea in a JScrollPane (not a JScrollBar) like this.
        JTextArea outputBox = new JTextArea(5, 20); //rows, columns
        wv.add(new JScrollPane(outputBox), 790, 300, 50 , 250);

Question:

I'm working on a TextTwist java implementation and I'm currently working on the GUI. I was wondering if some of you Swing geniuses could help me out. I'm trying to do a GUI where whenever a button is clicked, the text of that button is written into the first empty textField below it. I'm having trouble thinking through how to do it. What I've tried so far makes the first button click fill all the TextFields.

Any help or pointers in the right direction would be great.

        private void makeButtonLayout() {
    this.charArray = new char[6];
    ArrayList<Character> charArrayList = new ArrayList<Character>();

        this.charArray = this.randomString.toCharArray();
        for(char tempCharacter : this.charArray){
            charArrayList.add(tempCharacter);
        }

        for (int i = 0; i< 6; i++){

            JButton letterButton = new JButton();
            Character buttonCharacter = charArrayList.get(i);
            charArrayList.remove(i);

            String letterString = buttonCharacter.toString();
            letterButton.setText(letterString);
            this.letterButtonsArray.add(letterButton);
        }

        for (final JButton currentButton : this.letterButtonsArray){
            this.buttonPanel.add(currentButton);    
            currentButton.addActionListener(new ActionListener(){
                @Override
                public void actionPerformed(ActionEvent arg0) {
                    int i = 0;
                    currentButton.setVisible(false);
                    JTextField temporaryTextField = new JTextField();
                    String temporaryString = currentButton.getText();

                    temporaryTextField.setText(temporaryString);

                    if(textFieldArray.get(i).getText().isEmpty()){
                        textFieldArray.get(i).setText(temporaryString);
                        return;
                    }else{
                        i++;
                        return;
                    }

                }

            });
        }
    }


Answer:

I think you method is really strange. You mixed initialization code and execution code. Do it like this:

        for (final JButton currentButton : this.letterButtonsArray){
            this.buttonPanel.add(currentButton);    
            currentButton.addActionListener(new ActionListener(){
                @Override
                public void actionPerformed(ActionEvent arg0) {
                    currentButton.setVisible(false);

                    String temporaryString = currentButton.getText();

                    for(int i = 0; i < textFieldArray.size(); i++)
                      JTextField elem = textFieldArray.get(i);
                      if(elem.getText().equals("")){ // or if you don't want spaces do: elem.getText().trim().equals("");
                          elem.setText(temporaryString);
                          break;
                      }
                    }

                }

            });
        }