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.
Related
Apparently my Google-fu skills are bit lacklustre and I can't figure out how to get JTextField when pressing a JButton.
Please note that I've removed some parts of the code for ease of reading.
If you see some variable that's not defined assume that it was part of that code.
As it stands, the code works fine.
public final class Main {
// Some removed code was here
private void prepareGUI() {
// Top right stuff
JPanel topRightPanel = new JPanel();
topRightPanel.setLayout(new FlowLayout());
JLabel topRightLabel = new JLabel("Address");
JTextField topRightTextField = new JTextField("", 15);
topRightTextField.setName("add_address");
JButton topRightButton = new JButton("Add");
topRightButton.setName("add_btn");
topRightPanel.add(topRightLabel);
topRightPanel.add(topRightTextField);
topRightPanel.add(topRightButton);
mainFrame.add(topRightPanel);
// The button in question. Very suggestive name, I know.
topRightButton.addActionListener(new GenericButtonListener());
genericButtonListener.setKernel(kernel);
// some other non relevant stuff here
mainFrame.setVisible(true);
}
}
public class GenericButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
JButton btn = (JButton) e.getSource();
String btnName = btn.getName();
if(btnName.toLowerCase().contains("add_btn")) {
addBtn(btn);
}
}
public void addBtn(JButton button){
SshFileIO sshFileIO = kernel.getFileIO();
// Get field text here
}
}
My current dilemma is how to get said textfield value inside GenericButtonListener.
I realize that I can use getText to get the text field value, however I don't have access to that variable inside the actionPerformed function.
I suppose this is more of a scoping problem rather than anything else.
I just need some pointing in the right direction, no hand holding required.
It's painfully obvious that I'm very new to Java.
Please try to get a reference of topRightTextField with the constructor of GenericButtonListener. Store as property of the class and use it inside actionPerformed.
Change this one:
topRightButton.addActionListener(new GenericButtonListener());
To this:
topRightButton.addActionListener(new GenericButtonListener(topRightTextField));
And inside class GenericButtonListener add field:
private JTextField topRightTextField;// set it in the constructor
And then use it inside of your method actionPerformed.
Have a nice coding and good luck!
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
I do not understand what is happening in my code, when I fire a button with attached action listener, reading the JTextField getText() value shows as null, even though all fields contain text. Furthermore when I debugged the code and stopped just before this line the JTextField object showed as null as well, like it was never initialised in the first place.
I'm not sure whether I can keep all these JLabel and JTextField as class members and then just freely read from them.
public class EditPartGUI extends JFrame {
private JLabel manufacturerLabel;
private JTextField manufacturerTextField;
private JButton submit;
private ActionListener submitListener;
public EditPartGUI(Part part) {
JPanel panel = new JPanel();
this.setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
panel.add(initialiseField("Manufacturer: ", manufacturerLabel, part.getManufacturer(), manufacturerTextField));
JPanel sub = new JPanel();
submit = new JButton("Submit");
submitListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println(submit().toString());
}
};
submit.addActionListener(submitListener);
sub.add(submit);
panel.add(sub);
this.add(panel);
}
public JPanel initialiseField(String label, JLabel contentLabel, String value, JTextField contentTextField) {
JPanel contentPanel = new JPanel();
contentLabel = new JLabel(label, JLabel.TRAILING);
contentTextField = new JTextField(10);
contentTextField.setText(value);
contentLabel.setLabelFor(contentTextField);
contentPanel.add(contentLabel);
contentPanel.add(contentTextField);
return contentPanel;
}
public Part submit() {
Part p = new Part();
p.setManufacturer(this.manufacturerTextField.getText()); // <---- this is where NullPointerException shows
return p;
}
}
I'm not sure whether I can keep all these JLabel and JTextField as class members and then just freely read from them.
Yes you can and that is the solution to your problem.
Just use the following when you
//private JTextField manufacturerTextField;
private JTextField manufacturerTextField = new JTextField();
and don't try to create the text field in your initialiseField() method. Of course you will need to do the same with the label.
so I could avoid repeating the same code for each field (there are a lot more of them in my actual code).
If you want to have many panels with those fields, then you need to create a custom class to create the panel and then the text fields and labels will be part of that class, not your main class.
The problem is, that you assume that the method initialiseField is assigning the argument contentTextField to manufactererTextField. This won't work in Java as David Wallace already stated.
If you want to avoid repeating the same code, try to create a method that returns the initialised TextField and assign it in the constructor.
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...
I am having a bit of problem regarding Swing. I have a JFrame called FrameMain. Inside it is a JPanel called panelChoices.
When FrameMain is called/created, it fills up the panelChoices object with a number of PanelEntries objects, which is a JPanel with a number of JButtons in it (it is a different class that I wrote).
What I want to do is when I click one of the buttons inside the PanelEntries object, I want to destroy/remove FrameMain, along with the rest of it components (including the PanelEntries object that contains the JButton).
I've tried using super but it returns the JPanel (the PanelEntries object) that holds the JButton and not FrameMain that holds them all together. How can I achieve this?
EDIT: It seems that I am not clear enough, so here's a bit more information from my work. I don't have the actual code right now because I am on a different machine but I hope this will help elaborate my question.
public class FrameMain() {
private JFrame frameMain;
private JPanel panelChoices;
public FrameMain(args) {
createGUI();
loadData();
}
private void createGUI() {
JFrame frameMain = new JFrame();
JPanel panelChoices = new JPanel(new GridLayout(1,1));
frameMain.add(panel);
// removed formatting and other design codes since they are not important.
pack();
}
private void loadData() {
boolean available;
for (int i = 1; i <= 10; i++) {
// do some if/else and give value to boolean available
PanelEntries panel = new PanelEntries(i, available);
frameMain.add(panel);
// more code here to handle data.
}
}
}
public class PanelEntries() extends JPanel {
public PanelEntries(int num, boolean avb) {
JButton button = new JButton("Button Number " + num);
button.setEnabled(avb);
add(button);
// add action listener to created button so that it calls 'nextScreen()' when clicked.
// more code
pack();
}
private void nextScreen() {
// destroy/dispose MainFrame here.
// See Notes.
AnotherFrame anotherFrame = new AnotherFrame();
}
}
Notes:
All classes are inside their own .java file.
I need to know how to dispose FrameMain from the button inside the PanelEntries object, not just disposing a JFrame.
As per the given information,
If you want to exit the application, its not a big deal use System.exit(0); :)
If you mean to dispose the frame, jframe.dispose();
If you want to remove a componet / all components you can use .remove(Component) / .removeAll() etc
If this did not help, please re-write your question with more information.