How can I use general string in Jspinner? - java

I have problem with JSpinner over to show Month in JSpinner and i have follow code bellow.I use swing control with jframe form to use spinner control. When I run project it always set default value 0. How to solve this error?
static protected String[] getMonthStrings(){
String[] months=new DateFormatSymbols().getMonths();
int lastIndex=months.length-1;
if(months[lastIndex]==null || months[lastIndex].length()<=0){
String[] mS=new String[lastIndex];
System.arraycopy(months,0,mS, lastIndex,0);
return mS;
}
else{
return months;
}
}
public spinner(boolean CycleMonths) {
initComponents();
JTextField tf=null;
String[] monthStrings = getMonthStrings();
SpinnerListModel monthModel=null;
if(CycleMonths){
monthModel=new CycleSpinnerList(monthStrings);
}
else {
monthModel=new SpinnerListModel(monthStrings);
}
spMonth=new JSpinner(monthModel);
}

In your constructor code, you are calling initComponents, then creating your SpinnerListModel, creating a new JSpinner, but never adding it anywhere... So it looks like the problem is that you're just not adding the JSpinner anywhere
public spinner(boolean CycleMonths) {
initComponents();
JTextField tf=null;
String[] monthStrings = getMonthStrings();
SpinnerListModel monthModel=null;
if(CycleMonths){
monthModel=new CycleSpinnerList(monthStrings);
}
else {
monthModel=new SpinnerListModel(monthStrings);
}
spMonth=new JSpinner(monthModel);
}

Related

How would I program an array of Strings to work as a set of passwords?

So I'm trying to get a java applet to accept a set of multiple passwords, so naturally I thought to put them in array. However, only one of the passwords in the array is working, the last one in the set. None of the ones before it will work and my applet denies the others. This is my code so far:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class JPasswordC extends JApplet implements ActionListener
{
private final String[] password = {"Rosebud", "Redrum", "Jason", "Surrender", "Dorothy"};
private Container con = getContentPane();
private JLabel passwordLabel = new JLabel("Password: ");
private JTextField passwordField = new JTextField(16);
private JLabel grantedPrompt = new JLabel("<html><font color=\"green\">Access Granted</font></html>");
private JLabel deniedPrompt = new JLabel("<html><font color=\"red\">Access Denied</font></html>");
public void init()
{
con.setLayout(new FlowLayout());
con.add(passwordLabel);
con.add(passwordField);
con.add(grantedPrompt);
grantedPrompt.setVisible(false);
con.add(deniedPrompt);
deniedPrompt.setVisible(false);
passwordField.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
String input = passwordField.getText();
for(String p : password)
{
if(input.equalsIgnoreCase(p))
{
grantedPrompt.setVisible(true);
deniedPrompt.setVisible(false);
}
else
{
grantedPrompt.setVisible(false);
deniedPrompt.setVisible(true);
}
}
}
}
How would I get this to work properly? Am I doing something wrong with the array? Is it something in the code altogether?
The code is checking each password even if a valid one is found meaning that even if a valid password is found it will still change based on the validity of the next password. So the last one in the array declares the status of grantedPrompt and deniedPrompt. Try adding a break after the input is equal to one of the passwords.
for(String p : password)
{
if(input.equalsIgnoreCase(p))
{
grantedPrompt.setVisible(true);
deniedPrompt.setVisible(false);
break; // break out or loop once found
}
else
{
grantedPrompt.setVisible(false);
deniedPrompt.setVisible(true);
}
}
You are looping through all the passwords,even though there is a match.So change the code to return the method when ever there is a match in the password.
public void actionPerformed(ActionEvent ae)
{
String input = passwordField.getText();
for(String p : password)
{
if(input.equalsIgnoreCase(p))
{
grantedPrompt.setVisible(true);
deniedPrompt.setVisible(false);
return;
}
}
grantedPrompt.setVisible(false);
deniedPrompt.setVisible(true);
}

Creating Custom Components - Extending to JFormattedField

