How do I validate a textfield in java - java

public class Login extends JFrame{
JFrame frame; //frame
JTextField field; //to get username
JPasswordField p; //password field
JLabel l; //used for printing on frame
JButton b;
Login() {
frame = new JFrame("Login");
frame.setSize(350,200);
frame.setLocationRelativeTo(null);
frame.setLayout(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
l = new JLabel("Enter Username");
l.setLocation(10,10);
l.setSize(l.getPreferredSize());
frame.add(l);
field = new JTextField();
field.setColumns(15);
field.setSize(field.getPreferredSize());
field.setLocation(120,10);
frame.add(field);
l = new JLabel("Enter Password");
l.setLocation(10,40);
l.setSize(l.getPreferredSize());
frame.add(l);
p = new JPasswordField();
p.setColumns(15);
p.setSize(p.getPreferredSize());
p.setLocation(120,40);
frame.add(p);
b = new JButton("OK");
b.setSize(b.getPreferredSize());
b.setLocation(120, 80);
frame.add(b);
frame.setVisible(true);
}
private class b implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
String str;
str = field.getText();
if(str.equals("")) {
JOptionPane.showMessageDialog(null,"Please enter username");
field.requestFocusInWindow();
} else {
}
}
}
public static void main (String[] args) {
new Login();
}
}
the button won't functioning when I'm hit it

the button won't functioning when I'm hit it
You need to add the ActionListener to the button:
b = new JButton("OK");
b.addActionListener( new b() );
Make your class names more descriptive. "b" is not descriptive. Also, class names should start with an upper case character.
Don't use null layouts and setBounds(...). Swing was designed to be used with Layout Managers. Keep a link to the tutorial handy for Swing basics.

Take a look at How to Write an Action Listeners and How to Use Buttons, Check Boxes, and Radio Buttons.
Basically, you never register the ActionListener with your JButton
b.addActionListener(new b());
You code would be easier to read if you used meaningful variable names and followed the establishing coding conventions of the language. Have a look at Code Conventions for the Java TM Programming Language, for more details, it will make it easier for people to read your code and for you to read others
You may also want to have a read of You might want to have a read of Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?, but since you're discarded the layout manager, the use of setPreferredSize is completely pointless.
Avoid using null layouts, pixel perfect layouts are an illusion within modern ui design. There are too many factors which affect the individual size of components, none of which you can control. Swing was designed to work with layout managers at the core, discarding these will lead to no end of issues and problems that you will spend more and more time trying to rectify

Related

How to add action to a button?

