我有一個簡單的框架,它有一個按鈕來切換該框架是否全屏。我想擁有它,以便用戶只需按下回車鍵切換全屏。我對Java非常陌生。我希望事件收聽者在private FrontEnd()
讓用戶按回車鍵在全屏之間切換
import java.awt.event.*;
import javax.swing.*;
public class FrontEnd extends JFrame {
private boolean FullScreenMode = false;
private int PrevX, PrevY, PrevWidth, PrevHeight;
public static void main(String[] args) {
FrontEnd frame = new FrontEnd();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(480, 320);
frame.setVisible(true);
}
private FrontEnd() {
JPanel contentPane = new JPanel();
setContentPane(contentPane);
// From Here starts the trick
FullScreenEffect effect = new FullScreenEffect();
JButton fullscreenButton = new JButton("Fullscreen Mode");
fullscreenButton.addActionListener(effect);
contentPane.add(fullscreenButton);
fullscreenButton.setVisible(true);
}
private class FullScreenEffect implements ActionListener {
@Override
public void actionPerformed(ActionEvent arg0) {
if (!FullScreenMode) {
PrevX = getX();
PrevY = getY();
PrevWidth = getWidth();
PrevHeight = getHeight();
dispose();
setUndecorated(true);
setBounds(0, 0, getToolkit().getScreenSize().width, getToolkit().getScreenSize().height);
setVisible(true);
FullScreenMode = true;
} else {
dispose();
setUndecorated(false);
setBounds(PrevX, PrevY, PrevWidth, PrevHeight);
setVisible(true);
FullScreenMode = false;
}
}
}
什麼問題?你有錯誤嗎? –
沒有錯誤。該按鈕按預期工作。但不是一個按鈕點擊,我想要一個按鍵。所以沒有按鈕和用戶按下輸入切換全屏 – Ross
那麼,[使用Keylistener](http://stackoverflow.com/questions/21997130/how-to-use-keylistener-with-jframe)或更好的[鍵綁定](https://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html)。您應該先嚐試這些解決方案。 – AxelH