2016-09-07 111 views
1

我試圖提示用戶輸入來自JOptionPane以更改JTextArea的字體大小,如下所示,爲「控制檯」。更改JTextArea字體大小的問題

問題

然而,JOptionPane中沒有顯示當我點擊大小JMenu的項目。

代碼:與JOptionPane的

Font font = new Font("Arial", Font.PLAIN, 12); 

panel = new JPanel(); 
panel.setLayout(new BorderLayout()); 
add(panel, BorderLayout.CENTER); 

JTextArea console = new JTextArea(); 
console.setLineWrap(true); 
console.setWrapStyleWord(true); 
console.setEditable(false); 
console.setFont(font); 

JScrollPane scroll = new JScrollPane(console); 
scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); 
panel.add(scroll, BorderLayout.CENTER); 

JMenuBar bar = new JMenuBar(); 
panel.add(bar, BorderLayout.NORTH); 

JMenu size = new JMenu("Size"); 
size.addActionListener(new ActionListener() { 
    @Override public void actionPerformed(ActionEvent e) { 
     String fontSize = JOptionPane.showInputDialog(panel, "New font size, 6 or larger:", "Set Font Size", JOptionPane.OK_CANCEL_OPTION); 
     Font newFont = font.deriveFont(Integer.parseInt(fontSize)); 
     console.setFont(newFont); 
    } 
}); 

bar.add(size); 
+0

無法更新Jtextarea中的字體。已經在http://stackoverflow.com/questions/2488384/setting-fonts-in-a-jtextarea?rq=1 – VinuBibin

+0

@VinuBibin回答好的,謝謝,但是如果你閱讀我的問題,它與JOptionPane點擊時不顯示大小JMenu項目 –

+0

使用'JMenuItem'而不是'JMenu' – copeg

回答

1

這似乎是一個bug但您可以使用'MenuListener'描述在此answer通過@TPete

這是他在回答中提供的代碼來解決此問題:

JMenu menu = new JMenu("MyMenu"); 
menu.addMenuListener(new MenuListener() { 

    @Override 
    public void menuSelected(MenuEvent e) { 
     System.out.println("menuSelected"); 
    } 

    @Override 
    public void menuDeselected(MenuEvent e) { 
     System.out.println("menuDeselected"); 
    } 

    @Override 
    public void menuCanceled(MenuEvent e) { 
     System.out.println("menuCanceled"); 
    } 
}); 

基本上他使用的MenuListener而不是ActionListener成功地捕捉事件。

希望這會有所幫助!

+0

也可以使用'JMenuItem'而不是'JMenu' – copeg

0

問題沒有顯示當我點擊大小JMenu的項目,是因爲我們需要顯示窗格中的容器是不正確

嘗試以下

JOptionPane.showInputDialog(**this**, "New font size, 6 or larger:", 
    "Set Font Size", JOptionPane.OK_CANCEL_OPTION);