Question

When I design a Java Form with intellij it only declares private components like

Private JPanel myPanel;

But how can I access this object from within my class sourcefile. E.g. when I want to add a JButton to myPanel?

i know I can write a getter for myPanel but how do I access it then?

Was it helpful?

Solution

Let me explain my solution with the change of a button text.

  1. Create the button in intellij GUI Designer
  2. Add a getter method to it (go to source, write getter manually or let intellij do it for you)
  3. Now you can use the getter method to access the objects methods.

Example: Change button text of a GUI-designer-created button on click:

import javax.swing.*;
import java.awt.event.*;

public class TestForm {

private JButton button1;
private JPanel panel1;

public TestForm() {
    getButton1().addActionListener(new clickListener());
}

public JButton getButton1() {
    return button1;
}


public static void main(String[] args) {
    JFrame frame = new JFrame("TestForm");
    frame.setContentPane(new TestForm().panel1);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
    frame.setVisible(true);
}

public void changeTextOnButton(){
    getButton1().setText("gwerz");
}

public class clickListener implements ActionListener{
    public void actionPerformed(ActionEvent e){
        if (getButton1().getText().equals("Button")){
        getButton1().setText("Dgsdg");
    }
    else {
        getButton1().setText("Button");
    }
}
}


}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top