Netbeans Swing jButton - java

I have two buttons and in the second one I want to use a variable made in the first button. So Netbeans is generating code of the button. ActionEvent generated by netbeans is
"private void buttonActionPerformed(java.awt.event.ActionEvent evt)"
and I cant change it. I tried to change button to public in button setting. I changed it to public but in code it is still private. I dont know what to do. Anyone know where the problem might be?
Thanks.

What you want to do is, there is a blank line above the private void buttonActionPerformed(ActionEvent evt) you create your variable in that line the example: int a; now the a will turn green. This is called a global variable

JFrame jtfMainFrame;
JButton jbnButton1, jbnButton2;
JTextField jtfInput;
JPanel jplPanel;
//Declaring the string variable setText
String setText;
public JButtonDemo2() {
jtfMainFrame = new JFrame("Which Button Demo");
jtfMainFrame.setSize(50, 50);
jbnButton1 = new JButton("Button 1");
jbnButton2 = new JButton("Button 2");
jtfInput = new JTextField(20);
jplPanel = new JPanel();
jbnButton1.setMnemonic(KeyEvent.VK_I); //Set ShortCut Keys
jbnButton2.setMnemonic(KeyEvent.VK_I);
jbnButton1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//Setting the setText variable
setText = "Do whatever you want";
}
});
jbnButton2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//Displaying the setText variable
jtfInput.setText(setText);
}
});
jplPanel.setLayout(new FlowLayout());
jplPanel.add(jtfInput);
jplPanel.add(jbnButton1);
jplPanel.add(jbnButton2);
jtfMainFrame.getContentPane().add(jplPanel, BorderLayout.CENTER);
jtfMainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jtfMainFrame.pack();
jtfMainFrame.setVisible(true);
}

Simply declare it as a global means when the class definition starts at that time declare the variable which you want to use at the two buttons click and change the value of variable according to your use.

No need to change the ActionPerformed(). All you have to do is declare the variable as a global variable and then do whatever the task inside the button's ActionPerformed().

Related

Swing get JTextField upon JButton press

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!

changing attributes to a JButton created by a method without variable name

I create some JButtons with a method, but I don't give them a variable i can call them with. i was wondering if it is possible to change the text somehow, after the button is created from another method. I am aware of that i can get the action command when the button is pressed but i want to change the button text, without it being pressed. I can give the buttons names like but would prefer not to. since I am only going to call half of them, and then I don't think its a good idea. or is it?
JButton button1 = buttons(0,0,0);
public JButton buttons(int coord, int coord1, int number) {
JButton box = new JButton("");
box.setFont(new Font("Tahoma", Font.PLAIN, 60));
box.setBounds(coord, coord1, 100, 100);
contentPane.add(box);
box.addActionListener(this);
box.setActionCommand(Integer.toString(number));
return box;
}
public static void main(String[] args) {
buttons(0,0,0);
buttons(98,0,1);
buttons(196,0,2);
buttons(0,98,3);
addText();
}
public void addText() {
//help me guys
button.setText("Please fix me");
}
You can get pressed button from actionEvent
#Override
public void actionPerformed(ActionEvent e) {
JButton button = (JButton)e.getSource();
}
Why not just have them in a public arraylist?
ArrayList<JButton> buttons = new ArrayList<JButton>();
public JButton buttons(int coord, int coord1, int number) {
JButton box = new JButton("");
box.setFont(new Font("Tahoma", Font.PLAIN, 60));
box.setBounds(coord, coord1, 100, 100);
contentPane.add(box);
box.addActionListener(this);
box.setActionCommand(Integer.toString(number));
buttons.add(box);//Add it here
return box;
}
This way you can loop through them later and change something if you want to,
for(JButton b : buttons){
if(/*Whatever*/){
b.setText("New name");
}
}
I can give the buttons names like but would prefer not to. since I am only going to call half of them, and then I don't think its a good idea. or is it?
You are creating problems for yourself. Even if you may only need the call a few/none of them, there is significant advantage for not keeping a reference for them.
If you have too many JButtons and you do not want to have a separate variable name for each of them, you can have an array/collection of JButtons.
JButton[] btns = new JButton[size];
//or
ArrayList<JButton> btns= new ArrayList<JButton>();
To change text for all buttons:
for(JButton b : btns)
btns.setText("whatever here");
To change text for a specific button:
btns[x].setText("whatever here"); //from array
btns.get(x).setText("whatever here"); //from list
Alternatively, if you do not keep a reference. You can get the list of buttons from the content pane:
Component[] components = myPanel.getComponents();
for(Component c : components)
if(c instanceof JButton)
((JButton)c).setText("whatever here");

Adding a button that reset all the text fields Netbeans Java

I'm trying to make a simple calculator and i want a reset button when pressed it clears all the text fields. I've already added an addActionListener and and ive already added the button panel just need to know the method on how do I do this. here is my code -
else if(choice.equals("c")) {
xValue = inputXTextField.getText();
yValue = inputYTextField.getText();
if(convertPreOperand(xValue) && convertPostOperand(yValue)) {
total = preOperand c postOperand;
outputTextField.setText(Double.toString(total));
}
}
You can use inputField.setText(""); to set the text of any field to nothing.
Your Code sniplet is quite short and I can't figure out, what it is there for, except giving the names of the Textfields?
Anyway, in genereal your program could look like this:
public class calculator implements ActionListener{
JTextField inputXTextField;
JTextField inputYTextField;
JButton bClear=new JButton("clear all");
JPanel panel;
private void init(){
bClear.addActionListener(this);
panel.add(bClear);
panel.add....
}
void actionPerformed(ActionEvent e){
Object obj=e.getSource();
if (obj=bClear){
inputXTextField=new JTextField(...);
or
inputXTextField.setText(""); //just to empty the field
.
.
}
}
JTextField textField1, textField2; //Or as many as you want;
JButton clear;
private void init(){
textField1 = new JTextField(); //Do this for all text fields.
clear=new JButton("C");
clear.addActionListener(this);
//Add controls to the panel/frame
}
void actionPerformed(ActionEvent e){
Object obj=e.getSource();
if (e.getSource==clear){
textField1.setText("");
textField2.setText("");
//... For all the textFields you have
}
}

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.

Accessing Variable within JButton ActionListener

This seems like a very simple problem, but I'm having a lot of trouble figuring out how to deal with it.
Sample Scenario:
final int number = 0;
JFrame frame = new JFrame();
frame.setVisible(true);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setSize(400, 400);
final JTextArea text = new JTextArea();
frame.add(text, BorderLayout.NORTH);
JButton button = new JButton(number + "");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
number++; // Error is on this line
text.setText(number + "");
}});
frame.add(button, BorderLayout.SOUTH);
I really have no idea where to go.
If you declared number as final, you cannot modified its value. You must remove the final modificator.
Then, you can access to that variable via:
public class Scenario {
private int number;
public Scenario() {
JButton button = new JButton(number + "");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Scenario.this.number++;
text.setText(Scenario.this.number + "");
}
});
}
}
The notation "ClassName.this" allow you to access to the object of a class where you are in.
Keep atention in when you use "number" first time, -new JButton(number)-, you can access to number directly, because you are in Scenario scope. But when you use it inside your ActionListener, you are in your ActionListener scope instead of Scenario scope. That is why you cannot see the variable "number" directly inside of your action listener and you have to access to the instance of Scenario where you are in. This can be done by Scenario.this
The fastest solution would be to declare number as static, and reference it using the name of your class.
Alternatively you can make a class that implements ActionListener, and pass number and text into it's constructor.

Categories

Resources