我创建了与记事本相同的菜单,并希望在点击新标签后添加新标签。
所以我创建了New()
函数,返回类型为JPanel
。但它并没有归还我必须工作的对象。
以下是代码:
class Notepad {
public static void main(String []z){
JFrame jf = new JFrame("J-Note");
JTabbedPane jtab = new JTabbedPane();
Menus menus = new Menus(jf, jtab);
jf.add(jtab, BorderLayout.CENTER);
Page pg = new Page();
//pg.getObject(jtab);
jtab.add(pg, "Tag 1");
jf.setSize(700,400);
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
};
class Menus {
JTabbedPane jtab;
JFrame jf;
public Menus() {}
public Menus(JFrame jf, JTabbedPane jtab) {
this.jf = jf;
this.jtab = jtab;
JMenuBar jmenuBar = new JMenuBar();
jf.add(jmenuBar, BorderLayout.NORTH);
////////////////////////////////////////////////////////////////////
/* Menu File: New, Open, Save, Save As, Page setup, Print, Exit. */
JMenuItem New, Open, Save, Save_As, Page_SetUp, Print, Exit;
JMenu jmenuFile = new JMenu("File");
jmenuBar.add(jmenuFile);
New = new JMenuItem("New");
jmenuFile.add(New);
New.setActionCommand("N");
New.addActionListener(new File(jtab));
Open = new JMenuItem("Open");
jmenuFile.add(Open);
Open.setActionCommand("O");
Open.addActionListener(new File());
}
}
class Page extends JPanel {
public String str = "Harshad";
//JTabbedPane jtab;
JPanel jp;
JLabel jl;
public JTextArea jtxtArea;
public Page () {
BorderLayout brLayout = new BorderLayout();
brLayout.setHgap(20);
setLayout(brLayout);
jp = new JPanel();
jp.setOpaque(true);
jp.setBackground(Color.GRAY);
add(jp, BorderLayout.WEST);
jl = new JLabel("1");
jp.add(jl);
jtxtArea = new JTextArea();
//jtxtArea.setOpaque(true);
//jtxtArea.setBackground(Color.GREEN);
add(jtxtArea, BorderLayout.CENTER);
}
}
class File implements ActionListener {
JTabbedPane jtab;
public File() {}
public File(JTabbedPane jtab) {
this.jtab = jtab;
}
public void actionPerformed(ActionEvent e) {
String s = e.getActionCommand();
char ch = s.charAt(0);
//JOptionPane.showMessageDialog(new JFrame(),"You Clicked "+e.getActionCommand());
switch(ch) {
case 'O': Page p = New();
JOptionPane.showMessageDialog(new JFrame(),"Page str: "+p.str);
break;
case 'N': New();
break;
default: JOptionPane.showMessageDialog(new JFrame(),"Operation Not Found.");
break;
}
}
Page New() {
Page pg = new Page();
jtab.add(pg,"Tab 2");
return p;
}
void open() {
try {
FileDialog fd = new FileDialog(new JFrame(), "Select a File to Open");
fd.setVisible(true);
if(fd.getFile()==null)
return;
String fname = fd.getDirectory() + fd.getFile();
FileInputStream fin = new FileInputStream(fname);
int size = fin.available();
byte []data = new byte[size];
fin.read(data);
String str = new String(data);
//JOptionPane.showMessageDialog(new JFrame(),"Panel: "+str);
Page p = New();
p.jtxtArea.setText(str);
}
catch(IOException ioex) {
JOptionPane.showMessageDialog(new JFrame(),"You Clicked "+ioex);
}
}
};