当我使用intellij设计Java表单时,它只声明像
这样的私有组件Private JPanel myPanel;
但是如何从我的类源文件中访问该对象。例如。当我想将一个JButton添加到myPanel?
我知道我可以为myPanel编写一个getter但是如何访问呢?
答案 0 :(得分:0)
让我通过更改按钮文字解释我的解决方案。
示例:在点击时更改GUI设计器创建按钮的按钮文本:
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");
}
}
}
}