I am trying to enter an event for JButon I create:
JButton botton1=new JButton("welcom to my show db! lets start");
botton1.setFont(new Font ("Eras Medium ITC",Font.BOLD,20));
this.add(botton1);
JPanel Basic_panel=new JPanel();
Basic_panel.setName("SHOW DB ");
Basic_panel.setBounds(x,y,width,hight);
botton1.addActionListener(this) ;
}
public void actionPerformed(ActionEvent e) {
if (e.getSource()==botton1){
Now I want to enter another JFrame I made, and make the first disappear. How?
For your original question:
How to add action to a button?
you might want to check How to write an Action Listener.
For your second question:
Now I want to enter another JFrame I made, and make the first disappear. How?
please check both approaches :)
Option 1 (Recommended)
If you want to do it the right way, you should use a CardLayout as recommended by #AndrewThompson in his comment above.
I also saw you were using a Null Layout (because of setBounds() method), you might also want to get rid of it, see Why is it frowned upon to use a null layout in Swing? and Null Layout is Evil to know why, insted you should be using a Layout Manager or combinations of them as shown in the following code based on #AndrewThompson's answer (The same that was linked in his comment above) but a bit modified to work with a JFrame instead of a JOptionPane, so give him credit by upvoting his Original Answer too!
This produces the following outputs:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class CardLayoutDemo {
JButton button1, button2;
CardLayoutDemo() {
JFrame gui = new JFrame("CardLayoutDemo");
button1 = new JButton("Go to pane 2");
button2 = new JButton("Go to pane 1");
JPanel pane1 = new JPanel();
pane1.setLayout(new BoxLayout(pane1, BoxLayout.PAGE_AXIS));
JPanel pane2 = new JPanel();
pane2.setLayout(new BoxLayout(pane2, BoxLayout.PAGE_AXIS));
final CardLayout cl = new CardLayout();
final JPanel cards = new JPanel(cl);
pane1.add(new JLabel("This is my pane 1"));
pane1.add(button1);
pane2.add(new JLabel("This is my pane 2"));
pane2.add(button2);
gui.add(cards);
cards.add(pane1, "frame1");
cards.add(pane2, "frame2");
ActionListener al = new ActionListener(){
public void actionPerformed(ActionEvent ae) {
if (ae.getSource() == button1) {
cl.show(cards, "frame2");
} else if (ae.getSource() == button2) {
cl.show(cards, "frame1");
}
}
};
button1.addActionListener(al);
button2.addActionListener(al);
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.pack();
gui.setVisible(true);
}
public static void main(String[] args) {
new CardLayoutDemo();
}
}
With this option you only have 1 JFrame but you can change through different views, and you don't annoy user with multiple windows on the task bar.
One more tip here is: If you're going to open this second JFrame to prevent user from doing something on the 1st one, you should consider using a JOptionPane or this second JFrame will contain just a bit information which you don't want to have there for the whole time (Something like a pop up).
Option 2 (Not recommended)
But if you really really really want to use multiple JFrames (which is not recommended) you can dispose() it. At the time you're calling your new JFrame to be created. For example, the following code produces this output:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class TwoJFrames {
JFrame frame;
JButton button;
TwoJFrames() {
frame = new JFrame("1st frame");
button = new JButton("Click me!");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
new AnotherFrame();
frame.dispose();
}
});
frame.add(button);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public static void main(String args[]) {
new TwoJFrames();
}
class AnotherFrame {
JFrame frame2;
JLabel label;
AnotherFrame() {
frame2 = new JFrame("Second Frame");
label = new JLabel("This is my second frame");
frame2.add(label);
frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame2.pack();
frame2.setVisible(true);
}
}
}
In this case you might want to consider setVisible() instead if you want to go back to previous state or reopen this one when closing the second JFrame
Both of my above codes are called a Minimal, Complete, and Verifiable example (MCVE) or Runnable Example or Short, Self Contained, Correct Example (SSCCE) which are code you can copy-paste and see the same output as me, when you have an error in your code, these examples are very handy because we can see where your errors are or be able to find them easier and/or faster.
You should consider reading all the links I provided (included these ones) and for your future questions to make something like I've done above, that way you'll prevent confusion and you'll get more, faster and better responses.

Improper use of JTextField (maybe) Help creating a GUI