I am currently working on an application and I have a certain requirement for my interface: A time input.
I need my controls to accept 12hrs to 24hrs input using JFormattedTextField and found this:
MaskFormatter mask = new MaskFormatter("##:##");
mask.setPlaceHolderCharacter('0');
Now I created a class that extends to a JFormattedTextField
public class JayTimeInput extends JFormattedTextField{....
now I peeked inside JFormattedTextField's source and found something like this:
public JFormattedTextField(Object mask){...
my question is: How do I create my JayTimeInput class that automatically has a mask formatter? I tried declaring it in my constructor but I am not sure about this:
public JayTimeInput(){
try{
MaskFormatter mask = new MaskFormatter("##:##");
mask.setPlaceHolderCharacter('0');
new JFormattedTextField(mask);
}catch(Exception e){e.printStackTrace()}
}
Ive seen examples on how to use MaskFormatter and the only way I found was by declaring it like this:
MaskFormatter mask = new MaskFormatter("##:##");
mask.setPlaceHolderCharacter('0');
JFormattedTextField jformat = new JFormattedTextField(mask);
Im not sure if my actionlistener was correctly done but I need this to work first.
anyone help me out? im still new in creating my own controls by extending existing swings.
UPDATE:
I was looking at the wrong way of customizing my JFormattedTextField. I Should've used FormatFactory. Answer code has been posted for anyone who needs it.
//if you found this usefull, please dont remove this
//and credit my work for this
//James C. Castillo
//zeinzu21#gmail.com
import java.awt.event.KeyEvent;
import javax.swing.JFormattedTextField;
import javax.swing.text.MaskFormatter;
public final class JayTimeInput extends JFormattedTextField{
public JayTimeInput(){
myFormat();
addKeyListener(new java.awt.event.KeyAdapter() {
#Override
public void keyTyped(java.awt.event.KeyEvent evt) {
verify(evt);
}
});
}
public void myFormat() {
try {
MaskFormatter format = new MaskFormatter("##:##");
format.setPlaceholderCharacter('0');
this.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(format));
} catch (java.text.ParseException ex) {
ex.printStackTrace();
}
}
public String getTime(){
return this.getText();
}
public void setTime(String x){
this.setText(x);
}
public void resetTime(){
this.setText("00:00");
}
public void setFocus(boolean f){
this.setFocusable(f);
this.setVerifyInputWhenFocusTarget(f);
}
public void verify(KeyEvent evt){
try {
int carret = this.getCaretPosition();
char c = evt.getKeyChar();
if(carret==0){
int hour = Integer.parseInt(c+"");
if(hour>1){
evt.consume();
}
}
if(carret==1){
int hour = Integer.parseInt(c+"");
if(hour>2){
evt.consume();
}
}
if(carret==3){
int min = Integer.parseInt(c+"");
if(min>5){
evt.consume();
}
}
} catch (Exception e) {
//do nothing. nothing to catch since its keyevent
}
}
}

getSelectedItem JComboBox with GlazedLists AutocompleteSupport Returns Null

I'm a bit new to programming so sorry if there is a few things that could have been done better
My combobox is successfully filled with my string array and the auto-complete works fine. I just cant get the text in the combobox.
returns java.lang.NullPointerException
private ArrayList<String> arrRekening;
private ArrayList<String> arrEienaar;
private String[] sarrRekening;
private String[] sarrEienaar;
public NewConnectionPoint() {
arrAccount = new ArrayList<String>();
arrOwner = new ArrayList<String>();
FillCombo(arrAccount , "Owners", "OwnerName");
FillCombo(arrOwner , "Accounts", "AccountName");
sarrOwner= arrOwner.toArray(new String[arrOwner .size()]);
sarrAccount= arrAccount.toArray(new String[arrAccount.size()]);
JComboBox<String> comboAccount = new JComboBox<String>();
AutoCompleteSupport<String> supAccount = AutoCompleteSupport.install(comboRekening, GlazedLists.eventList(Arrays.asList(sarrAccount)));
supAccount.setStrict(true);
JComboBox<String> comboOwner = new JComboBox<String>();
AutoCompleteSupport<String> supOwner = AutoCompleteSupport.install(comboOwner,GlazedLists.eventList(Arrays.asList(sarrOwner)));
supOwner.setStrict(true);
JButton btnShow = new JButton("ShowSelectedr");
btnShow.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
//Error occurs at this line
JOptionPane.showMessageDialog(null, comboOwner.getSelectedItem().toString());
});}
}
//Data loaded into arraylists from a Database with sql
private void FillCombo(ArrayList<String> ComboElements, String sTable, String sColumn){
try{
Data.changeQuery(sTable);// database connection fine returns and fills combobox
while(MyData.rs.next()){
String sReturn= MyData.rs.getString(sColumn);
ComboElements.add(sReturn);
}
}catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
The fundamental difficulty you're experiencing here is that you're trying to leverage the GlazedLists package without properly embracing it's core utility: EventLists.
You can easily side-step your difficulties if you use EventLists rather than ArrayLists.
If you really want to you can keep your FillCombo method returning an ArrayList (perhaps better name as getElements()) but straight-away initiate an EventList, use the GlazedLists EventComboBoxModel to link the EventList to the JComboBox and then you'll find your combobox getSelectedItem() should work fine.
The modified code to hook a list up to a combobox with autocomplete support will look something like this:
...
FillCombo(arrOwner , "Owners", "OwnerName");
EventList<String> ownerEventList = GlazedLists.eventList(arrOwner);
EventComboBoxModel<String> ownerModel = new EventComboBoxModel<String>(ownerEventList);
JComboBox comboOwner = new JComboBox(ownerModel);
AutoCompleteSupport<String> supOwner = AutoCompleteSupport.install(comboOwner,ownerEventList);
supOwner.setStrict(true);
...

How to setText() into not enabled JFormattedTextField

I've got problem trying to setText into my JFormattedTextField when it is not enabled. It's all right, when it is... String value is not empty, but the field stays empty.
private SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy") {
#Override
public Date parse(String source) throws ParseException {
return (source != null && !source.trim().equals("") && !source.trim().equals(". .")) ? super.parse(source) : null;
}
};
...
jFormattedTextField1 = new javax.swing.JFormattedTextField();
`enter code here`...
jFormattedTextField1.setFormatterFactory(new DefaultFormatterFactory(mf));
jFormattedTextField2.setFormatterFactory(new DefaultFormatterFactory(mf));
jFormattedTextField1.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
super.mouseClicked(e);
showPopup(jFormattedTextField1);
}
});
`jFormattedTextField1.setText("22.10.2012");`
just use Apache StringUtils.isBlank or StringUtils.isNotblank quite handy instead checking for null or empty.
The prolem was with Look and Feel Nimbus. The colour of text and TextField is the same

