How do we test if JFormattedTextField is empty? - java

I have a JFormattedTextField that is meant for user to enter phone number. My phone number is taking the following format :+### ###-###-###. I want to check for empty string before I save the phone number to a database. The problem is I am not able to check/determine if the field is empty. When I print field.getText().length() it outputs 16 meaning some characters are already in the field. How do I check if the user has entered some characters?
Below is my code:
public class JTextFiledDemo {
private JFrame frame;
JTextFiledDemo() throws ParseException {
frame = new JFrame();
frame.setVisible(true);
frame.setSize(300, 300);
frame.setLayout(new GridLayout(4, 1));
frame.setLocationRelativeTo(null);
iniGui();
}
private void iniGui() throws ParseException {
JButton login = new JButton("Test");
JFormattedTextField phone = new JFormattedTextField(new MaskFormatter(
"+### ###-###-###"));
frame.add(phone);
frame.add(login);
frame.pack();
login.addActionListener((ActionEvent) -> {
JOptionPane.showMessageDialog(frame, "The length of input is :"
+ phone.getText().length());
});
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
JTextFiledDemo tf = new JTextFiledDemo();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}

You can used the isEditValid() method to check the contents
final boolean editValid = phone.isEditValid();
showMessageDialog(frame, "The length of input is :" + phone.getText().length() + ". It is " + (editValid ? "" : "not ") + "valid!");

Related

Java External JAR Doesn't Seem To Be Working

Using Eclipse, Mslink.jar (creates shortcuts), Java 1.8.0
The coding that fails. The JOptionPane never appears when I export this out to a .JAR
public static void main(String[] args) {
// create an empty combo box with items of type String
JComboBox<String> systems = new JComboBox<String>();
// add items to the combo box
systems.addItem("System1");
systems.addItem("System2");
systems.addItem("System5");
systems.addItem("System6");
systems.addItem("System7");
systems.addItem("System9");
systems.addItem("System10");
systems.addItem("System12");
systems.addItem("System14");
systems.addItem("System15");
systems.addItem("System16");
systems.addItem("System17");
systems.addItem("System18");
systems.addItem("System19");
systems.addItem("System20");
systems.addItem("System21");
systems.addItem("System22");
systems.addItem("System24");
systems.addItem("System30");
systems.addItem("System34");
systems.addItem("All Systems Install");
systems.setEditable(true);
JPanel steps = new JPanel();
JPanel firstStep = new JPanel();
JPanel secondStep = new JPanel();
frame.setSize(1200, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setLayout(new GridLayout(3, 1));
frame.add(steps);
frame.add(firstStep);
frame.add(secondStep);
Button go = new Button("Go");
Button go2 = new Button("Go");
Label stepInstruction = new Label(
"Please do each step in order to complete the process. First step requires you install Universal desktop for your system."
+ " Second step requires your username to find Universal desktop install");
Label instruction = new Label("Step 1: Please select a system to download from");
Label instruction2 = new Label("Step 2: Press Go when Universal Desktop is Installed");
// Steps Explained
steps.add(stepInstruction);
// First Step
firstStep.add(instruction);
firstStep.add(systems);
firstStep.add(go);
// Second Step
secondStep.add(instruction2);
secondStep.add(go2);
go.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
String selectedSystem = (String) systems.getSelectedItem();
System.out.println(selectedSystem);
try {
if (!selectedSystem.equalsIgnoreCase("All Systems Install")) {
// Open UD install page in Internet explorer
Runtime.getRuntime().exec("C:\\Program Files\\Internet Explorer\\iexplore.exe " + "https://"
+ selectedSystem
+ ".pos.infogenesisasp.com/infogenesis/install/universaldesktop/UniversalDesktop.application");
// Runtime.getRuntime().exec("C:\\Program Files\\Internet Explorer\\iexplore.exe
// "
// + "https://" + selectedSystem +
// ".pos.infogenesisasp.com/infogenesis/install/universaldesktop/");
}
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(frame, e);
}
frame.validate();
}
});
go2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
String selectedSystem = (String) systems.getSelectedItem();
String Username = System.getProperty("user.name");
if (selectedSystem.equalsIgnoreCase("All Systems Install")) {
String[] systems = { "System1", "System2", "System5", "System6", "System7", "System9", "System10",
"System12", "System14", "System15", "System16", "System17", "System18", "System19",
"System20", "System21", "System22", "System24", "System30", "System34" };
for (int count = 0; count < systems.length; count++) {
try {
// Need to figure out a way to ensure the person installs UD before we can
// proceed
Runtime.getRuntime().exec("C:\\Program Files\\Internet Explorer\\iexplore.exe " + "https://"
+ systems[count]
+ ".pos.infogenesisasp.com/infogenesis/install/universaldesktop/UniversalDesktop.application");
count = systems.length;
} catch (IOException e) {
JOptionPane.showMessageDialog(frame, e);
e.printStackTrace();
}
}
} else {
// Single System installer
Installer(Username, selectedSystem);
JOptionPane.showMessageDialog(frame, "Installion Completed!");
}
}
});
}
import mslinks.ShellLink;
public static void createShortcut(String folder, String system) throws IOException
{
ShellLink.createLink(folder, system);
JOptionPane.showMessageDialog(frame, "Created Shortcut!");
}
File system:
This code works fine in Eclipse, but exporting to a JAR causes it to fail. Is there something missing preventing the Referenced Libaries Mslinks.jar from loading? I've tried everything in Eclipse's export

