how to get int from JTextField with a JButton - java

I'm trying to get an int from my JTextField with the click of my JButton but I can't figure out how to do so. I'm trying to get the int and set it to a variable so I can use it in my program further down.
Here is the code(this is the whole method):
JFrame presets = new JFrame("Presets");
presets.setVisible(true);
presets.setSize(500, 500);
JPanel gui = new JPanel(new BorderLayout(2,2));
JPanel labelFields = new JPanel(new BorderLayout(2,2));
labelFields.setBorder(new TitledBorder("Presets"));
JPanel labels = new JPanel(new GridLayout(0,1,1,1));
JPanel fields = new JPanel(new GridLayout(0,1,1,1));
labels.add(new JLabel("Place values on Cat.2/Cat.3 at"));
JTextField f1 = new JTextField(10);
String text = f1.getText();
int first = Integer.parseInt(text);
labels.add(new JLabel("and place follow up value at"));
fields.add(new JTextField(10));
labelFields.add(labels, BorderLayout.CENTER);
labelFields.add(fields, BorderLayout.EAST);
JPanel guiCenter = new JPanel(new BorderLayout(2,2));
JPanel submit = new JPanel(new FlowLayout(FlowLayout.CENTER));
submit.add( new JButton("Submit") );
guiCenter.add( submit, BorderLayout.NORTH );
gui.add(labelFields, BorderLayout.NORTH);
gui.add(guiCenter, BorderLayout.CENTER);
JOptionPane.showMessageDialog(null, gui);

Try this,
String getText()
Returns the text contained in this TextComponent.
So, convert your String to Integer as:
try {
int integerValue = Integer.parseInt(jTextField.getText());
}
catch(NumberFormatException ex)
{
System.out.println("Exception : "+ex);
}

Probably you want the entered data as int. write it in the button action
JButton button = new JButton("Submit");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
try {
int myInt=Integer.parseInt(jtextfield.getText());
System.out.println("Integer is: "+myInt);
//do some stuff
}
catch (NumberFormatException ex) {
System.out.println("Not a number");
//do you want
}
}
});
Remember Integer.parseInt throws NumberFormatException which must be caught. see java docs

if you want to get the f1 text when the submit pressed, use this code:
.
.
.
JPanel submit = new JPanel(new FlowLayout(FlowLayout.CENTER));
JButton button = new JButton("Submit");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
int first = Integer.parseInt(f1.getText().trim());
}
});
submit.add(button);
guiCenter.add(submit, BorderLayout.NORTH);
.
.
.

Related

JRadioButton toggle unexpectedly in CardLayout panels

So the problem is: I'm trying to make a wizard-like CardLayout. In each card panel, I put back & next JButton and 3 JRadioButton to switch between 3 pages.
Now, when I select the radio buttons the 1st time, it works normally. However, the 2nd time I select the radio button, they don't get selected as expected. For example, I want to select page 2, the card panel 2 does show up, but the radio button 2 state does not show that it's being selected, instead either radio button 1 or 3 gets selected. Button 2 only gets selected when I click it again. Same thing happens when I try to select the others.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CardLayoutWizardDemo extends JFrame{
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable() {
public void run() {
CardLayoutWizardDemo frame= new CardLayoutWizardDemo();
frame.init();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
private static final long serialVersionUID = 1L;
private JPanel cardPanel, panel1, panel2, panel3, btnPanel1, btnPanel2, btnPanel3;
private JLabel label1, label2, label3;
private JRadioButton step1, step2, step3;
private ButtonGroup bg;
private CardLayout cl = new CardLayout();
private void init(){
setTitle("CardLayoutWizardDemo");
cardPanel = new JPanel();
cardPanel.setLayout(cl);
panel1 = new JPanel(new BorderLayout());
panel2 = new JPanel(new BorderLayout());
panel3 = new JPanel(new BorderLayout());
label1 = new JLabel("label 1");
label2 = new JLabel("label 2");
label3 = new JLabel("label 3");
panel1.add(label1, BorderLayout.NORTH);
panel2.add(label2, BorderLayout.NORTH);
panel3.add(label3, BorderLayout.NORTH);
btnPanel1 = new JPanel();
btnPanel2 = new JPanel();
btnPanel3 = new JPanel();
btnPanel1.setName("panel1");
btnPanel2.setName("panel2");
btnPanel3.setName("panel3");
btnPanel1 = initTutBtn(btnPanel1);
btnPanel2 = initTutBtn(btnPanel2);
btnPanel3 = initTutBtn(btnPanel3);
panel1.add(btnPanel1, BorderLayout.SOUTH);
panel2.add(btnPanel2, BorderLayout.SOUTH);
panel3.add(btnPanel3, BorderLayout.SOUTH);
cardPanel.add(panel1, "1");
cardPanel.add(panel2,"2");
cardPanel.add(panel3,"3");
getContentPane().add(cardPanel, BorderLayout.CENTER);
setPreferredSize(new Dimension(350,500));
setMinimumSize(new Dimension(240,320));
pack();
setLocationByPlatform(true);
}
/**create new set of 3 step buttons
*/
private JPanel initTutBtn(JPanel btnPanel){
btnPanel.setLayout(new BoxLayout(btnPanel,BoxLayout.X_AXIS));
step1 = new JRadioButton();
step2 = new JRadioButton();
step3 = new JRadioButton();
step1.setActionCommand("step1");
step2.setActionCommand("step2");
step3.setActionCommand("step3");
bg = new ButtonGroup();
bg.add(step1);
bg.add(step2);
bg.add(step3);
if (btnPanel.getName().equals("panel1")){
step1.setSelected(true);
}else if (btnPanel.getName().equals("panel2")){
step2.setSelected(true);
}else if (btnPanel.getName().equals("panel3")){
step3.setSelected(true);
}
step1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
goToStep(e);
}
});
step2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
goToStep(e);
}
});
step3.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
goToStep(e);
}
});
btnPanel.add(step1);
btnPanel.add(step2);
btnPanel.add(step3);
return btnPanel;
}
private void goToStep(ActionEvent evt){
if(evt.getActionCommand().equals("step1")){
cl.show(cardPanel, "1");
}else if(evt.getActionCommand().equals("step2")){
cl.show(cardPanel, "2");
}else if(evt.getActionCommand().equals("step3")){
cl.show(cardPanel, "3");
}
}
}
I think maybe the problems lie where I create new radio buttons within initButton() and goToStep(ActionEvent evt)but I can't figure out what I did wrong