getText() vs getPassword()

I'm currently designing a login system for a make-believe company, right now all I have is the Main login, which needs a lot of cleaning up. Below is my login handler.
private class LoginButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
if(_uid.getText().equalsIgnoreCase("Nathan") && _pwd.getText().equals("password")) {
JOptionPane.showMessageDialog(null, "Congratulations on logging in!");
} else {
JOptionPane.showMessageDialog(null, "Error on login!");
}
}
}
As is, this works perfectly fine, but when I change it to
_pwd.getPassword.equals("password")
it directs straight to the else statement when everything is input correctly.
What is wrong here? Full program below.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Main extends JFrame {
private static final int HEIGHT = 90;
private static final int WIDTH = 400;
JTextField _uid = new JTextField(10);
JPasswordField _pwd = new JPasswordField(10);
JButton _login = new JButton("Login");
JButton _reset = new JButton("Reset");
public Main() {
super("Login - Durptech");
Container pane = getContentPane();
setLayout(new FlowLayout());
add(new JLabel("User ID:"));
add(_uid);
add(new JLabel("Password:"));
add(_pwd);
add(_login);
_login.addActionListener(new LoginButtonHandler());
add(_reset);
_reset.addActionListener(new ResetButtonHandler());
/*if(_uid.getText().equals("") && _pwd.getText().equals("")) {
_login.setEnabled(false);
} else {
_login.setEnabled(true);
}*/
setSize(WIDTH, HEIGHT);
setResizable(false);
setLocation(500, 300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
private class ResetButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
_uid.setText("");
_pwd.setText("");
_uid.requestFocusInWindow();
}
}
private class LoginButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
if(_uid.getText().equalsIgnoreCase("Nathan") && _pwd.getText().equals("password")) {
JOptionPane.showMessageDialog(null, "Congratulations on logging in!");
} else {
JOptionPane.showMessageDialog(null, "Error on login!");
}
}
}
public static void main(String[] args) {
new Main();
}
}
You will want to get to know the API well, to make it your best friend. The key to solving this is to see what JPasswordField#getPassword() returns. Hint 1: it's not a String. Hint 2: you may want to solve this using the java.util.Arrays class methods.
The reason getPassword doesn't return a String is because of the way Java handles Strings -- it can store them in the String pool, allowing Strings to hang out in the program longer than you'd expect, and making the Strings potentially retrievable by malware -- something you don't want to have happen to a password. It's much safer to work with char arrays.
Incidentally, don't use JPasswords deprecated getText() method or change a char array to a String using the new String(char[]) constructor since as these both return a String, they are not secure.
JPasswordField.getPassword() returns a char [] instead of a String. This is done for the sake of security. You should compare the characters inside the array instead of seeing if the char [] .equals(a String);
password.getPassword() returns a char[], and char[]'s aren't equal to Strings. So you need to compare it to a char[]:
if (Arrays.equals(password.getPassword(), new char[]{'p','a','s','s','w','o','r','d'}))
As all the other answers have said, JPasswordField returns a char[] when you call the getPassword() method. However, the way I have it set in my sample log on form is I have a method for validating the input. I have two arrays for storing usernames[] and passwords[] and then I have my username input, and my password input. The password input in my method changes the char[] to a string before continuing, you can do so like this:
String PasswordTyped = new String(_pwd.getPassword());
Then take that string and place that in your 'if' statement:
if (_uid.equals("Nathan") && PasswordTyped.equals("password") {
JOptionPane.showMessageDialog(null, "Congrats, you logged in as Nathan");
}
However, as I mentioned my validation method runs on the two arrays of usernames[] and passwords[], while accepting a string and a char[] as input. I will copy and paste my method so you can implicate it if you would like:
public static void validate(String u, Char[] pass) {
String password = new String(pass);
boolean uGood = false;
String[] usernames = new String[2];
String[] passwords = new String[usernames.length];
usernames[0] = "Don";
passwords[0] = "password";
usernames[1] = "Jared";
passwords[1] = "password";
for (int i = 0; i < usernames.length; i++) {
if (usernames[i].equals(u) && passwords[i].equals(password)) {
uGood = true;
}
}
if (uGood) {
System.out.println("Hooray, you did it!");
}
else {
JOptionPane.showMessageDialog(null, "Incorrect Username\nand/or Password.");
}
}
Finally, you would call this validation method by typing:
validate(_uid.getText(), _pwd.getPassword());

Categories

Resources