How to Remove Mask of JFormattedTextField?

I've a JFormattedTextField controlled by two RadioButton. In one of RadioButton I set the mask and the other I want to clear the mask and type normally. After set to type normally it doesn't return the value of getText(), the value only return if the mask is setted.
How could fix this problem ?
private void setMask() {
MaskFormatter formatter = null;
try {
txtPesquisar.setValue(null);
if (rbNome.isSelected()) {
//clear mask to type normally
formatter = new MaskFormatter("****************************************");
formatter.setPlaceholderCharacter(' ');
} else {
//set mask
formatter = new MaskFormatter("###.###.###-##");
formatter.setPlaceholderCharacter(' ');
}
txtPesquisar.setFormatterFactory(new DefaultFormatterFactory(formatter));
txtPesquisar.requestFocus();
txtPesquisar.selectAll();
} catch (ParseException ex) {
ex.printStackTrace();
}
}
Be sure to call commitEdit() on your JFormattedTextField before calling getValue(). As per the JFormattedTextField API section on getValue():
Returns the last valid value. Based on the editing policy of the AbstractFormatter this may not return the current value. The currently edited value can be obtained by invoking commitEdit followed by getValue.
Returns:
For example:
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.text.ParseException;
import javax.swing.*;
import javax.swing.text.DefaultFormatterFactory;
import javax.swing.text.MaskFormatter;
#SuppressWarnings("serial")
public class TestFormattedField extends JPanel {
private JFormattedTextField txtPesquisar = new JFormattedTextField();
private JRadioButton rbNome = new JRadioButton("None");
private JRadioButton rbFormat = new JRadioButton("Format");
public TestFormattedField() {
txtPesquisar.setColumns(20);
ButtonGroup btnGroup = new ButtonGroup();
btnGroup.add(rbFormat);
btnGroup.add(rbNome);
rbNome.setSelected(true);
rbNome.setMnemonic(KeyEvent.VK_N);
rbFormat.setMnemonic(KeyEvent.VK_F);
add(txtPesquisar);
add(rbFormat);
add(rbNome);
setMask();
add(new JButton(new SetFormatAction()));
add(new JButton(new GetTextAction()));
}
private void setMask() {
MaskFormatter formatter = null;
try {
txtPesquisar.setValue(null);
if (rbNome.isSelected()) {
//clear mask to type normally
formatter = new MaskFormatter("****************************************");
formatter.setPlaceholderCharacter(' ');
} else {
//set mask
formatter = new MaskFormatter("###.###.###-##");
formatter.setPlaceholderCharacter(' ');
}
txtPesquisar.setFormatterFactory(new DefaultFormatterFactory(formatter));
txtPesquisar.requestFocus();
txtPesquisar.selectAll();
} catch (ParseException ex) {
ex.printStackTrace();
}
}
private class SetFormatAction extends AbstractAction {
public SetFormatAction() {
super("Set Format");
putValue(MNEMONIC_KEY, KeyEvent.VK_S);
}
#Override
public void actionPerformed(ActionEvent e) {
setMask();
}
}
private class GetTextAction extends AbstractAction {
public GetTextAction() {
super("Get Text");
putValue(MNEMONIC_KEY, KeyEvent.VK_G);
}
#Override
public void actionPerformed(ActionEvent e) {
final String text = txtPesquisar.getText();
try {
txtPesquisar.commitEdit();
} catch (ParseException e1) {
String title = "Incomplete Text Entry";
String msg = "Text -- " + text + " is not yet complete";
JOptionPane.showMessageDialog(TestFormattedField.this, msg, title, JOptionPane.ERROR_MESSAGE);
}
Object value = txtPesquisar.getValue();
System.out.println("text: " + text);
System.out.println("value: " + value);
}
}
private static void createAndShowGui() {
TestFormattedField mainPanel = new TestFormattedField();
JFrame frame = new JFrame("Test JFormattedField");
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(() -> createAndShowGui());
}
}
In the future, please consider taking a little time to create and post a minimal example program or SSCCE since this would be the best and quickest way to get folks to fully understand your problem and then be able to help you. Please see my code as an example of this.
on form constructor after inintcomponets
public Form1() {
initComponents();
MaskFormatter dateMask;
try {
dateMask = new MaskFormatter("|#|#|#|#|#|#|#|#|#|#|");
dateMask.install(JTEXTFORMATEE);
} catch (ParseException ex) {
Logger.getLogger(Forma051.class.getName()).log(Level.SEVERE, null, ex);
}
}

