我写了一个小的测试程序,它创建了一个拆分窗格,其中一个窗格是文本区域。我已经在窗格中添加了一个meubar和菜单项,但在创建的gui中没有看到它们。
有人能指出我在下面的程序中做错了什么吗:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.JMenuBar;
import java.util.*;
import javax.swing.text.BadLocationException;
import java.awt.*;
import java.io.IOException;
//SplitPaneDemo itself is not a visible component.
public class SplitPaneDemo extends JFrame
implements ActionListener {
private JTextArea ta;
private JMenuBar menuB;
private JMenu dbM;
private JMenuItem cnadb,bsmdb,cdmdb;
private JLabel picture;
private JSplitPane splitPane;
public SplitPaneDemo() {
ta = new JTextArea(); //textarea
ta.setLineWrap(true);
ta.setWrapStyleWord(true);
ta.addKeyListener(new KeyAdapter()
{
public void keyPressed(KeyEvent ke )
{
int code = ke.getKeyCode();
int modifiers = ke.getModifiers();
if(code == KeyEvent.VK_ENTER && modifiers == KeyEvent.CTRL_MASK)
{
System.out.println("cmd in table:");
}
}
});
JScrollPane taPane = new JScrollPane(ta);
picture = new JLabel();
picture.setFont(picture.getFont().deriveFont(Font.ITALIC));
picture.setHorizontalAlignment(JLabel.CENTER);
JScrollPane pictureScrollPane = new JScrollPane(picture);
splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
taPane, pictureScrollPane);
splitPane.setOneTouchExpandable(true);
splitPane.setDividerLocation(450);
//Provide minimum sizes for the two components in the split pane.
Dimension minimumSize = new Dimension(100, 100);
taPane.setMinimumSize(minimumSize);
pictureScrollPane.setMinimumSize(minimumSize);
//Provide a preferred size for the split pane.
splitPane.setPreferredSize(new Dimension(900, 900));
menuB = new JMenuBar(); //menubar
dbM = new JMenu("DB"); //file menu
cnadb = new JMenuItem("CNA");
bsmdb = new JMenuItem("BSM");
cdmdb = new JMenuItem("CDM");
setJMenuBar(menuB);
menuB.add(dbM);
dbM.add(cnadb);
dbM.add(bsmdb);
dbM.add(cdmdb);
cnadb.addActionListener(this);
bsmdb.addActionListener(this);
cdmdb.addActionListener(this);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
}
public void valueChanged(ListSelectionEvent e) {
}
public JSplitPane getSplitPane() {
return splitPane;
}
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("SplitPaneDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
SplitPaneDemo splitPaneDemo = new SplitPaneDemo();
frame.getContentPane().add(splitPaneDemo.getSplitPane());
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
您在SplitPaneDemo
类中添加了JMenuBar
,但当您实际调用createAndShowGUI时,您会生成一个新的JFrame
,并通过调用getSplitPane
将SplitPane
添加到其中。这个新框架对菜单栏一无所知。
如果您在SplitPaneDemo
中扩展JFrame
,为什么不使用它为您的gui制作框架呢?