I'm very new to Java and I'm trying to create a small program that reverses text (That part I've figured out).
Where I'm getting stuck on is my GUI, my envisioned plan for the gui is a window with a centered text field for user input then under it in the directly middle of the window a button that reverses the text from the above text box and outputs it in a text box below the button.
Right now I'm using JTextField boxes and after trying to make them look the way I want I'm getting the feeling that there's an easier way to do it, but I don't know it.
Here's my GUI class:
public class ReverseTextGUI extends ReverseRun implements ActionListener {
public static JFrame frame;
private JPanel northFlowLayoutPanel;
private JPanel centerFlowLayoutPanel;
private JPanel southFlowLayoutPanel;
private final JButton reverse = new JButton("Reverse");
private final JTextField userInput = new JTextField(50);
private final JTextField reverseOutput = new JTextField(50);
public void actionPerformed(ActionEvent e) {
reverse.addActionListener((ActionListener) reverse);
reverse.setActionCommand("Reverse");
if ("algorithm".equals(e.getActionCommand())) {
System.out.println("test");
}
}
public void initUI() {
northFlowLayoutPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
northFlowLayoutPanel.add(userInput);
userInput.setPreferredSize(new Dimension(150,100));
centerFlowLayoutPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
centerFlowLayoutPanel.add(reverse);
southFlowLayoutPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
southFlowLayoutPanel.setBorder(BorderFactory.createTitledBorder("Output text"));
southFlowLayoutPanel.add(reverseOutput);
reverseOutput.setPreferredSize(new Dimension(150,100));
JFrame frame = new JFrame("Backwardizer");
frame.setLayout(new BorderLayout()); // This is the default layout
frame.add(northFlowLayoutPanel, BorderLayout.PAGE_START);
frame.add(centerFlowLayoutPanel, BorderLayout.CENTER);
frame.add(southFlowLayoutPanel, BorderLayout.PAGE_END);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setSize(750, 500);
}
Any ideas how to either move the cursor to the start of the box (it shows up in the middle as of now) or a better way to accomplish what I'm trying to do?
For the reversing aspect, you can add the text from the first box to a string builder
StringBuilder rev = new StringBuilder(firstBox.getText());
String reversedText = rev.reverse().toString();
secondBox.setText(reversedText);
Something along those line should get the desired result if you nest it in the button action.
Any ideas how to either move the cursor to the start of the box (it shows up in the middle as of now) or a better way to accomplish what I'm trying to do?
JTextField#setCaretPosition, call this AFTER you've updated the text of the field
Make the field readonly, JTextField#setEditable and pass it false
Additionally, you could use a JList or JTextArea if you want to store multiple rows/lines of text
You should also avoid using setPreferredSize, see Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing? for more details

Jbutton not clearing my text fields

I have a button to clear the text fields in the program that I am putting together but when I click it, it doesn't clear them. Here is my code plus the code for the button. I don't know what is wrong this is the way I shown to set up GUI's and this is the way it has always worked for me.
public class GradeCalculator extends JFrame implements ActionListener {
Container c;
JTextField gradeWeight1,gradeWeight2,gradeWeight3,gradeWeight4,gradeWeight5,gradeWeight6,
gradeWeight7,gradeWeight8,gradeWeight9,gradeWeight10;
JTextField gradeAch1,gradeAch2,gradeAch3,gradeAch4,gradeAch5,gradeAch6,gradeAch7,
gradeAch8,gradeAch9,gradeAch10;
JLabel score , weight;
JButton btnGPA, btnClear,btnCalc;
JPanel northP, southP;
public void actionPerformed(ActionEvent e) {
if(e.getSource() == btnClear){
gradeAch1.setText(null);
gradeWeight1.setText(null);
gradeAch2.setText(null);
gradeWeight2.setText(null);
gradeAch3.setText(null);
gradeWeight3.setText(null);
gradeAch4.setText(null);
gradeWeight4.setText(null);
gradeAch5.setText(null);
gradeWeight5.setText(null);
gradeAch6.setText(null);
gradeWeight6.setText(null);
gradeAch7.setText(null);
gradeWeight7.setText(null);
gradeAch8.setText(null);
gradeWeight8.setText(null);
gradeAch9.setText(null);
gradeWeight9.setText(null);
gradeAch10.setText(null);
gradeWeight10.setText(null);
}
}
public GradeCalculator(){
super("Grade Calculator");
c = getContentPane();
c.setLayout(null);
JPanel northP = new JPanel();
northP.setLayout(null);
northP.setBorder(BorderFactory.createTitledBorder("Enter your grades"));
northP.setSize(330,460);
northP.setLocation(2,0);
c.add(northP);
JLabel score = new JLabel("Grade you recieved..");
score.setSize(130,20);
score.setLocation(20,30);
northP.add(score);
JLabel weight = new JLabel("Weight of the grade..");
weight.setSize(140,20);
weight.setLocation(190,30);
northP.add(weight);
JButton btnClear = new JButton("New Calculation");
btnClear.setSize(150,20);
btnClear.setLocation(90,530);
btnClear.addActionListener(this);
btnClear.setMnemonic(KeyEvent.VK_N);
c.add(btnClear);
}
public static void main(String[] args) {
GradeCalculator app = new GradeCalculator();
app.setSize(350,600);
app.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
app.setVisible(true);
}
}
First General Suggestions:
First off, your code is begging you to use arrays or ArrayLists. This will simplify your code greatly and make it much easier to enhance, debug, and fix.
Don't set the text to null but rather to "", the empty String.
Don't set sizes or locations of any components but rather use the layout managers to do this for you.
Now for your problem:
I'm guessing here, because your code does not show us your error, but I suspect that you're calling setText(...) on the wrong references, on JButtons that aren't part of your displayed GUI. Is the listener code in a different class from that of the displayed GUI? Are you misusing inheritance by having the listener code class extend the GUI?
Or does your code have more than one btnClear variable? Are you creating the button with a "shadow" variable, one that is re-declared in a construtor or method while the class field is null?
___________________________________________________________
Please show us more information and code for a more detailed and accurate answer.
Edit
Solution: it's my second point, that you're shadowing your btnClear variable. Don't re-declare it!
e.g.,
public GradeCalculator(){
super("Grade Calculator");
// ... etc...
// **** here ****
JButton btnClear = new JButton("New Calculation");
// .... etc...
}
change to:
public GradeCalculator(){
super("Grade Calculator");
// ... etc...
// **** here ****
btnClear = new JButton("New Calculation");
// .... etc...
}
The reason this is important, by re-declaring the variable in the constructor, you create a new variable that is visible only inside of the constructor. The btnClear field in the class is null since you never initialize it.

Code Executing in different orders, Jframe, Button and TextArea

Basically i have some code to make an interface that allows me to submit a request and it pulls the necessary information from a txt File. For some reason wheni execute my StartUp for the code, sometimes the button isnt there, one text box dominates the screen, all the textboxes overlap... Its weird.
Anyway heres the GUI Code
public class Menu {
SubmitCode submit = new SubmitCode();
public static JFrame frame;
public static JTextField field;
public static Button btn;
public static TextArea txtComm;
public static TextArea txtSites;
public static TextArea txtProg;
public static Dimension dim = new Dimension(40, 10);
public Menu() {
frame = new JFrame();
frame.setTitle("Welcome :)");
frame.pack();
frame.setResizable(false);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
}
public static void open() {
Menu.main(null); // Opens up the main method of the class
}
public static void main(String args[]) {
field = new JTextField();
btn = new Button();
txtComm = new TextArea();
txtSites = new TextArea();
txtProg = new TextArea();
field.setText("What do you want to do?");
field.setSize(390, 20);
field.setLocation(0, 125);
btn.setVisible(true);
btn.setLabel("Click to Submit");
btn.setSize(90, 20);
btn.setLocation(400, 125);
txtComm.setVisible(true);
txtComm.setText("Commands: ");
txtComm.setSize(150, 100);
txtComm.setLocation(10, 10);
txtComm.setEditable(false);
frame.add(txtComm);
txtSites.setVisible(true);
txtSites.setText("Sites: ");
txtSites.setSize(150, 100);
txtSites.setLocation(170, 10);
txtSites.setEditable(false);
frame.add(txtSites);
txtProg.setVisible(true);
txtProg.setText("Programmes: ");
txtProg.setSize(150, 100);
txtProg.setLocation(330, 10);
txtProg.setEditable(false);
frame.add(txtProg);
frame.setSize(500, 175);
frame.add(field, BorderLayout.SOUTH);
frame.add(btn);
btn.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.out.println("Do Something Clicked");
SubmitCode.main(null);
}
});
}
}
Suggestions:
Don't use static methods/fields, except when a specific need arises or for the main method. You do not have the need here.
Instead use valid classes, classes with constructors, instance (non-static) fields and instance methods.
Don't needlessly mix AWT and Swing components but instead use just Swing components. So JTextArea, not TextArea, JButton, not Button, etc....
For instance, your Menu constructor is wasted code that is never called due to your misuse and over-use of statics.
Don't set sizes, use null layouts and absolute positioning such as with setBounds.
Instead read up on and use the layout managers.
Don't pepper your code with useless bits such as most of your calls to setVisible(true).
Call setVisible(true) on the top level window, here your JFrame, after adding all components.
Do read the relevant tutorials as this is all very well explained there. Google Java Swing Tutorials and check the very first hit.
This bit scares me: SubmitCode.main(null); and suggests that you're trying to call the static main method of another class from within a GUI. You should avoid doing this, and instead have your SubmitCode class use good OOP techniques including non-static methods and fields, constructors, etc...