Simple Calculator with all buttons created and actions added in JButton array

I'm self learning java beginner
i'm trying to create simple calculator using java swing and i want to create array of JButtons to create all the buttons in the project , i had some issues so i declare all variables outside the constructor
public class SimpleCalculator extends JFrame implements ActionListener {
JButton btnArray[] = new JButton[16];
JLabel nameLabel = new JLabel("Ghanayem's Calculator",
SwingConstants.CENTER);
JTextField txt = new JTextField();
JPanel numPanel = new JPanel(new GridLayout(4, 3, 15, 5));
JPanel opPanel = new JPanel(new GridLayout(4, 1, 0, 5));
JPanel panel = new JPanel(new GridLayout(2, 1, 0, 5));
int counter;
char operation;
double operand1;
double operand2;
like that ,and i think to add actions to buttons inside for-loop no compiler errors every thing is ok
for (counter = 0; counter < 10; counter++) {
btnArray[counter] = new JButton("" + counter);
btnArray[counter].addActionListener(this);
}
and here is action performed implementation
#Override
public void actionPerformed(ActionEvent e) {
txt.setText(txt.getText() + counter);
}
just like that ,when i try to run the program and press any number button the number added to text field is "16" for all buttons, and this is main method
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
SimpleCalculator frame = new SimpleCalculator();
frame.setVisible(true);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setResizable(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
i am getting crazy i don't know what is wrong , please i need your help this my first swing application i am so disperate
thank you
Try something like this (I can't test right now so it may contain some lesser errors):
#Override
public void actionPerformed(ActionEvent e) {
String value = ((JButton)e.getSource()).getText();
Integer intValue = Integer.parseInt(value);
Integer intValue2 = Integer.parseInt(txt.getText());
txt.setText( "" + (intValue + intValue2));
}
#Override
public void actionPerformed(ActionEvent e) {
JButton b = (JButton) e.getSource();
txt.replaceSelection(b.getActionCommand());
}
this is a solution for my question i found here
java-action-listener
#Override
public void actionPerformed(ActionEvent e) {
String value = (JButton) e.getSource().getText();
txt.setText(txt.getText() + value);
}
and this is another solution #Paco Abato helps me to find

Java RandomAccessFile , Only finds the first entry

When my program reads from the randomaccessfile it will only find the first file or the file with the lowest account number ( this is a banking program )
After that I get the IO exception with a read error
private RandomAccessFile input; // Random Aecess File input Stream
private Record data;
public static JFrame frame = new JFrame();
public CredRead() // Constructor CredRead created
{
// open the file
try {
// declare the output stream object and associate it to file
// file.dat
input = new RandomAccessFile("UnionDB.dat", "rw");
}
catch (IOException e) {
// if an error occurs display a message on the screen
System.err.println("File not opened properly\n " + e.toString());
// the program terminates due to error
System.exit(1);
}
data = new Record();
setPreferredSize(new Dimension(650, 400));
frame.setSize(getPreferredSize()); // Frame Size
frame.setLocationRelativeTo(null);
frame.setLayout(new GridLayout(7, 2)); // Grid Layout set
/* GUI Components */
frame.add(new Label("Enter Account Number and click Enter"));
account_num = new TextField();
frame.add(account_num);
account_num.addActionListener(this);
frame.add(new Label("First Name"));
first_name = new TextField(20);
first_name.setEditable(false);
frame.add(first_name);
frame.add(new Label("Last Name"));
last_name = new TextField(20);
last_name.setEditable(false);
frame.add(last_name);
frame.add(new Label("Available Funds"));
balance = new TextField(20);
balance.setEditable(false);
frame.add(balance);
frame.add(new Label("Overdraft Limit"));
overdraft = new TextField(20);
overdraft.setEditable(false);
frame.add(overdraft);
enter = new Button("Enter");
enter.addActionListener(this);
frame.add(enter);
done = new Button("Click to Exit");
done.addActionListener(this);
frame.add(done);
setVisible(true); // GUI components set as visible to the program
}
public void readRecord() {
DecimalFormat twoDigits = new DecimalFormat("0.00");
try {
do {
data.read(input);
} while (data.getAccount() == 0);
input.seek(
(long) ( data.getAccount()-1 ) * Record.size());
data.write( input );
account_num.setText(String.valueOf(data.getAccount()));
first_name.setText(data.getFirstName());
last_name.setText(data.getLastName());
balance.setText(String.valueOf(twoDigits.format(data.getBalance())));
overdraft.setText(String.valueOf(twoDigits.format(data.getOverdraft())));
}// end try
catch (EOFException eof) {
closeFile();
}
catch (IOException e) {
// if an error occurs display a message on the screen
System.err.println("Error during read from file\n " + e.toString());
// the program terminates due to error
// System.exit(1);
}
}
private void closeFile() {
try {
input.close();
// System.exit(1);
} catch (IOException e) {
// if an error occurs display a message on the screen
System.err.println("Error closing file\n " + e.toString());
// System.exit(1);
}
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == enter)
readRecord();
else if (e.getSource() == done)
frame.dispose();
else
frame.add(new TextField(" Account Not Found on Database "));
closeFile();
}
public static void main(String args[]) {
new CredRead();
}
}
My guess is that
data.getAccount() != 0
and so your loop only executes once, because you did it in a do ... while();
Try adding some debugging into your code and make sure what data.getAccount() is equal to.

cant create a JTextField

import org.jsoup.Jsoup;
#SuppressWarnings({ "unused", "serial" })
public class SimpleWebCrawler extends JFrame {
JTextField yourInputField = new JTextField(20);
static JTextArea _resultArea = new JTextArea(200, 200);
JScrollPane scrollingArea = new JScrollPane(_resultArea);
private final static String newline = "\n";
String word2;
public SimpleWebCrawler() throws MalformedURLException {
yourInputField.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
word2 = yourInputField.getText();
}
});
_resultArea.setEditable(false);
try {
URL my_url = new URL("http://" + word2 + "/");
BufferedReader br = new BufferedReader(new InputStreamReader(
my_url.openStream()));
String strTemp = "";
while (null != (strTemp = br.readLine())) {
_resultArea.append(strTemp + newline);
}
} catch (Exception ex) {
ex.printStackTrace();
}
_resultArea.append("\n");
_resultArea.append("\n");
_resultArea.append("\n");
String url = "http://" + word2 + "/";
print("Fetching %s...", url);
try{
Document doc = Jsoup.connect(url).get();
Elements links = doc.select("a[href]");
System.out.println("\n");
BufferedWriter bw = new BufferedWriter(new FileWriter("C:\\Users\\user\\fypworkspace\\FYP\\Link\\abc.txt"));
_resultArea.append("\n");
for (Element link : links) {
print(" %s ", link.attr("abs:href"), trim(link.text(), 35));
bw.write(link.attr("abs:href"));
bw.write(System.getProperty("line.separator"));
}
bw.flush();
bw.close();
} catch (IOException e1) {
}
JPanel content = new JPanel();
content.setLayout(new BorderLayout());
content.add(scrollingArea, BorderLayout.CENTER);
content.add(yourInputField,BorderLayout.SOUTH);
this.setContentPane(content);
this.setTitle("Crawled Links");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.pack();
JPanel content2 = new JPanel();
this.setContentPane(content2);
this.setTitle("Input the URL");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.pack();
}
private static void print(String msg, Object... args) {
_resultArea.append(String.format(msg, args) +newline);
}
private static String trim(String s, int width) {
if (s.length() > width)
return s.substring(0, width - 1) + ".";
else
return s;
}
//.. Get the content pane, set layout, add to center
public static void main(String[] args) throws IOException {
JFrame win = new SimpleWebCrawler();
win.setVisible(true);
}
}
I am trying to create a JTextField to accept the user input. The input will go to this line of code to process the code.
URL my_url = new URL("http://" + word2 + "/");
String url = "http://" + word2 + "/";
However, the code is run without asking the user for input. The JTextField does not appear and i straight get an error on because i din enter the input.
I am trying to get the JTextField to accept input from the user. However, it does not appear and the code straight proceed with the processing end up with empty my_url and rmpty url variable.
How do i create a JTextField according to my code that i post ? It seems that the Jtextfield i created clashed with my codes.
Java swing does not follow the imperative approach but is event driven. Your constructor method is executed in total and does not wait for your input.
You must not include the business logic (i.e. all this read/write stuff) into this method but into a separate one and invoke it from the action listener your registered with your input field. (see e.g. http://download.oracle.com/javase/tutorial/uiswing/events/index.html)
Note A: If your logic is quite heavy you should spawn a background thread and not do it directly in your action listener (see Swingworker).
Note B: There is lot's of strange code within your class.
this.setContentPane(content);
this.setTitle("Crawled Links");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.pack();
JPanel content2 = new JPanel();
this.setContentPane(content2);
this.setTitle("Input the URL");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.pack();
As mentioned before this will be run immediately and thus your panel content is never shown at all because it will be overwritten by content2.

Categories