In an attempt to tidy up my (very basic) UI code i have split the button and text field into two seperate classes, with a main to create a frame and run. The button needs to affect the contents of the text field when clicked, so i have used a mouseEvent
. However, i cannot call my textfield's method, as the textfield object is stored in main, so there is no object to use a method for. All methods are public and all attributes are private. All help is apprciated, thank you.
I have tried making the object public statiic
to no avail, i'm not sure if there's something brightly obvious that I am missing here.
Fpor context, the mouseEvent
needs to call the method rename(String)
from the text field object, known as tf, in the class gui1
edit:
(main)
public interface gui1{
public static void main(String[] args) {
textfieldobj tf = new textfieldobj("You should press button 1",100,100, 150,20);
buttonObject b = new buttonObject("new button!");
(in buttonObject class)
public class buttonObject extends JButton implements{
JButton b;
public buttonObject(String text){
JButton b=new JButton(text);
b.setBounds(100,100,60,60);
b.addMouseListener(new MouseListener() {
public void mouseClicked(MouseEvent e) {
tf.setText("You Did It");//problem area
b.setEnabled(false);
(in textfield class)
public void setText(String newtext) {
text = newtext;
super.setText(newtext);
}
textfieldobj
buttonObject
Why are you reinventing all these wheels? JTextField
and JButton
are the classes to represent a text field and a button, you don't need to make do-nothing wrappers around these.
The button needs to affect the contents of the text field when clicked
That's bad design; you don't want your button to need to know about the textfield; if it does, there is no way to use said button for anything, except to modify that exact text field.
so i have used a mouseEvent.
Yup, that's what to use. But, just.. add the listener at the place that knows about both the button and the field. This can be main, but this gets us to another point:
public static void main(...
this is not the place to write code. Make an object, invoke some 'go' method on it, and that's the one line your main should have. You want to get away from static
asap, that's how you do that.
So, something like:
public class MainApp {
// frames, layout managers, whatever you need as well
private final JButton switchTextButton;
private final JTextField textField;
public MainApp() {
this.switchTextButton = new JButton("Switch it up!");
this.textField = new JTextField();
// add a panel, add these gui elements to it, etc.
setupListeners();
}
private void setupListeners() {
// hey, we have both the button and the textfield in scope here.
switchTextButton.addActionListener(evt -> {
textField.setText("Hello!");
});
}
}