我在该行收到错误:jFrame无法解析
jFrame.setTitle(titleName.getText());
public void createOption(){
Option = new JPanel();
Option.setLayout( null );
JLabel TitleLabel = new JLabel("Change the company name");
TitleLabel.setBounds(140, 15, 200, 20);
Option.add(TitleLabel);
titleName = new JTextField();
titleName.setBounds(90,40,260,20);
Option.add(titleName);
JButton Change = new JButton("Change New Name");
Change.setBounds(90,80,150,20);
Change.addActionListener(this);
Change.setBackground(Color.white);
Option.add(Change);
JButton Exit = new JButton("Exit");
Exit.setBounds(270,80,80,20);
Exit.addActionListener(this);
Exit.setBackground(Color.white);
Option.add(Exit);
Change.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
jFrame.setTitle(titleName.getText());
}
});
}
答案 0 :(得分:6)
您必须拥有对JFrame的引用。假设按钮和textBox用于控件的名称,您可以执行
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
jFrame.setTitle(textBox.getText());
}
});
编辑:
这是一个完整的例子
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class JFrameExample {
public static void main(String[] args) {
final JFrame jFrame = new JFrame("This is a test");
jFrame.setSize(400, 150);
Container content = jFrame.getContentPane();
content.setBackground(Color.white);
content.setLayout(new FlowLayout());
final JTextField jTextField = new JTextField("TestTitle");
content.add(jTextField);
final JButton button = new JButton("Change");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
jFrame.setTitle(jTextField.getText());
}
});
content.add(button);
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jFrame.setVisible(true);
}