How to make blank fields valid until user clicks SAVE -Java

This is a simple program that uses a JDialog to add or edit work orders. When the dialog appears, the user will enter information into the fields (name, date, position, billing rate, etc.). The program must validate each of these fields. The problem is that if I leave a field blank and I tab to the next field, the error message pops up. Actually, this isn't a problem, its working as it should, however, I would like to make it so that all blank fields are valid until the user clicks SAVE. Any suggestions or ideas? I have pasted the entire program below so feel free to compile and run it yourself, thank you!
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.lang.*;
import java.awt.event.*;
import javax.swing.filechooser.*;
import java.io.*;
import static javax.swing.GroupLayout.Alignment.*;
public class WorkOrderProject
{
public static void main (String args[])
{
new MyFrameClass();
}
}
class MyFrameClass extends JDialog implements ActionListener
{
JButton addButton, editButton;
JPanel buttonPanel;
WorkOrder workOrderToEdit = new WorkOrder();
MyFrameClass()
{
Container cp;
addButton = new JButton("ADD");
addButton.addActionListener(this);
addButton.setActionCommand("ADD");
editButton = new JButton("EDIT");
editButton.addActionListener(this);
editButton.setActionCommand("EDIT");
buttonPanel = new JPanel(new FlowLayout());
buttonPanel.add(addButton);
buttonPanel.add(editButton);
cp = getContentPane();
cp.add(buttonPanel, BorderLayout.NORTH);
setupMainFrame();
}
void setupMainFrame()
{
Toolkit tk;
Dimension d;
tk = Toolkit.getDefaultToolkit();
d = tk.getScreenSize();
setLayout(new FlowLayout());
setTitle("Work Orders");
setSize(d.width/2, d.height/2);
setLocation(d.width/4, d.height/4);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand().equals("ADD"))
{
System.out.println("ADD");
new MyDialog();
}
else if(e.getActionCommand().equals("EDIT"))
{
System.out.println("EDIT");
new MyDialog(workOrderToEdit);
}
}
}
class MyDialog extends JDialog implements ActionListener
{
JPanel buttonPanel, fieldPanel;
JButton button1, button2, button3, button4;
GroupLayout layout;
WorkOrder workOrderToEdit;
String[] comboTypes = { "Sales", "Hardware", "Electronics" };
JComboBox<String> comboTypesList;
public MyDialog()
{
Container cp;
button1 = new JButton("SAVE");
button1.addActionListener(this);
button1.setActionCommand("SAVE");
button2 = new JButton("CANCEL");
button2.addActionListener(this);
button2.setActionCommand("CANCEL");
button2.setVerifyInputWhenFocusTarget(false);
button3 = new JButton("SAVE AND NEW");
button3.addActionListener(this);
button3.setActionCommand("SAVE AND NEW");
buttonPanel = new JPanel(new FlowLayout());
buttonPanel.add(button2);
buttonPanel.add(button1);
buttonPanel.add(button3);
fieldPanel = setFields();
cp = getContentPane();
cp.add(fieldPanel, BorderLayout.NORTH);
cp.add(buttonPanel, BorderLayout.SOUTH);
setTitle("Add New Work Order");
setupMainFrame();
}
public MyDialog(WorkOrder w)
{
Container cp;
button1 = new JButton("SAVE");
button1.addActionListener(this);
button1.setActionCommand("SAVE");
button2 = new JButton("CANCEL");
button2.addActionListener(this);
button2.setActionCommand("CANCEL");
button2.setVerifyInputWhenFocusTarget(false);
buttonPanel = new JPanel(new FlowLayout());
buttonPanel.add(button2);
buttonPanel.add(button1);
fieldPanel = setFields();
getContentPane().add(fieldPanel, BorderLayout.NORTH);
getContentPane().add(buttonPanel, BorderLayout.SOUTH);
setTitle("Edit Work Order");
setupMainFrame();
}
void setupMainFrame()
{
Toolkit tk;
Dimension d;
tk = Toolkit.getDefaultToolkit();
d = tk.getScreenSize();
setLayout(new FlowLayout());
setSize(d.width/3, d.height/3);
setLocation(d.width/3, d.height/3);
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
setModal(true);
setVisible(true);
}
JPanel setFields()
{
GroupLayout layout;
JPanel p;
JLabel label1, label2, label3, label4, label5;
JTextField text1, text2, text3, text4, text5;
String[] comboTypes = { "-Select-" ,"Sales", "Hardware", "Electronics" };
comboTypesList = new JComboBox<>(comboTypes);
comboTypesList.addActionListener(this);
label1 = new JLabel("Name: ");
label2 = new JLabel("Department: ");
label3 = new JLabel("Date of request: ");
label4 = new JLabel("Date request was fulfilled: ");
label5 = new JLabel("Billing rate: ");
text1 = new JTextField(20);
text1.setInputVerifier(new NameVerifier());
text2 = new JTextField(20);
text3 = new JTextField(20);
text4 = new JTextField(20);
text5 = new JTextField(20);
p = new JPanel();
layout = new GroupLayout(p);
p.setLayout(layout);
layout.setAutoCreateGaps(true);
layout.setAutoCreateContainerGaps(true);
GroupLayout.SequentialGroup hGroup = layout.createSequentialGroup();
hGroup.addGroup(layout.createParallelGroup().addComponent(label1).addComponent(label2).addComponent(label3).addComponent(label4).addComponent(label5));
hGroup.addGroup(layout.createParallelGroup().addComponent(text1).addComponent(comboTypesList).addComponent(text3).addComponent(text4).addComponent(text5));
layout.setHorizontalGroup(hGroup);
GroupLayout.SequentialGroup vGroup = layout.createSequentialGroup();
vGroup.addGroup(layout.createParallelGroup(BASELINE).addComponent(label1).addComponent(text1));
vGroup.addGroup(layout.createParallelGroup(BASELINE).addComponent(label2).addComponent(comboTypesList));
vGroup.addGroup(layout.createParallelGroup(BASELINE).addComponent(label3).addComponent(text3));
vGroup.addGroup(layout.createParallelGroup(BASELINE).addComponent(label4).addComponent(text4));
vGroup.addGroup(layout.createParallelGroup(BASELINE).addComponent(label5).addComponent(text5));
layout.setVerticalGroup(vGroup);
return(p);
}
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand().equals("SAVE"))
{
System.out.println("SAVED");
dispose();
}
else if(e.getActionCommand().equals("CANCEL"))
{
System.out.println("CANCELED");
dispose();
}
else if(e.getActionCommand().equals("SAVE AND NEW"))
{
System.out.println("SAVED AND NEW");
}
}
}
class WorkOrder
{
String name;
int department;
Object dateRequested;
Object dateFulfilled;
String description;
double billingRate;
}
class NameVerifier extends InputVerifier
{
public boolean verify(JComponent input)
{
String str;
boolean isValid;
int score;
str = ((JTextField)input).getText().trim();
if(str.equals(""))
{
isValid = false;
JOptionPane.showMessageDialog(input.getParent(), "Name field is blank.", "ERROR", JOptionPane.ERROR_MESSAGE);
}
else
{
isValid = true;
}
return(isValid);
}
}
The problem is that if I leave a field blank and I tab to the next field, the error message pops up.
Don't use an InputVerifier. The purpose of the InputVerifier is to validate a text field when it loses focus.
I would like to make it so that all blank fields are valid until the user clicks SAVE.
Add your validation logic (for all the fields) to the ActionListener of the "Save" button.
So you would use the InputVerifier on each text field to validate the format of the data entered (when the data is entered). For example, for the "billing rate" you would verify that the value is a double number, the date fields contain a valid date.
Then in the "Save" listener you validate that all fields contain data. So if the data is in a valid format and all fields contain data, then you know the forum can be submitted for processing.