Swing GUI Factory Method Pattern

I am looking to use the Factory Method Pattern in order to make the development of my Swing UI quicker and more manageable.
In general, its an MDI application using JInternalFrames. I have a lot of settings, types as I call them, in the system (Eg. userTypes, accountTypes, etc.) I have a fixed UI which I've decided to use. Thing is, there are over 50 of these types in the system, so the factory method pattern seems to be the most manageable solution. Below are two screenshots of a working app.
I was looking at [this example][3] but since I wont be able to estimate the number of tabs I would require to store all info in a record, I would need to be able to add multiple tabs and controls (labels, textboxes, tables, comboboxes, etc.) within these tabs.
Based on the example, is it possible to create a JTabbedPane in the abstract class and modify and add to it in the subclasses? I tried the following and am a bit lost:
public AbstractTypeInternalFrame(String title) {
setBounds(100, 100, 808, 589);
JToolBar toolBar = new JToolBar();
getContentPane().add(toolBar, BorderLayout.NORTH);
JButton btnAdd = new JButton("Add");
toolBar.add(btnAdd);
JButton btnSave = new JButton("Save");
btnSave.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
toolBar.add(btnSave);
JButton btnDelete = new JButton("Delete");
toolBar.add(btnDelete);
JButton btnCancel = new JButton("Cancel");
btnCancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
toolBar.add(btnCancel);
JTabbedPane recordTabs = new JTabbedPane(makeRecordTabPane());
getContentPane().add(recordTabs, BorderLayout.NORTH);
JSeparator recordSearchSeparator = new JSeparator();
getContentPane().add(recordSearchSeparator, BorderLayout.NORTH);
}
protected abstract int makeRecordTabPane();
with the method makeRecordTabPane() require to return an int.
As you can see, I'm a little lost and just need some direction as to how to proceed with such a pattern. If any has any advice or even examples/links, it would be much appreciated.
I realize my question is vague, so if any clarification is required on my side, please feel free to ask.
Best regards.
Here is the question in more detail.
So, I am looking to build a simple JInternalFrame for CRUD operations on records on the system. Records such as users, usertypes, accounts, accountypes, etc. There are more than 50 of these types in the system, so I figure using the factory method pattern would make all these JInternalFrames more manageable.
Here is an example of a user record:
Link1
Link2
The top half constitutes of the details of a record, which are split into tabs depending on the contents of the record. Some records may have just one tab, while other larger ones will have multiple. Therefore, the contents of the JTabbedPane should be instantiated at the subclass level and per this example.
The bottom part is where we would search for records of that type. Say for example, in the links posted, the User Manager JInternalFrame is opened. We then would search for users according to username and/or userID. Results are displayed in the table below and on double-clicking a search result, the record is displayed above in the JTabbedPane.
Add, Save, Delete and Cancel buttons are then used to perform CRUD operations on whatever is entered into the record.
From this, we can say that the aspects of the design than need to be instantiated by subclasses are:
1) Size of the JInternaFrame
2) All contents of the JTabbedPane: no of tabes, tables, labels, textboxes, etc.
3) The number of columns in the search result JTable: which we can change by instantiating the JTable Header.
As a start, I was trying to just create an Abstract class with a JTabbedPane, and add components to the JTabbedPane to see how I could go about it. This is the code I posted earlier. This file was generated using WindowBuilder, which I later then modified:
package zm.co.freight.fpsManagementGUI.view;
import java.awt.EventQueue;
public abstract class AbstractTypeInternalFrame extends JInternalFrame {
/**
* Launch the application.
*/
// public static void main(String[] args) {
// EventQueue.invokeLater(new Runnable() {
// public void run() {
// try {
// AbstractTypeInternalFrame frame = new AbstractTypeInternalFrame();
// frame.setVisible(true);
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
// });
// }
/**
* Create the frame.
*/
public AbstractTypeInternalFrame(String title) {
setBounds(100, 100, 808, 589);
JToolBar toolBar = new JToolBar();
getContentPane().add(toolBar, BorderLayout.NORTH);
JButton btnAdd = new JButton("Add");
toolBar.add(btnAdd);
JButton btnSave = new JButton("Save");
btnSave.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
toolBar.add(btnSave);
JButton btnDelete = new JButton("Delete");
toolBar.add(btnDelete);
JButton btnCancel = new JButton("Cancel");
btnCancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
toolBar.add(btnCancel);
JTabbedPane recordTabs = new JTabbedPane(makeRecordTabPane());
getContentPane().add(recordTabs, BorderLayout.NORTH);
JSeparator recordSearchSeparator = new JSeparator();
getContentPane().add(recordSearchSeparator, BorderLayout.NORTH);
}
protected abstract int makeRecordTabPane();
}
The question is, am I on the right track? How should I approach it using the factory method pattern as I don't seem to grasp it very well. I've seen simpler examples, with shapes and drawings, but am a bit lost with Swing interfaces. Is there a good example you could direct me to or a simple example just to point me in the right direction ... thats all I was asking for. Sorry if it was vague ...

Categories

Resources