我是stackoverflow和学习Java的新手。我正在为我在大学的一门课程创建一个应用程序,我们必须创建一个带有菜单栏和工具栏的文本编辑器。我已经能够让菜单栏工作,但工具栏没有显示,即使它没有破坏代码。有谁知道这是怎么回事?
import com.sun.deploy.ui.AboutDialog;
import com.sun.org.apache.bcel.internal.generic.RETURN;
import javafx.scene.control.ToolBar;
import javax.swing.JToolBar;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.print.PageFormat;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import javax.swing.JOptionPane;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.event.UndoableEditEvent;
import javax.swing.event.UndoableEditListener;
import javax.swing.undo.CannotUndoException;
import javax.swing.undo.UndoManager;
@SuppressWarnings("serial")
public class DoesThisWork extends JFrame implements ActionListener {
public static void main(String[] args) {
new DoesThisWork();
}
//============================================
// FIELDS
//============================================
// Menus
private JMenu fileMenu;
private JMenu editMenu;
private JMenu formatMenu;
private JMenu helpMenu;
private JMenuItem newFile, openFile, saveFile, saveAsFile, pageSetup, printFile, exit;
private JMenuItem undoEdit, redoEdit, selectAll, copy, paste, cut;
private JMenu fontColor, fontSize;
private JMenuItem about;
private JMenuItem subColorRed, subColorBlue, subColorGreen, subColorBlack;
private JMenuItem subTimes, subArial, subCourier, subVerdana;
//Toolbar Buttons
private JButton red;
private JButton blue;
private JButton green;
private JButton black;
// private JButton newFile, openFile, saveFile, saveAsFile, pageSetup, printFile, exit;
// private JMenuItem undoEdit, redoEdit, selectAll, copy, paste, cut;
// private JMenu fontColor, fontSize;
// private JMenuItem about;
// private JMenuItem subColorRed, subColorBlue, subColorGreen, subColorBlack;
// private JMenuItem sub8, sub10, sub12, sub50;
// Window
private JFrame editorWindow;
// Text Area
private Border textBorder;
private JScrollPane scroll;
private JTextArea textArea;
private Font textFont;
// Window
private JFrame window;
// Printing
private PrinterJob job;
public PageFormat format;
// Is File Saved/Opened
private boolean opened = false;
private boolean saved = false;
// Record Open File for quick saving
private File openedFile;
// Undo manager for managing the storage of the undos
// so that the can be redone if requested
private UndoManager undo;
//Toolbar
private JToolBar toolBar;
//============================================
// CONSTRUCTOR
//============================================
public DoesThisWork() {
super("Text Editor");
// Create Menus
fileMenu();
editMenu();
formatMenu();
helpMenu();
// Create Text Area
createTextArea();
// Create Undo Manager for managing undo/redo commands
undoMan();
// Create Window
createEditorWindow();
// Create Toolbar
createToolBar();
}
private JFrame createEditorWindow() {
editorWindow = new JFrame("Text Editor");
editorWindow.setVisible(true);
editorWindow.setExtendedState(Frame.MAXIMIZED_BOTH);
editorWindow.setDefaultCloseOperation(EXIT_ON_CLOSE);
// Create Menu Bar
editorWindow.setJMenuBar(createMenuBar());
editorWindow.add(scroll, BorderLayout.CENTER);
editorWindow.pack();
// Centers application on screen
editorWindow.setLocationRelativeTo(null);
// Create ToolBar
//editorWindow.add(toolBar, BorderLayout.NORTH);
return editorWindow;
}
private JTextArea createTextArea() {
//textBorder = BorderFactory.createBevelBorder(0, Color.BLACK, Color.BLACK);
textArea = new JTextArea(30, 50);
textArea.setEditable(true);
textArea.setBorder(BorderFactory.createCompoundBorder(textBorder, BorderFactory.createEmptyBorder(2, 5, 0, 0)));
textFont = new Font("Verdana", 0, 14);
textArea.setFont(textFont);
scroll = new JScrollPane(textArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
return textArea;
}
private JMenuBar createMenuBar() {
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
menuBar.add(fileMenu);
menuBar.add(editMenu);
menuBar.add(formatMenu);
menuBar.add(helpMenu);
return menuBar;
}
private JToolBar createToolBar(){
toolBar = new JToolBar();
toolBar.setFloatable(true);
red = new JButton("Red");
red.setToolTipText("Click here to change font color to Red");
blue = new JButton("Blue");
blue.setToolTipText("Click here to change font color to Blue");
green = new JButton("Green");
green.setToolTipText("Click here to change font color to Green");
black = new JButton("Black");
black.setToolTipText("Click here to change font color to Black");
//add(toolBar, BorderLayout.SOUTH);
// Toolbar Color Buttons
toolBar.add(red);
toolBar.add(blue);
toolBar.add(green);
toolBar.add(black);
add(toolBar, BorderLayout.WEST);
//ToolBar tb = new ToolBar();
toolBar.setVisible(true);
return toolBar;
}
private UndoManager undoMan() {
// Listener for undo and redo functions to document
undo = new UndoManager();
textArea.getDocument().addUndoableEditListener(new UndoableEditListener() {
@Override
public void undoableEditHappened(UndoableEditEvent e) {
undo.addEdit(e.getEdit());
}
});
return undo;
}
private void fileMenu() {
// Create File Menu
fileMenu = new JMenu("File");
fileMenu.setMnemonic(KeyEvent.VK_F);
fileMenu.setPreferredSize(new Dimension(40, 20));
// Add file menu items
newFile = new JMenuItem("New");
newFile.setMnemonic(KeyEvent.VK_N);
newFile.addActionListener(this);
newFile.setPreferredSize(new Dimension(100, 20));
newFile.setEnabled(true);
openFile = new JMenuItem("Open...");
openFile.setMnemonic(KeyEvent.VK_O);
openFile.addActionListener(this);
openFile.setPreferredSize(new Dimension(100, 20));
openFile.setEnabled(true);
saveFile = new JMenuItem("Save");
saveFile.setMnemonic(KeyEvent.VK_S);
saveFile.addActionListener(this);
saveFile.setPreferredSize(new Dimension(100, 20));
saveFile.setEnabled(true);
saveAsFile = new JMenuItem("Save As...");
saveAsFile.setMnemonic(KeyEvent.VK_A);
saveAsFile.addActionListener(this);
saveAsFile.setPreferredSize(new Dimension(100, 20));
saveAsFile.setEnabled(true);
pageSetup = new JMenuItem("Page Setup...");
pageSetup.setMnemonic(KeyEvent.VK_U);
pageSetup.addActionListener(this);
pageSetup.setPreferredSize(new Dimension(100, 20));
pageSetup.setEnabled(true);
printFile = new JMenuItem("Print...");
printFile.setMnemonic(KeyEvent.VK_P);
printFile.addActionListener(this);
printFile.setPreferredSize(new Dimension(100, 20));
printFile.setEnabled(true);
exit = new JMenuItem("Exit");
exit.setMnemonic(KeyEvent.VK_E);
exit.addActionListener(this);
exit.setPreferredSize(new Dimension(100, 20));
exit.setEnabled(true);
// Add items to menu
fileMenu.add(newFile);
fileMenu.add(openFile);
fileMenu.add(saveFile);
fileMenu.add(saveAsFile);
fileMenu.add(pageSetup);
fileMenu.add(printFile);
fileMenu.add(exit);
}
private void editMenu() {
editMenu = new JMenu("Edit");
editMenu.setMnemonic(KeyEvent.VK_E);
editMenu.setPreferredSize(new Dimension(40, 20));
// Add file menu items
undoEdit = new JMenuItem("Undo");
undoEdit.setMnemonic(KeyEvent.VK_U);
undoEdit.addActionListener(this);
undoEdit.setPreferredSize(new Dimension(100, 20));
undoEdit.setEnabled(true);
redoEdit = new JMenuItem("Redo");
redoEdit.setMnemonic(KeyEvent.VK_R);
redoEdit.addActionListener(this);
redoEdit.setPreferredSize(new Dimension(100, 20));
redoEdit.setEnabled(true);
selectAll = new JMenuItem("Select All");
selectAll.setMnemonic(KeyEvent.VK_S);
selectAll.addActionListener(this);
selectAll.setPreferredSize(new Dimension(100, 20));
selectAll.setEnabled(true);
copy = new JMenuItem("Copy");
copy.setMnemonic(KeyEvent.VK_C);
copy.addActionListener(this);
copy.setPreferredSize(new Dimension(100, 20));
copy.setEnabled(true);
paste = new JMenuItem("Paste");
paste.setMnemonic(KeyEvent.VK_P);
paste.addActionListener(this);
paste.setPreferredSize(new Dimension(100, 20));
paste.setEnabled(true);
cut = new JMenuItem("Cut");
cut.setMnemonic(KeyEvent.VK_T);
cut.addActionListener(this);
cut.setPreferredSize(new Dimension(100, 20));
cut.setEnabled(true);
// Add items to menu
editMenu.add(undoEdit);
editMenu.add(redoEdit);
editMenu.add(selectAll);
editMenu.add(copy);
editMenu.add(paste);
editMenu.add(cut);
}
private void formatMenu() {
formatMenu = new JMenu("Format");
formatMenu.setMnemonic(KeyEvent.VK_O);
formatMenu.setPreferredSize(new Dimension(60, 20));
// Add file menu items
fontColor= new JMenu("Font Color");
fontColor.setMnemonic(KeyEvent.VK_C);
fontColor.addActionListener(this);
fontColor.setPreferredSize(new Dimension(100, 20));
fontColor.setEnabled(true);
fontSize= new JMenu("Font Style");
fontSize.setMnemonic(KeyEvent.VK_S);
fontSize.addActionListener(this);
fontSize.setPreferredSize(new Dimension(100, 20));
fontSize.setEnabled(true);
// Add submenu items
subColorRed= new JMenuItem("Red");
subColorRed.setMnemonic(KeyEvent.VK_R);
subColorRed.addActionListener(this);
subColorRed.setPreferredSize(new Dimension(100, 20));
subColorRed.setEnabled(true);
subColorBlue= new JMenuItem("Blue");
subColorBlue.setMnemonic(KeyEvent.VK_B);
subColorBlue.addActionListener(this);
subColorBlue.setPreferredSize(new Dimension(100, 20));
subColorBlue.setEnabled(true);
subColorGreen= new JMenuItem("Green");
subColorGreen.setMnemonic(KeyEvent.VK_G);
subColorGreen.addActionListener(this);
subColorGreen.setPreferredSize(new Dimension(100, 20));
subColorGreen.setEnabled(true);
subColorBlack= new JMenuItem("Black");
subColorBlack.setMnemonic(KeyEvent.VK_K);
subColorBlack.addActionListener(this);
subColorBlack.setPreferredSize(new Dimension(100, 20));
subColorBlack.setEnabled(true);
subTimes= new JMenuItem("Times New Roman");
subTimes.setMnemonic(KeyEvent.VK_T);
subTimes.addActionListener(this);
subTimes.setPreferredSize(new Dimension(125, 20));
subTimes.setEnabled(true);
subArial= new JMenuItem("Arial");
subArial.setMnemonic(KeyEvent.VK_A);
subArial.addActionListener(this);
subArial.setPreferredSize(new Dimension(100, 20));
subArial.setEnabled(true);
subCourier= new JMenuItem("Courier");
subCourier.setMnemonic(KeyEvent.VK_C);
subCourier.addActionListener(this);
subCourier.setPreferredSize(new Dimension(100, 20));
subCourier.setEnabled(true);
subVerdana= new JMenuItem("Verdana");
subVerdana.setMnemonic(KeyEvent.VK_V);
subVerdana.addActionListener(this);
subVerdana.setPreferredSize(new Dimension(100, 20));
subVerdana.setEnabled(true);
// Add items to menu
formatMenu.add(fontColor);
fontColor.add(subColorRed);
fontColor.add(subColorBlue);
fontColor.add(subColorGreen);
fontColor.add(subColorBlack);
formatMenu.add(fontSize);
fontSize.add(subTimes);
fontSize.add(subArial);
fontSize.add(subCourier);
fontSize.add(subVerdana);
}
private void helpMenu() {
helpMenu = new JMenu("Help");
helpMenu.setMnemonic(KeyEvent.VK_H);
helpMenu.setPreferredSize(new Dimension(40, 20));
// Add file menu items
about = new JMenuItem("About");
about.setMnemonic(KeyEvent.VK_A);
about.addActionListener(this);
about.setPreferredSize(new Dimension(100, 20));
about.setEnabled(true);
// Add items to menu
helpMenu.add(about);
}
// Method for saving files - Removes duplication of code
private void saveFile(File filename) {
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(filename));
writer.write(textArea.getText());
writer.close();
saved = true;
window.setTitle("Text Editor - " + filename.getName());
} catch (IOException err) {
err.printStackTrace();
}
}
// Method for quick saving files
private void quickSave(File filename) {
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(filename));
writer.write(textArea.getText());
writer.close();
} catch (IOException err) {
err.printStackTrace();
}
}
// Method for opening files
private void openingFiles(File filename) {
try {
openedFile = filename;
FileReader reader = new FileReader(filename);
textArea.read(reader, null);
opened = true;
window.setTitle("Text Editor - " + filename.getName());
} catch (IOException err) {
err.printStackTrace();
}
}
@Override
public void actionPerformed(ActionEvent event) {
if(event.getSource() == newFile) {
new DoesThisWork();
} else if(event.getSource() == openFile) {
JFileChooser open = new JFileChooser();
open.showOpenDialog(null);
File file = open.getSelectedFile();
openingFiles(file);
} else if(event.getSource() == saveFile) {
JFileChooser save = new JFileChooser();
File filename = save.getSelectedFile();
if(opened == false && saved == false) {
save.showSaveDialog(null);
int confirmationResult;
if(filename.exists()) {
confirmationResult = JOptionPane.showConfirmDialog(saveFile, "Replace existing file?");
if(confirmationResult == JOptionPane.YES_OPTION) {
saveFile(filename);
}
} else {
saveFile(filename);
}
} else {
quickSave(openedFile);
}
} else if(event.getSource() == saveAsFile) {
JFileChooser saveAs = new JFileChooser();
saveAs.showSaveDialog(null);
File filename = saveAs.getSelectedFile();
int confirmationResult;
if(filename.exists()) {
confirmationResult = JOptionPane.showConfirmDialog(saveAsFile, "Replace existing file?");
if(confirmationResult == JOptionPane.YES_OPTION) {
saveFile(filename);
}
} else {
saveFile(filename);
}
} else if(event.getSource() == pageSetup) {
job = PrinterJob.getPrinterJob();
format = job.pageDialog(job.defaultPage());
} else if(event.getSource() == printFile) {
job = PrinterJob.getPrinterJob();
if(job.printDialog()) {
try {
job.print();
} catch (PrinterException err) {
err.printStackTrace();
}
}
} else if(event.getSource() == exit) {
System.exit(0);
} else if(event.getSource() == undoEdit) {
try {
undo.undo();
} catch(CannotUndoException cu) {
cu.printStackTrace();
}
} else if(event.getSource() == redoEdit) {
try {
undo.redo();
} catch(CannotUndoException cur) {
cur.printStackTrace();
}
} else if(event.getSource() == selectAll) {
textArea.selectAll();
} else if(event.getSource() == copy) {
textArea.copy();
} else if(event.getSource() == paste) {
textArea.paste();
} else if(event.getSource() == cut) {
textArea.cut();
} else if(event.getSource() == about){
//createAboutFrame();
JLabel About = new JLabel();
About.setText("<html>"
+ "<p>This is a custom Text Editor</p>"
+ "<p>Built By Todd Eaton, October 2015</p>"
+ "<p>Brandeis University</p>"
+ "<p>Master of Software Engineering Candidate</p>");
JOptionPane.showMessageDialog(null, About, "About Text Editor", JOptionPane.INFORMATION_MESSAGE);
} else if(event.getSource() == subColorRed){
textArea.setForeground(Color.RED);
} else if(event.getSource() == subColorBlue) {
textArea.setForeground(Color.BLUE);
} else if(event.getSource() == subColorGreen) {
textArea.setForeground(Color.GREEN);
} else if(event.getSource() == subColorBlack) {
textArea.setForeground(Color.BLACK);
} else if(event.getSource() == subTimes){
textFont = new Font("Times New Roman", 0, 14);
textArea.setFont(textFont);
} else if(event.getSource() == subArial){
textFont = new Font("Arial", 0, 14);
textArea.setFont(textFont);
} else if(event.getSource() == subCourier){
textFont = new Font("Courier", 0, 14);
textArea.setFont(textFont);
} else if(event.getSource() == subVerdana){
textFont = new Font("Verdana", 0, 14);
textArea.setFont(textFont);
}
}
//============================================
// GETTERS AND SETTERS
//============================================
public JTextArea getTextArea() {
return textArea;
}
public void setTextArea(JTextArea text) {
textArea = text;
}
}
答案 0 :(得分:0)
以下评论
//editorWindow.add(toolBar, BorderLayout.NORTH);
应替换为
editorWindow.add(createToolBar(), BorderLayout.NORTH);
实际创建工具栏并将其添加到用户界面。
答案 1 :(得分:0)
您将JToolBar
添加到JFrame
创建的DoesThisWork
实例中,但屏幕上实际上并未显示。
首先删除extends JFrame
并依赖JFrame
分配给editorWindow
然后在您的createEditorWindow
方法中添加
editorWindow.add(createToolBar(), BorderLayout.WEST);
(您需要修复通过删除extends JFrame
生成的其他几个编译器错误,但它们应该非常明显)
答案 2 :(得分:0)
//editorWindow.add(toolBar, BorderLayout.NORTH);
您不会将工具栏添加到框架中。
您是否意识到代码中有两个JFrame?您的类扩展了JFrame,然后在您的代码中也创建了另一个JFrame。有时您的代码只使用add(...)
方法向组中添加组件。然后,有时您的代码会使用editorWindow.add(...)
向框架中添加组件。
您的代码令人困惑,因为您有两个框架。不要扩展JFrame。
从How to Make Menus上的Swing教程中的MenuLookDemo
代码开始。它将向您展示如何更好地构建代码,以便您不会有两个框架。 &#34;创建&#34;方法实际上应该返回组件,以便将它们添加到框架中。