positioning jpanel at the bottom

I want to position the JPanel that contains the send button and the textfield (and right now uses a flowlayout) at the bottom of the JTextArea (The white area).
How can I achieve this?
public GUI()
{
mainWindow = new JFrame("Chat GUI");
lowerPanel = new JPanel(new FlowLayout());
usersPanel = new JPanel(new GridLayout(GRIDLAYOUT_ROWS, GRIDLAYOUT_COLS));
users = new JList(data);
usersPanel.add(users);
sendButton = new JButton("Send");
textField = new JTextField(TEXTFIELD_WIDTH);
textArea = new JTextArea(TEXTAREA_HEIGHT, TEXTAREA_WIDTH);
textArea.setEditable(false);
}
private void addButtonListener(JButton b) {
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
}
public void createGUI() {
addButtonListener(sendButton);
lowerPanel.add(sendButton);
lowerPanel.add(textField);
mainWindow.add(users);
mainWindow.add(textArea);
mainWindow.add(lowerPanel);
mainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainWindow.setVisible(true);
mainWindow.setLayout(new FlowLayout());
mainWindow.pack();
}
You Will have Layout :
this.add(buttonPanel,BorderLayout.SOUTH);
see this answer

Action Listener does not work on swing

I have a form , That when i click to save button, "Yes" String should display on my console!
(I use "Yes" String for test!)
But does not work when clicked.
My code:
public final class NewUserFrame1 extends JFrame implements ActionListener {
UserInformation userinfo;
JLabel fnamelbl;
JLabel lnamelbl;
JTextField fntf;
JTextField lntf;
JLabel gndlnl;
JRadioButton malerb;
JRadioButton femalerb;
ButtonGroup bgroup;
JLabel registnm;
JButton savebt;
JButton cancelbt;
JLabel showreglbl;
public NewUserFrame1() {
add(rowComponent(), BorderLayout.CENTER);
setLocation(200, 40);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
}
public JPanel rowComponent() {
JPanel panel = new JPanel();
fnamelbl = new JLabel("First name");
lnamelbl = new JLabel("Last Name");
JLabel fntemp = new JLabel();
JLabel lntemp = new JLabel();
fntf = new JTextField(10);
lntf = new JTextField(10);
gndlnl = new JLabel("Gender");
malerb = new JRadioButton("Male");
femalerb = new JRadioButton("Female");
bgroup = new ButtonGroup();
bgroup.add(malerb);
bgroup.add(femalerb);
registnm = new JLabel("Registration ID is:");
showreglbl = new JLabel("");
JLabel regtemp = new JLabel();
savebt = new JButton("Save");
cancelbt = new JButton("Cancell");
JLabel buttontemp = new JLabel();
panel.add(fnamelbl);
panel.add(fntf);
panel.add(fntemp);
panel.add(lnamelbl);
panel.add(lntf);
panel.add(lntemp);
panel.add(gndlnl);
JPanel radiopanel = new JPanel();
radiopanel.setLayout(new FlowLayout(FlowLayout.LEFT));
radiopanel.add(malerb);
radiopanel.add(femalerb);
panel.add(radiopanel);
panel.add(new JLabel());
panel.add(registnm);
panel.add(showreglbl);
panel.add(regtemp);
panel.add(savebt);
panel.add(cancelbt);
panel.add(buttontemp);
panel.setLayout(new SpringLayout());
SpringUtilities.makeCompactGrid(panel, 5, 3, 50, 10, 80, 60);
return panel;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
NewUserFrame1 newUserFrame1 = new NewUserFrame1();
}
});
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == savebt) {
System.out.print("Yes");
}
}
}
You need to add an ActionListener to your button like so:
savebt.addActionListener(this);
or with an anonymous class, like so:
savebt.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// your code.
}
});
Using anonymous classes (or inner classes) is better because you can't have more than one actionPerformed() method in a given class.
You need to tell the button to invoke the ActionListener:
savebt = new JButton("Save");
savebt.addActionListener(this);
Note if you intend to use the same method for the save and cancel buttons, you'll need to differentiate, perhaps by comparing the source of the ActionEvent against the two buttons.

