Java 按钮中的全局变量
如何使退出按钮成为全局变量?我正在为我的老师制作一个用于评分的gui,我必须使它成为“全局”图形,以便jframe可以访问它。代码如下:Java 按钮中的全局变量,java,Java,如何使退出按钮成为全局变量?我正在为我的老师制作一个用于评分的gui,我必须使它成为“全局”图形,以便jframe可以访问它。代码如下: import javax.swing.*; import java.awt.event.ActionListener; import java.awt.event.*; import java.awt.*; public class StudentGUI extends JFrame implements ActionListener { pub
import javax.swing.*;
import java.awt.event.ActionListener;
import java.awt.event.*;
import java.awt.*;
public class StudentGUI extends JFrame implements ActionListener {
public StudentGUI()
{
super("StudentGUI Frame");
//TopPanel
TopPanel tp;
tp=new TopPanel();
Dimension d = new Dimension(800,600);
tp.setPreferredSize(d);
this.add (tp, BorderLayout.NORTH);
tp.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(800,600);
setBackground(Color.PINK);
tp.setVisible(true);
//TopPanel End
//BottomPanel
BottomPanel bp;
bp=new BottomPanel();
this.add (bp, BorderLayout.SOUTH);
tp.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(800,600);
exitBtn.addActionListener(this);
//BottomPanel End
//MiddlePanel
MiddlePanel mp;
mp=new MiddlePanel();
this.add (mp, BorderLayout.CENTER);
mp.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(800,600);
//MiddlePanel End
this.setVisible(true);
}
public void actionPerformed(ActionEvent e){
int selectedOption = JOptionPane.showConfirmDialog(null,
"Do you want to close the window?",
"Choose",
JOptionPane.YES_NO_OPTION);
if (selectedOption == JOptionPane.YES_OPTION) {
System.exit(0);
//ExitBtn.addActionListener(this);
}
}
public static void main(String[] args)
{
new StudentGUI();
}
}
现在这就是框架。下面是使退出按钮执行操作时出现问题的面板
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.*;
public class BottomPanel extends JPanel {
public String findbtn="";
public String insertBtn="";
public String updateBtn="";
public String deleteBtn="";
Button exitBtn;
public BottomPanel() {
JButton findbtn;
findbtn=new JButton("Find");
add(findbtn);
JButton insertBtn;
insertBtn=new JButton("Insert");
add(insertBtn);
JButton updateBtn;
updateBtn=new JButton("Update");
add(updateBtn);
JButton deleteBtn;
deleteBtn=new JButton("Delete");
add(deleteBtn);
JButton exitBtn;
exitBtn=new JButton("Exit");
add(exitBtn);
}
}
救命啊 如果您已经可以在GUI中看到按钮,则不必从主框架访问该按钮,因此您所要做的就是在
按钮面板
内的退出按钮中添加一个操作侦听器
,您的问题将得到解决
例如:
exitBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(1);
}
});
为什么要从frame类添加它。您只能在panel类中执行此操作。但是,如果你想从frame类中学习,请记住 BottomPanel类中的exitbtn是包私有的,因此只有当框架类在同一个包中时才能访问它。下一步就是添加操作侦听器write的地方
bp.extBtn.addActionListener(this)
一直说包bp.exitBtn.addActionListener(这个);英国石油公司不存在,救命啊?