我有一個JMenu
A內JMenuBar
對齊到屏幕的右側。在此菜單中有幾個JMenuItems
,以及另一個JMenu
B。由於菜單A右對齊,我需要菜單B向左側打開。爲了做到這一點,我發現代碼將JMenu展開到左側,同時保留默認的文本對齊方式
setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
。
但問題是,這與菜單2的文本對齊混淆,我想保持與其他菜單項完全相同。
我也嘗試手動對齊使用SwngConstants.leftAlign菜單2,然而,這是很嚴重:
我怎樣才能使畫面向左展開,同時保留默認文本對齊?提前致謝!我用於產生上述圖像中的代碼如下所示:
import java.awt.*;
import javax.swing.*;
public class Test{
public Test(){
JFrame frame = new JFrame();
JMenuBar menuBar = new JMenuBar();
JMenu menu1 = new JMenu("Menu 1");
JMenu menu2 = new JMenu("Menu 2");
JMenuItem menuitem1 = new JMenuItem("Menu Item 1");
JMenuItem menuitem2 = new JMenuItem("Menu Item 2");
JMenuItem menuitem3 = new JMenuItem("Menu Item 3");
JMenuItem menuitem4 = new JMenuItem("Menu Item 4");
menuBar.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
menu1.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
menu2.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
menu2.setHorizontalAlignment(SwingConstants.LEFT);
menuBar.add(menu1);
menu1.add(menuitem1);
menu1.add(menuitem2);
menu1.add(menu2);
menu2.add(menuitem3);
menu2.add(menuitem4);
frame.setJMenuBar(menuBar);
frame.getContentPane().setBackground(Color.WHITE);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension(270,170));
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args){
try{
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
UIManager.getLookAndFeelDefaults().put("Label.font", new Font("Arial", Font.PLAIN, 12));
UIManager.getLookAndFeelDefaults().put("Button.font", new Font("Arial", Font.PLAIN, 12));
UIManager.getLookAndFeelDefaults().put("ComboBox.font", new Font("Arial", Font.PLAIN, 12));
UIManager.getLookAndFeelDefaults().put("JTextField.font", new Font("Arial", Font.PLAIN, 12));
new Test();
} catch(Exception e){
JOptionPane.showConfirmDialog(null, e.getMessage());
}
}
}
UPDATE:如果刪除的代碼對準菜單從右至左和移動框架到顯示屏幕的邊緣處的線,然後菜單按照需要進行操作(即菜單不會從顯示器擴展)。也許有辦法告訴菜單不要擴展JFrame而不是顯示器?
UPDATE:謝謝@StanislavL的想法。使用下面的代碼覆蓋菜單2會訣竅,它也擺脫了兩個菜單之間難看的重疊。請注意,菜單2不再需要ComponentOrientation.RIGHT_TO_LEFT
。
JMenu menu2 = new JMenu("Menu 2"){
protected Point getPopupMenuOrigin(){
return new Point(-this.getPopupMenu().getPreferredSize().width, 0);
}
};
大的歡呼聲!第二個工作,將更新問題以顯示工作代碼。 – Hungry 2014-10-22 12:13:10