Unstable GUI in Java

I am writing a very simple GUI, that contains 3 buttons, 2 labels, 2 text fields and one text area. Strangely, the result is unstable: when running the class the GUI appears with random number of the controls. I tried various layout managers, changing the order among the control - nothing.
Can someone help?
package finaltestrunner;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class FinalTestGUI extends JFrame implements ActionListener
{
public Boolean startState = false;
JButton sofButton;
JButton startStopButton;
JButton exitButton;
JTextField loopCounts;
JTextField trSnField;
JTextArea resultField = null;
public FinalTestGUI()
{
// The constructor creates the panel and places the controls
super(); // Jframe constructor
JFrame trFrame = new JFrame();
trFrame.setSize(1000, 100);
trFrame.setVisible(true);
trFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
trFrame.setTitle("Test runner");
setFont(new Font("SansSerif", Font.PLAIN, 14));
// trFrame.setLayout(new FlowLayout());
JPanel trControlPanel = new JPanel();
trControlPanel.setSize(1000, 100);
trControlPanel.setLayout(new GridLayout(1,7));
exitButton = new JButton("Exit");
trControlPanel.add(exitButton);
startStopButton = new JButton("Run ");
trControlPanel.add(startStopButton);
JLabel loopsLabel = new JLabel ("Loops count: ");
trControlPanel.add(loopsLabel);
loopCounts = new JTextField (5);
trControlPanel.add(loopCounts);
sofButton = new JButton("SoF");
trControlPanel.add(sofButton);
JLabel testLabel = new JLabel ("serial Number: ");
trControlPanel.add(testLabel);
trSnField = new JTextField (5);
trControlPanel.add(trSnField);
JTextArea trResultField = new JTextArea (80, 10);
trFrame.add(trControlPanel);
// cpl.add(trResultField);
startStopButton.addActionListener(new ActionListener()
{
#Override
public void actionPerformed (ActionEvent trStartStopButton)
{
startState = !startState;
if (startState)
{
startStopButton.setText("Run ");
startStopButton.setForeground(Color.red);
}
else
{
startStopButton.setText("Stop");
startStopButton.setForeground(Color.green);
}
}
});
sofButton.addActionListener(new ActionListener()
{
#Override
public void actionPerformed (ActionEvent trSofButton)
{
loopCounts.setText("SOF\n");
}
});
exitButton.addActionListener (new ActionListener()
{
#Override
public void actionPerformed (ActionEvent trExitButton)
{
System.exit(0);
}
});
} // End of the constructor
#Override
public void actionPerformed (ActionEvent ae) { }
public void atpManager ()
{
String selectedAtp = "";
}
}
There are a couple of issues with this code:
You are already inheriting from JFrame, so you do not need to create yet another JFrame
You are showing your frame with setVisible(true) and afterwards adding components to it. This invalidates your layout, you need to revalidate afterwards (or move setVisible() to a position where you already added your components)
You are adding your components to the JFrame directly, but you need to use its contentpane. Starting with Java 1.5, the JFrame.add() methods automatically forward to the content pane. In earlier versions, it was necessary to retrieve the content pane with JFrame.getContentPane() to add the child components to the content pane.
Try this:
public FinalTestGUI() {
// The constructor creates the panel and places the controls
super(); // Jframe constructor
setSize(1000, 100);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Test runner");
setFont(new Font("SansSerif", Font.PLAIN, 14));
setLayout(new FlowLayout());
JPanel trControlPanel = new JPanel();
trControlPanel.setSize(1000, 100);
trControlPanel.setLayout(new GridLayout(1,7));
exitButton = new JButton("Exit");
trControlPanel.add(exitButton);
startStopButton = new JButton("Run ");
trControlPanel.add(startStopButton);
JLabel loopsLabel = new JLabel ("Loops count: ");
trControlPanel.add(loopsLabel);
loopCounts = new JTextField (5);
trControlPanel.add(loopCounts);
sofButton = new JButton("SoF");
trControlPanel.add(sofButton);
JLabel testLabel = new JLabel ("serial Number: ");
trControlPanel.add(testLabel);
trSnField = new JTextField (5);
trControlPanel.add(trSnField);
JTextArea trResultField = new JTextArea (80, 10);
// getContentPane().add(trControlPanel); // pre 1.5
add(trControlPanel); // 1.5 and greater
setVisible(true);
}

Categories

Resources