I followed a few different tutorials on how to get this working and I just can't seem to get my buttons to update the JLabel. Can you tell me which part is incorrect and lead me in the right path of what to fix. This has been plaguing me for hours.
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.SwingConstants;
public class CoinApp extends JFrame {
private JLabel label;
private JRadioButton rdbtnNewRadioButton_3, rdbtnNewRadioButton, rdbtnNewRadioButton_1, rdbtnNewRadioButton_2;
public CoinApp() {
setBounds(50, 50, 500, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
ButtonGroup buttonGroup = new ButtonGroup();
JPanel panel = new JPanel();
getContentPane().add(panel);
JRadioButton rdbtnNewRadioButton_3 = new JRadioButton("");
buttonGroup.add(rdbtnNewRadioButton_3);
rdbtnNewRadioButton_3.setIcon(new ImageIcon(getClass().getResource("UsCent.png")));
panel.add(rdbtnNewRadioButton_3);
JRadioButton rdbtnNewRadioButton = new JRadioButton("");
buttonGroup.add(rdbtnNewRadioButton);
rdbtnNewRadioButton.setIcon(new ImageIcon(getClass().getResource("UsNickel.png")));
panel.add(rdbtnNewRadioButton);
JRadioButton rdbtnNewRadioButton_1 = new JRadioButton("");
buttonGroup.add(rdbtnNewRadioButton_1);
rdbtnNewRadioButton_1.setIcon(new ImageIcon(getClass().getResource("UsDime.png")));
panel.add(rdbtnNewRadioButton_1);
JRadioButton rdbtnNewRadioButton_2 = new JRadioButton("");
buttonGroup.add(rdbtnNewRadioButton_2);
rdbtnNewRadioButton_2.setVerticalAlignment(SwingConstants.TOP);
rdbtnNewRadioButton_2.setIcon(new ImageIcon(getClass().getResource("UsQuarter.png")));
panel.add(rdbtnNewRadioButton_2);
rdbtnNewRadioButton_3.setSelected(true);
label = new JLabel("CENT w:2.5 d:19.1", JLabel.CENTER);
add(label);
}
**
public void actionPerformed(ActionEvent evt) {
if ( rdbtnNewRadioButton_3.isSelected() ) {
label.setText("CENT w:2.5 d:19.1");
}
else if ( rdbtnNewRadioButton.isSelected() ) {
label.setText("NICKEL w:5.0 d:21.2");
}
else if ( rdbtnNewRadioButton_1.isSelected() ) {
label.setText("DIME w:2.3 d:17.9");
}
else if ( rdbtnNewRadioButton_2.isSelected() ) {
label.setText("QUARTER w:5.7 d:24.3");
}
} // end actionPerformed()
**
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
CoinApp frame = new CoinApp();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
for( Coin el : Coin.values())
{
System.out.println(el);
}
}
}
Start by taking a look at How to Write an Action Listeners
In order for your buttons to provide notification, you must register an ActionListener within them.
In order for your buttons to call your actionPerformed method however, you need to implement the ActionListener interface...
public class CoinApp extends JFrame implements ActionListener {
//...
#Override
public void actionPerformed(ActionEvent evt) {
You should add the #Override annotation to methods you believe you are overriding from parent classes or interfaces, it will give you a compiler warning if you've done something wrong, like misspelt it for example.
Now you can register the ActionListener with your buttons...
rdbtnNewRadioButton_3.addActioinListener(this);
Updated...
Also, beware, you are shadowing your variables...
What I mean by this is, you are declaring your variables as instance/class variables...
private JRadioButton rdbtnNewRadioButton_3, rdbtnNewRadioButton, rdbtnNewRadioButton_1, rdbtnNewRadioButton_2;
Which is good, but in your constructor, you are re-declaring them...
public CoinApp() {
//...
JRadioButton rdbtnNewRadioButton_3 = new JRadioButton("");
This means when you go to reference rdbtnNewRadioButton_3 somewhere else in your program, it will be null.
You should be using something like...
public CoinApp() {
//...
rdbtnNewRadioButton_3 = new JRadioButton("");
You need to hook up your event handler method (actionPerformed) to each of the radio buttons. To do this you need to register an ActionListener to each radio button. The most convenient way for you to do this is to have your main class implement the ActionListener interface, and then call addActionListener on each radio button a reference to this
Also note that your event handler method will currently cause you problems because you are never actually setting the class level members (fields) (rdbtnNewRadioButton_3 etc). You are actually creating new local variables in your constructor with the same name that 'hide' the class level fields, which then become inaccessible when they fall out of scope, leaving the class level variables null.
Your constructor code should look like this:
rdbtnNewRadioButton_3 = new JRadioButton("");
Instead of
JRadioButton rdbtnNewRadioButton_3 = new JRadioButton("");
Good luck!
Related
Hey I am a beginner and I have wrote the following code in java, but I can´t click on the JButtons. The program includes three clases - Main, Frame and Actionhandler. My goal was to create a Frame with two buttons: Singleplayer and Mulitplayer. I wanted to test if they work, but I can´t click them. Can anyone help me please?
This is the Main class:
public class Main {
public static void main (String [] args) {
new Frame ();
}
}
This is the Frame class:
import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
public class Frame extends JFrame {
public static Object multi;
public static Object single;
Frame() {
// Frame
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setExtendedState(JFrame.MAXIMIZED_BOTH);
this.setLocationRelativeTo(null);
//Layout in Frame
this.setLayout(new GridLayout(2,1));
this.setVisible(true);
// Buttons in Main Menu
JButton single = new JButton("Singleplayer");
JButton multi = new JButton("Multiplayer");
// specify single button
single.setBounds(200,100,250,80);
single.setForeground(Color.GREEN);
single.setBackground(Color.LIGHT_GRAY);
single.setOpaque(true);
single.setBorder(BorderFactory.createLineBorder(Color.BLACK));
single.setFont(new Font("Comic Sans",Font.BOLD,25));
single.addActionListener(new ActionHandler());
//specify multi button
multi.setBounds(800,100,250,80);
multi.setForeground(Color.GREEN);
multi.setBackground(Color.GRAY);
multi.setOpaque(true);
multi.setFont(new Font("Comic Sans",Font.BOLD,25));
multi.setBorder(BorderFactory.createLineBorder(Color.BLACK));
multi.addActionListener(new ActionHandler());
// add Buttons to Frame
this.add(single);
this.add(multi);
}
}
This is the ActionHandler class:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ActionHandler implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == Frame.multi) {
System.out.println("You have clicked on Singleplayer");
if(e.getSource() == Frame.single) {
System.out.println("You have clicked on Multiplayer");
}
}};
}
You can click on the buttons fine. They just won't do anything because of how you've wired the program:
public class Frame extends JFrame {
public static Object multi; // this is null
public static Object single; // and so is this
Frame() {
// Frame
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setExtendedState(JFrame.MAXIMIZED_BOTH);
this.setLocationRelativeTo(null);
//Layout in Frame
this.setLayout(new GridLayout(2,1));
this.setVisible(true);
// Buttons in Main Menu
JButton single = new JButton("Singleplayer"); // this is a new *local* variable
JButton multi = new JButton("Multiplayer"); // and so is this:
You are initializing local variables that have the same name as your static class fields, and you're leaving the same static class fields null, a situation known as "variable shadowing", and so in your listeners, you check if the source is the null static field. Which won't work.
So in your listener:
public void actionPerformed(ActionEvent e) {
if(e.getSource() == Frame.multi) {
You're testing if a null variable is the button that was pressed, and this will not work.
One simple solution is to not re-declare the multi and single variables, to assign your JButtons to these public static fields by changing this:
JButton single = new JButton("Singleplayer");
JButton multi = new JButton("Multiplayer");
to this:
single = new JButton("Singleplayer");
multi = new JButton("Multiplayer");
This would sort-of work. You'd have do do some casting to add these JButton objects to the container since the variables are Object, not JButton. But this would be a bad idea because you'd be throwing out the OOPs baby with the bathwater, discarding encapsulation completely.
Best not to throw out OOPs rules with public static (non-constant) fields and instead work with them. Better to use constant Strings to be passed into your JButtons and then test for them using the ActionEvent's actionCommand property:
public class Frame extends JFrame {
public static String SINGLE_PLAYER = "Single Player";
public static String MULTI_PLAYER = "Multi Player";
Frame() {
// Frame
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setExtendedState(JFrame.MAXIMIZED_BOTH);
this.setLocationRelativeTo(null);
//Layout in Frame
this.setLayout(new GridLayout(2,1));
this.setVisible(true);
// Buttons in Main Menu
JButton single = new JButton(SINGLE_PLAYER); // this is a new *local* variable
JButton multi = new JButton(MULTI_PLAYER); // and so is this:
in the listener:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ActionHandler implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand().equals(Frame.MULTI_PLAYER)) {
System.out.println("You have clicked on Multi Player");
} else {
// ...
}
}};
}
Other problems with your code include:
Don't name your class Frame since this clashes with the name of class in the core Java library, java.awt.Frame. Name it something unique to avoid confusion
Avoid setting bounds, sizes and such. Let the GUI, its layout managers and component preferred sizes do the sizing by calling pack() on the top-level window (JFrame, JDialog,...) after adding components
Call .setVisible(true) on the top-level window after adding all components.
This looks like it will display as a sub-window or dialog window, and you might want to show this portion of the GUI in a modal JDialog, not in a JFrame.
my question is: how do I get the object of my CustomPanel, so that I am able to access its fields (because in my real programm I have some more fields in there) and also am able to delete it from my ArrayList?
I don't know how I have to implement an ActionListener in the Class Window, to somehow get the Object in my Arraylist, which containes the button that got pressed.
Also I am wondering if I am somehow able to implement an ActionListener in the Class CustomPanel which can influence the behaviour of the Object which is an instance of my Class Window.
I have kind of the following code:
public class Window extends JFrame{
ArrayList<CustomPanel> aLCustomPanel = new ArrayList();
JPanel jp = new JPanel();
public Window() {
for(int i=0;i<5;i++){
aLCustomPanel.add(new CustomPanel());
//here I could put the code from the 1 edit - see below
jp.add(aLCustomPanel.get(i));
}
this.add(jp);
}
public static void main(String args[]){
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Window().setVisible(true);
}
});
}
}
class CustomPanel extends JPanel {
private JButton button;
public CustomPanel(){
button = new JButton("button");
this.add(button);
}
public JButton getButton(){
return this.button;
}
}
my Code is much longer and weirder, so I tried to extract the (for this question) importing things.
Thanks for any help in advance!
edit:
for example: I would like to delete the object from the ArrayList, of which the button got pressed.
//imagine this comment in above code
aLCustomPanel.get(aLCustomPanel.size()-1).getButton().addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
button_IwantToDeleteYou(e); //here I want to remove the panel, containing the button that got pressed from the above ArrayList, which is located in Class Window
}
});
edit2:
added a missing bracket and fixed some mistakes, code should be ok now.
Your code contained a few "gaps", i.e. missing code, which I filled in, as follows:
Added calls to [JFrame] methods setDefaultCloseOperation() and pack() and setLocationByPlatform(). I suggest you refer to the javadoc for those methods in order to understand what they do.
I set a layout manager for jp class member variable in your Window class.
Yes, you need to register an ActionListener with the JButton in class CustomPanel and that listener should reside in your Window class - the one that extends JFrame.
Here is my rewrite of your code. Note that I changed the name of class Window to CusPanel so as to distinguish between your class and java.awt.Window class. Not that it makes a difference, I just prefer not to use names of classes from the JDK.
import java.awt.Container;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.WindowConstants;
public class CusPanel extends JFrame implements ActionListener {
private static final int COUNT = 5;
private ArrayList<CustomPanel> aLCustomPanel = new ArrayList<>();
private JPanel jp = new JPanel(new GridLayout(0, COUNT));
public CusPanel() {
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
for (int i = 0; i < COUNT; i++) {
aLCustomPanel.add(new CustomPanel(this));
// here I could put the code from the 1 edit - see below
jp.add(aLCustomPanel.get(i));
}
this.add(jp);
pack();
setLocationByPlatform(true);
}
public void actionPerformed(ActionEvent actionEvent) {
Object source = actionEvent.getSource();
if (source instanceof JButton) {
JButton button = (JButton) source;
Container parent = button.getParent();
jp.remove(parent);
jp.invalidate();
jp.repaint();
pack();
// aLCustomPanel.remove(parent); <- optional
}
}
public static void main(String args[]) {
EventQueue.invokeLater(new Runnable() {
public void run() {
new CusPanel().setVisible(true);
}
});
}
}
class CustomPanel extends JPanel {
private JButton button;
public CustomPanel(ActionListener parent) {
button = new JButton("button");
button.addActionListener(parent);
this.add(button);
}
public JButton getButton() {
return this.button;
}
}
Note that after removing a CustomPanel, the GUI components need to be laid out again and the JFrame should also be resized accordingly. Hence in the actionPerformed() method, I call invalidate(), then repaint() and then pack(). I also think that if you remove a CustomPanel from the GUI, you should also remove it from the ArrayList, but hey, I still don't understand why you want to do this although I obviously don't know the whole story behind you wanting to do this in the first place.
Of-course, since each button (and each CustomPanel) looks exactly the same, you can't really know which button was removed. Again, I assume you see the big picture whereas I don't.
This question already has answers here:
Why it says that "Cannot refer to a non-final variable i inside an inner class defined in a different method"? [duplicate]
(5 answers)
Closed 4 years ago.
I have a problem with ItemListeners. Basially, I want to query the database to get some data and put them into Objects following the DAO Pattern. The thing is, when I put an ArrayList of CheakBoxes, I can't figure out how to add Listeners to them.
I have tried to add ItemListener before putting them in their container through loop. I have also tried to add ItemListeners after adding them to the container but also with no avail.
I have tested my script for 1 chekBox only, it works. When it comes to the ArrayList, i have this error Message: Cannot refer to the non-final local variable jCheckBox defined in an enclosing scope
The following code is another test, just to see if something was incorrect on my program, but it seems to give me same Issue when adding the listener to the ArrayList objects
package test;
import java.awt.Dimension;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.ArrayList;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Test {
private static ArrayList<JCheckBox> jCheckBoxs;
private static JFrame jFrame=new JFrame();
public static void main(String[] args) {
init();
}
private static void init() {
jFrame.setSize(new Dimension(400,400));
jFrame.setTitle("test");
JPanel jp=new JPanel();
jCheckBoxs=new ArrayList<JCheckBox>();
addArray("A");
addArray("B");
addArray("C");
jp.add(jCheckBoxs.get(0));
jp.add(jCheckBoxs.get(1));
jp.add(jCheckBoxs.get(2));
jFrame.getContentPane().add(jp);
jFrame.setVisible(true);
}
private static void addArray(String msg) {
JCheckBox jCheckBox=new JCheckBox();
jCheckBox.setText(msg);
jCheckBox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
System.out.println(jCheckBox.getName());
}
});
}
}
If you're going to refer to a local variable within an anonymous inner class, as you're doing, you need to make the local variable final, as has been discussed in many similar questions
You're not adding the JCheckBoxes to the ArrayList or the GUI, so your code is meaningless
Don't use absolute ArrayList indices, since you're asking for exceptions. In your code above the ArrayList size is 0, so this code will result in an index out of bounds exception
Most all of that code should not be static. Use instance fields and instance methods. Only the main method should be static.
For example:
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
#SuppressWarnings("serial")
public class MultCheckBoxes extends JPanel {
private List<JCheckBox> checkBoxes = new ArrayList<>();
private JTextArea showSelectionTArea = new JTextArea(25, 50);
private JPanel checkBoxPanel = new JPanel(new GridLayout(0, 1));
private ItemListener myItemListener = new MyItemListener();
public MultCheckBoxes() {
showSelectionTArea.setFocusable(false); // so user can't enter text
JPanel wrapperPanel = new JPanel(new BorderLayout());
wrapperPanel.add(checkBoxPanel, BorderLayout.PAGE_START);
JPanel bottomPanel = new JPanel();
bottomPanel.add(new JButton(new GetAllStatesAction()));
setLayout(new BorderLayout());
add(new JScrollPane(showSelectionTArea));
add(wrapperPanel, BorderLayout.LINE_END);
add(bottomPanel, BorderLayout.PAGE_END);
}
public void addCheckBox(String name) {
JCheckBox checkBox = new JCheckBox(name);
checkBox.addItemListener(myItemListener);
checkBoxes.add(checkBox);
checkBoxPanel.add(checkBox);
revalidate();
repaint();
}
private class MyItemListener implements ItemListener {
#Override
public void itemStateChanged(ItemEvent itemEvt) {
// The ItemEvent object will give us the JCheckBox that was changed
JCheckBox checkBox = (JCheckBox) itemEvt.getSource();
// get its text and its state
String text = checkBox.getText();
String select = itemEvt.getStateChange() == ItemEvent.SELECTED ? "selected" : "unselected";
// display this in the JTextArea
showSelectionTArea.append(text + ": " + select + "\n");
}
}
private class GetAllStatesAction extends AbstractAction {
public GetAllStatesAction() {
super("Get All CheckBox States"); // button's text
putValue(MNEMONIC_KEY, KeyEvent.VK_A); // mnemonic key
}
#Override
public void actionPerformed(ActionEvent e) {
showSelectionTArea.append("\n");
showSelectionTArea.append("All CheckBox States: \n");
for (JCheckBox jCheckBox : checkBoxes) {
String text = jCheckBox.getText();
String select = jCheckBox.isSelected() ? "selected" : "unselected";
showSelectionTArea.append(text + ": " + select + "\n");
}
showSelectionTArea.append("\n");
}
}
private static void createAndShowGui() {
MultCheckBoxes mainPanel = new MultCheckBoxes();
mainPanel.addCheckBox("Box A");
mainPanel.addCheckBox("Box B");
mainPanel.addCheckBox("Box C");
mainPanel.addCheckBox("Box D");
mainPanel.addCheckBox("Box E");
JFrame frame = new JFrame("MultCheckBoxes");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
I'm trying to learn methods and classes
I created a small tool where class Main is to run it, class SWing to create the frame, class Verb to create a button to add to Swing and as well to do the action performed, my question here is that, how can I make the action performed really works via verb Class.
let's say I want to get text from textfield and to concatenate it with textfiled1 and to show the answer on textfield2.
here is my code
1- my main class
package Abo;
public class Main {
public static void main (String[]args){
Swing runFrame = new Swing(); // creating a variable for class Swing
runFrame.Run(); // to run the Swing
}
}
2- my Swing
package Abo;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JTextField;
public class Swing extends JFrame {
public JTextField textField;
public JTextField textField_1;
public JTextField textField_2;
public Swing() {
// creating the frame
getContentPane().setLayout(new GridLayout(2,2,5,5));
textField = new JTextField();
getContentPane().add(textField);
textField.setColumns(10);
textField_1 = new JTextField();
getContentPane().add(textField_1);
textField_1.setColumns(10);
textField_2 = new JTextField();
getContentPane().add(textField_2);
textField_2.setColumns(10);
textField_2.setEditable(false);
// adding the btn from another class
Verb addBTN = new Verb();
getContentPane().add(addBTN.BTN());
}
public void Run(){
// setting the frame
Swing frame = new Swing();
frame.setVisible(true);
frame.setSize(300,400);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
3- verb class
package Abo;
import javax.swing.JButton;
public class Verb extends JButton {
// creating the btn constructor
public JButton BTN(){
JButton btn1 = new JButton("First Button");
return btn1;
}
}
thank you in advance
Well in your verb class just add this to btn1
btn1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
//Execute when button is pressed
}
});
I noticed that Verb is extending JButton, but you are opting to write a method that returns a JButton inside of it.
If you want Verb to be a JButton that is always called "First Button", then I would instead modify Verb's constructor.
One way to do that would be like this:
package Abo;
import javax.swing.JButton;
public class Verb extends JButton {
public Verb() {
super("First Button"); //super calls the constructor of the parent of this class, in this case that is JButton
}
}
Now since you are extending JButton, whenever you make a Verb, it will also be a JButton with the text "First Button"
Now you can add your ActionListener to Verb directly.
By doing:
Verb addBTN = new Verb();
addBTN.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textField_2.setText(textField.getText() + textField_1.getText());
}
});
However, in order to access your text fields inside of the actionlistener, you will need to make them final.
final textField = new JTextField(); // do this for all text fields
Also, just as good practice, unless you are planning to add more functionality than the default constructor to Verb, I would just use a JButton instead of making your own class.
I'm a C programmer who was handed a last minute Java GUI task. Given that I am not a GUI or Java person, I have created two objects:
1 is a text box, which I'm hoping to be assigned the results of the 2nd object.
2 is a combo box. When user selects from the combo box, I wish for that value to be populated into my first object (textfield). Here is my actionListener():
class Foo {
// declared instance variable
private String theValue;
// created textField, and JComboBox thingies
listBox.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
// this line produces the reported error
//textField.setText( (String)(((JComboBox)e.getSource()).getSelectedItem()) );
// this line works, but then get below error when try to assign theValue outside method
theValue = ((JComboBox)e.getSource()).getSelectedItem();
}
});
...
textField.setValue(theValue); // errors out
and get the following (apparently well know Java error): Cannot refer to a non-final variable
textfield inside an inner class defined in a different method
The commented line produced the same results. I was hoping to be able to assign theValue as the value of my text field, but can not obviously declare I within the listener, as then there is the scope problem.
Any assistance is greatly appreciated :-)
Either make the JTextField final or make it an instance field within the class.
final JTextField textField = ...
or
public class ... {
private JTextField textField;
public ...() { = new JTextField(...);
You can do this for you other variables to. Typically, unless you have some reason to do otherwise, I would suggest using instance fields. Take a look at Understanding Class Members for some more details...
You can think of instance fields like "private" variables in C, those declared within the C file itself, where the can not be referenced externally to the file they are declared in (sorry VERY long time since I've done C so that might not be entirely correct)
Updated
Firstly, GUI's tend to be event driven, that is, they don't operate in a linear/procedural fashion. You set up a bunch of callbacks and wait for something to trigger them. When the callback is triggered, you take appropriate action...
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JTextField textField;
private JComboBox comboBox;
private String theValue;
public TestPane() {
textField = new JTextField(10);
comboBox = new JComboBox(new String[]{"Banana", "Apple", "Grapes", "Strawberries"});
comboBox.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
theValue = (String)comboBox.getSelectedItem();
textField.setText(theValue);
}
});
comboBox.setSelectedItem(null);
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
add(textField, gbc);
add(comboBox, gbc);
}
}
}
In the example, the ActionListener assigned to the JComboBox is not called immediately, meaning that the remaining code below the assignment will run immediately and before the ActionListener has any chance of been called.
Think of it like a function pointer or callback. You can pass it to another function, but you don't know when it might be called...
When the state of the JComboBox changes and triggers and action event, the ActionListeners actionPeformed method is called, at which time you can obtain the current value and apply it to the text field and assign it to your variable...or what ever else you need to do...
Notice, I attached the ActionListener and the called comboBox.setSelectedItem(null), this will actually cause the ActionListener to be notified...tricky ;)