我希望有这样的布局:
灰色区域将是两个不同的菜单。
我设法制作了分割窗格,但我似乎无法添加菜单,这是我的代码:
package View;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Toolkit;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JPanel;
import javax.swing.JSplitPane;
import javax.swing.plaf.basic.BasicSplitPaneUI;
public class TaskView extends JFrame{
JMenuBar menuBar;
JMenu addTask, refresh;
private int screenHeight,screenWidth;
public TaskView() {
setTitle("TASKS");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
Toolkit myScreen = Toolkit.getDefaultToolkit();
Dimension screenSize = myScreen.getScreenSize();
screenHeight = screenSize.height;
screenWidth = screenSize.width;
setSize(screenWidth/2,screenHeight/2);
System.out.println(screenWidth/2);
setLocation(screenWidth/4,screenHeight/4);
placeComponents(this.getContentPane());
}
private void placeComponents(Container contentPane) {
JPanel jsp1 = new JPanel();
JPanel jsp2 = new JPanel();
JLabel j1 = new JLabel("Area 1");
JLabel j2 = new JLabel("Area 2");
menuBar = new JMenuBar();
addTask = new JMenu("Add Task");
refresh = new JMenu("Refresh");
menuBar.add(addTask);
menuBar.add(refresh);
jsp1.add(menuBar);
jsp1.add(j1);
jsp2.add(j2);
JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
true, jsp1, jsp2);
splitPane.setUI(new BasicSplitPaneUI());
splitPane.setOneTouchExpandable(false);
contentPane.add(splitPane);
splitPane.setEnabled(false);
setVisible(true);
splitPane.setDividerLocation(300);
}
}
每当我尝试添加一个菜单时,它会在左侧面板中弄得一团糟,它看起来并不像菜单一样,我怎样才能添加菜单而不会看起来像狗屎?
答案 0 :(得分:1)
试试这个
public class TaskView extends JFrame {
public TaskView() throws HeadlessException {
createGUI();
}
private void createGUI() {
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setPreferredSize(new Dimension(600, 400));
JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, createPanel(), createPanel());
splitPane.setResizeWeight(0.5);
add(splitPane, BorderLayout.CENTER);
pack();
setLocationRelativeTo(null);
}
private JPanel createPanel() {
JPanel panel = new JPanel(new BorderLayout());
JMenuItem menuItem1 = new JMenuItem("MenuItem 1");
JMenuItem menuItem2 = new JMenuItem("MenuItem 2");
JMenuItem menuItem3 = new JMenuItem("MenuItem 3");
JMenu menu = new JMenu("Main");
menu.add(menuItem1);
menu.addSeparator();
menu.add(menuItem2);
menu.add(menuItem3);
JMenuBar menuBar = new JMenuBar();
menuBar.add(menu);
menuBar.add(new JMenu("View"));
panel.add(menuBar, BorderLayout.PAGE_START);
return panel;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new TaskView().setVisible(true));
}
}