我正在尝试编写一个可以复制/粘贴并保存到txt文件的剪贴板程序。 当程序有效时,我试图将按钮更改为带有MenuItems的菜单, 但是,我无法弄清楚如何正确使用菜单项,因为我无法将其添加到面板。
请注意我使用的是AWT而不是Swing,所以没有JPanel / JFrame等。 任何提示/帮助都表示赞赏。
这是我的代码,并尝试将其更改为菜单,请让我知道我做错了什么:
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class CheesyWP extends Frame implements ActionListener {
/**
* @param args
*/
//new panel for menu
Panel north;
//original
Panel center;
Panel south;
Button save;
Button load;
Button clip;
Button finish;
Menu mn;
MenuItem mSave;
MenuItem mLoad;
MenuItem mClip;
MenuItem mFinish;
TextArea ta;
public static void main(String[] args) {
// TODO Auto-generated method stub
CheesyWP cwp = new CheesyWP();
cwp.doIt();
}
public void doIt() {
center = new Panel();
south = new Panel();
clip = new Button("Open Clipboard");
save = new Button("Save");
load = new Button("Load");
finish = new Button("Finish");
//menu items
north = new Panel();
mn = new Menu();
mSave = new MenuItem("Save");
mLoad = new MenuItem("Load");
mClip = new MenuItem("Open Clipboard");
mFinish = new MenuItem("Finish");
mn.add(mSave);
mn.add(mLoad);
mn.add(mClip);
mn.add(mFinish);
mSave.addActionListener(this);
mLoad.addActionListener(this);
mClip.addActionListener(this);
mFinish.addActionListener(this);
//north.add(mn); <-------//PROBLEM HERE
clip.addActionListener(this);
save.addActionListener(this);
load.addActionListener(this);
finish.addActionListener(this);
ta = new TextArea(20, 80);
center.add(ta);
south.add(load);
south.add(save);
south.add(clip);
south.add(finish);
this.add(center, BorderLayout.CENTER);
this.add(south, BorderLayout.SOUTH);
this.setSize(600, 300);
this.setVisible(true);
}
public void actionPerformed(ActionEvent ae) {
if (ae.getSource() == save) {
try {
File junk = new File("junk.txt");
FileWriter fw = new FileWriter(junk);
fw.write(ta.getText()); // write whole TextArea contents
fw.close();
} catch (IOException ioe) {
}
}// ends if
if (ae.getSource() == load) {
String temp = "";
try {
File junk = new File("junk.txt");
FileReader fr = new FileReader(junk);
BufferedReader br = new BufferedReader(fr);
while ((temp = br.readLine()) != null) {
ta.append(temp + "\n");
}
br.close();
} catch (FileNotFoundException fnfe) {
} catch (IOException ioe) {
}
}
if (ae.getSource() == finish) {
System.exit(0);
}
if(ae.getSource()==clip){
new ClipBoard();
}
}
class ClipBoard extends Frame {
public ClipBoard() { // a constructor
this.setTitle("Clipboard");
this.setLayout(new FlowLayout());
this.add(new TextArea(10, 50));
this.setSize(400, 160);
this.setVisible(true);
}
}
}
答案 0 :(得分:0)
this.validate();
Swing组件的默认状态为无效,除非经过验证(通过在组件本身或其中一个父容器上调用.validate()方法),否则不会将其绘制到屏幕上。
答案 1 :(得分:0)
只需更改此
Panel north;
到此
MenuBar north;
因为使用awt库,你不能将菜单添加到Panel,但是你可以将菜单添加到MenuBar