当我点击搜索按钮时,我的代码复制了主屏幕的创建。搜索事件应该只打开一个带有文本框的新框架以输入查询。另一个框架的创建会导致这种重复,还是这种错误?我尝试使用mainFrame上传searchPane的日期(代码中的p1),但是当我这样做时,这解决了我的窗口问题,但搜索窗口上的defaultCloseOperation()导致整个程序关闭 - 我怎么能解决这个问题?
提前致谢
SearchScreen
import java.awt.Color;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class SearchScreen extends MainScreen{
JButton btsearch;
JLabel lbsearch;
protected JTextField txtsearch;
JPanel p1;
protected JFrame searchFrame = new JFrame();
public SearchScreen(){
//Button Creation
btsearch= new JButton("Search");
//Label Creation
lbsearch= new JLabel("Type Keywords in english to be searched below:");
//TextBox
txtsearch= new JTextField();
//Pane Creation
p1=new JPanel();
p1.setBackground(Color.gray);
//Pane Components
p1.add(lbsearch);
p1.add(txtsearch);
p1.add(btsearch);
//JFrame Layout Setup
p1.setLayout(new GridLayout(3,3));
btsearch.setEnabled(true);
//Adding JPaneel
searchFrame.add(p1);
//JFrame Setup
searchFrame.setTitle("SHST");
searchFrame.setSize(400, 400);
searchFrame.setVisible(true);
searchFrame.setDefaultCloseOperation(1);
}
}
MainScreen
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
public class MainScreen implements ActionListener {
JMenuBar bar;
JMenu file, register;
JMenuItem close, search;
JPanel entrance = new JPanel();
JFrame mainFrame = new JFrame();
public MainScreen()
{
bar= new JMenuBar();
file= new JMenu("File");
register= new JMenu("Search");
close= new JMenuItem("Close");
close.addActionListener(this);
search= new JMenuItem("Request Query");
search.addActionListener(this);
//mainFrame Setup
bar.add(file);
bar.add(register);
file.add(close);
register.add(search);
mainFrame.setExtendedState(mainFrame.getExtendedState() | mainFrame.MAXIMIZED_BOTH);
mainFrame.setTitle("SHST");
mainFrame.setJMenuBar(bar);
mainFrame.setDefaultCloseOperation(0);
mainFrame.setVisible(true);
WindowListener J=new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
};
mainFrame.addWindowListener(J);
}
public void actionPerformed(ActionEvent e){
if(e.getSource()==close){
System.exit(0);
}
if(e.getSource()==search){
SearchScreen s= new SearchScreen();
}
public static void main (String[] args){
MainScreen m= new MainScreen();
}
}
答案 0 :(得分:1)
您的问题在这里
if(e.getSource()==search){
SearchScreen s= new SearchScreen();
}
使用继承实现是危险的,SearchScreen是MainScreen
,然后始终调用此类的构造函数。