我正在嘗試為不同的 JPanel 添加背景(此后它們將被稱為 Window)。這些 Windows 是我創建的類并讓它們繼承 JPanel。然后根據程式的狀態,將一個視窗設定為程式 JFrame 的內容面板。當在某些 Windows 中設定背景而在其他 Windows 中沒有設定背景時,問題就出現了。背景設定是使用paintComponent(Graphics g) 方法執行的,但是盡管我已經嘗試修復錯誤,但我沒有成功。
這是我認為可能對那些想要幫助的人有用的代碼:
主回圈:
public class Game{
//here comes other stuff (constructor, main, other methods...)
private void run(){
while(true){
if(GameState.changed){
Screen.getInstance().seeWindow(state);
GameState.changed = false;
}else {
Screen.getInstance().requestFocus(state);
}
}
}
}
螢屏類:
package view;
import game.GameState;
import view.wins.*;
import javax.swing.*;
import java.awt.*;
public class Screen extends JFrame {
private final int WIDTH;
private final int HEIGHT;
private static Screen instance = null;
private JComponent titleWindow, menuWindow, settingsWindow;
private Screen(){
WIDTH = 1152;
HEIGHT = 768;
setTitle("Game");
setDefaultCloseOperation(EXIT_ON_CLOSE);
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
this.setLocation(dim.width/2-WIDTH/2, (dim.height - 50)/2-HEIGHT/2);
Dimension size = new Dimension(WIDTH, HEIGHT);
setPreferredSize(size);
setMinimumSize(size);
setMaximumSize(size);
setSize(size);
setResizable(false);
setVisible(true);
}
public static Screen getInstance() {
if(instance == null){
instance = new Screen();
}
return instance;
}
public void seeWindow(GameState state){
switch(state){
case TITLE -> setContentPane(getTitleWindow());
case MENU -> setContentPane(getMenuWindow());
case SETTINGS -> setContentPane(getSettingsWindow());
}
pack();
}
public void requestFocus(GameState state){
switch (state){
case TITLE -> getTitleWindow().requestFocus();
case MENU -> getMenuWindow().requestFocus();
case SETTINGS -> getSettingsWindow().requestFocus();
}
}
private JComponent getTitleWindow(){
if(titleWindow == null){
titleWindow = new TitleWindow();
}
return titleWindow;
}
private JComponent getMenuWindow(){
if(menuWindow == null){
menuWindow = new MenuWindow();
}
return menuWindow;
}
private JComponent getSettingsWindow(){
if(settingsWindow == null){
settingsWindow = new SettingsWindow();
}
return settingsWindow;
}
}
視窗抽象類:
package view.wins;
import utilz.GFXManager;
import view.Screen;
import javax.swing.*;
import java.awt.*;
import java.util.Observer;
public abstract class Window extends JComponent implements Observer {
private Image background;
public Window(String background){
setLayout(new BorderLayout());
setPreferredSize(Screen.getInstance().getPreferredSize());
setBackground(background);
setFocusable(true);
}
protected void setBackground(String backgroundName){
this.background = GFXManager.getInstance().getImage("backgrounds/" backgroundName ".png");
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(background, 0, 0, null);
}
}
正確設定背景的視窗:
package view.wins;
import game.GameState;
import game.Game;
import jdk.swing.interop.SwingInterOpUtils;
import logic.TitleLogic;
import utilz.GFXManager;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Observable;
import java.util.Observer;
public class TitleWindow extends Window implements Observer {
private final String BELOW_TITLE_TEXT;
private final ImageIcon TITLE_ICON;
private JLabel lblTitleIcon, lblBelowTitle;
private KeyController keyController;
public TitleWindow(){
super("title_background");
BELOW_TITLE_TEXT = "Press enter to start";
TITLE_ICON = new ImageIcon(GFXManager.getInstance().getImage("texts/title.png"));
TitleLogic.getInstance().addObserver(this);
setLayout(new BorderLayout());
addKeyListener(new KeyController());
add(getLblTitleIcon(), BorderLayout.CENTER);
add(getLblBelowTitle(), BorderLayout.SOUTH);
}
private JLabel getLblTitleIcon(){
if(lblTitleIcon == null){
lblTitleIcon = new JLabel(TITLE_ICON);
}
return lblTitleIcon;
}
private JLabel getLblBelowTitle(){
if(lblBelowTitle == null){
lblBelowTitle = new JLabel(BELOW_TITLE_TEXT, SwingConstants.CENTER);
lblBelowTitle.setFont(new Font("MS Gothic", Font.PLAIN, 24));
lblBelowTitle.setForeground(new Color(30,230,120));
}
return lblBelowTitle;
}
private KeyController getKeyController(){
if(keyController == null){
keyController = new KeyController();
}
return keyController;
}
@Override
public void update(Observable o, Object arg) {
if(TitleLogic.getInstance().isTickColorChange()){
getLblBelowTitle().setForeground(new Color(120, 30, 230));
}else{
getLblBelowTitle().setForeground(new Color(30,230,120));
}
}
private class KeyController extends KeyAdapter {
@Override
public void keyTyped(KeyEvent e) {
if(e.getKeyChar() == '\n'){
Game.getInstance().setState(GameState.MENU);
}else if(e.getKeyChar() == 'c'){
TitleLogic.getInstance().tickColorChange();
}
}
}
}
未設定背景的視窗:
package view.wins;
import game.GameState;
import game.Game;
import logic.MenuLogic;
import view.objs.Button;
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Observable;
import java.util.Observer;
public class MenuWindow extends Window implements Observer {
private JPanel btnPanel;
private Button btnStartNewGame, btnLoadGame, btnSettings, btnExit;
private Controller controller;
public MenuWindow(){
super("title_background");
MenuLogic.getInstance().addObserver(this);
setLayout(new BorderLayout());
add(getBtnPanel(), BorderLayout.CENTER);
}
private JPanel getBtnPanel(){
if(btnPanel == null){
btnPanel = new JPanel(new GridLayout(4,1));
btnPanel.add(getBtnStartNewGame());
btnPanel.add(getBtnLoadGame());
btnPanel.add(getBtnSettings());
btnPanel.add(getBtnExit());
}
return btnPanel;
}
private Button getBtnStartNewGame(){
if(btnStartNewGame == null){
btnStartNewGame = new Button("mediumLong", "Start new game", getController());
}
return btnStartNewGame;
}
private Button getBtnLoadGame(){
if(btnLoadGame == null){
btnLoadGame = new Button("mediumLong", "Load game", getController());
}
return btnLoadGame;
}
private Button getBtnSettings(){
if(btnSettings == null){
btnSettings = new Button("mediumLong", "Settings", getController());
}
return btnSettings;
}
private Button getBtnExit(){
if(btnExit == null){
btnExit = new Button("mediumLong", "Exit", getController());
}
return btnExit;
}
private Controller getController(){
if(controller == null){
controller = new Controller();
}
return controller;
}
@Override
public void update(Observable o, Object arg) {
}
private class Controller extends MouseAdapter {
@Override
public void mouseClicked(MouseEvent e) {
if(e.getSource().equals(getBtnStartNewGame())){
}else if(e.getSource().equals(getBtnLoadGame())){
}else if(e.getSource().equals(getBtnSettings())){
Game.getInstance().setState(GameState.SETTINGS);
}else if(e.getSource().equals(getBtnExit())){
System.exit(0);
}
}
@Override
public void mouseEntered(MouseEvent e) {
((Button)e.getSource()).changeHighlight();
}
@Override
public void mouseExited(MouseEvent e) {
((Button)e.getSource()).changeHighlight();
}
}
}
Button 是我自己的一類。
如果有人想自己測驗或查看更多代碼,請訪問github 存盤庫。
I tried everything and more. I've noticed that the Graphics of MenuWindow aren't initialized, so the problem could come because that window isn't rendered. I don't know.
uj5u.com熱心網友回復:
這...
private void run(){
while(true){
if(GameState.changed){
Screen.getInstance().seeWindow(state);
GameState.changed = false;
}else {
Screen.getInstance().requestFocus(state);
}
}
}
是個壞主意。除了“狂野回圈”本身通常是個壞主意之外,Swing 也不是執行緒安全的并且是單執行緒的。
這意味著如果它在事件調度執行緒的背景關系中運行,它將阻塞它并阻止它處理任何新事件。如果它沒有在 EDT 中運行,您就有可能導致任何數量的圖形故障或其他“臟執行緒”問題。
再加上像這樣的“瘋狂回圈”也會消耗 CPU 周期這一事實,您會增加巨大的性能開銷,而幾乎沒有收益。
首先看一下Swing 中的并發性
Screen.getInstance().requestFocus(state);也是對已知限制的一種破解,KeyListener通過使用鍵系結 API可以更好地解決這些限制
考慮到所有這些,Kavaliro應該看起來更像......
package game;
import view.Screen;
public class Kavaliro {
private static Kavaliro instance = null;
private GameState state;
private Kavaliro() {
state = GameState.TITLE;
Screen.getInstance().seeWindow(state);
}
public static Kavaliro getInstance() {
if (instance == null) {
instance = new Kavaliro();
}
return instance;
}
public static void main(String[] args) {
Kavaliro game = Kavaliro.getInstance();
}
public void setState(GameState state) {
Screen.getInstance().seeWindow(state);
}
}
這也不是在 Java 中創建單例的好方法。
public static Kavaliro getInstance() {
if (instance == null) {
instance = new Kavaliro();
}
return instance;
}
你可以看看Java Singleton Design Pattern Best Practices with Examples和What is an effective way to implement a singleton pattern in Java? 或者您可以只使用依賴注入(可能還有一些對依賴注入與單例的研究)
現在,正如我所說,KeyListener監控用戶鍵盤輸入通常是一個糟糕的選擇,這意味著TitleWindow應該改變,更像......
package view.wins;
import game.GameState;
import game.Kavaliro;
import game.Utilities;
import logic.TitleLogic;
import utilz.GFXManager;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Observable;
import java.util.Observer;
public class TitleWindow extends Window implements Observer {
private final String BELOW_TITLE_TEXT;
private final ImageIcon TITLE_ICON;
private JLabel lblTitleIcon, lblBelowTitle;
public TitleWindow() {
super("title_background");
BELOW_TITLE_TEXT = "Press enter to start";
TITLE_ICON = new ImageIcon(GFXManager.getInstance().getImage("texts/title.png"));
TitleLogic.getInstance().addObserver(this);
setLayout(new BorderLayout());
Utilities.addKeyBinding(this, Utilities.keyStrokeFor(Utilities.Input.ENTER), new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
Kavaliro.getInstance().setState(GameState.MENU);
}
});
Utilities.addKeyBinding(this, Utilities.keyStrokeFor(Utilities.Input.TITLE_TOGGLE), new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
TitleLogic.getInstance().tickColorChange();
}
});
add(getLblTitleIcon(), BorderLayout.CENTER);
add(getLblBelowTitle(), BorderLayout.SOUTH);
}
private JLabel getLblTitleIcon() {
if (lblTitleIcon == null) {
lblTitleIcon = new JLabel(TITLE_ICON);
}
return lblTitleIcon;
}
private JLabel getLblBelowTitle() {
if (lblBelowTitle == null) {
lblBelowTitle = new JLabel(BELOW_TITLE_TEXT, SwingConstants.CENTER);
lblBelowTitle.setFont(new Font("MS Gothic", Font.PLAIN, 24));
lblBelowTitle.setForeground(new Color(30, 230, 120));
}
return lblBelowTitle;
}
@Override
public void update(Observable o, Object arg) {
if (TitleLogic.getInstance().isTickColorChange()) {
getLblBelowTitle().setForeground(new Color(120, 30, 230));
} else {
getLblBelowTitle().setForeground(new Color(30, 230, 120));
}
}
}
Now, to make live easier, I wrote a quick "utility" class...
package game;
import java.awt.event.KeyEvent;
import javax.swing.Action;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JComponent;
import static javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW;
import javax.swing.KeyStroke;
public class Utilities {
public static enum KeyState {
PRESSED, RELEASED
}
public static enum Input {
ENTER(KeyEvent.VK_ENTER), TITLE_TOGGLE(KeyEvent.VK_C);
private int keyEvent;
private Input(int keyEvent) {
this.keyEvent = keyEvent;
}
protected KeyStroke getKeyStroke(int modifiers, KeyState keyState) {
return KeyStroke.getKeyStroke(keyEvent, 0, keyState == KeyState.RELEASED ? true : false);
}
}
public static void addKeyBinding(JComponent parent, KeyStroke keyStroke, Action action) {
addKeyBinding(parent, keyStroke.toString(), keyStroke, action);
}
public static void addKeyBinding(JComponent parent, String name, KeyStroke keyStroke, Action action) {
InputMap inputMap = parent.getInputMap(WHEN_IN_FOCUSED_WINDOW);
ActionMap actionMap = parent.getActionMap();
inputMap.put(keyStroke, name);
actionMap.put(name, action);
}
public static KeyStroke keyStrokeFor(Input key) {
return keyStrokeFor(key, 0, KeyState.PRESSED);
}
public static KeyStroke keyStrokeFor(Input key, int modifiers) {
return keyStrokeFor(key, modifiers, KeyState.PRESSED);
}
public static KeyStroke keyStrokeFor(Input key, int modifiers, KeyState keyState) {
return key.getKeyStroke(modifiers, keyState);
}
public static KeyStroke keyStrokeFor(int key) {
return keyStrokeFor(key, 0, KeyState.PRESSED);
}
public static KeyStroke keyStrokeFor(int key, int modifiers) {
return keyStrokeFor(key, modifiers, KeyState.PRESSED);
}
public static KeyStroke keyStrokeFor(int key, int modifiers, KeyState keyState) {
return KeyStroke.getKeyStroke(key, 0, keyState == KeyState.RELEASED ? true : false);
}
}
This takes care of a lot of the boiler plate/repeating code, but also provides a means to "limit" the possible inputs to the API. Note the Input enum allows for ENTER and TITLE_TOGGLE as viable options for the keyStrokeFor methods.
Note that TITLE_TOGGLE "hides" the key stroke which is used, but it is pretty self documenting at the same time. There are lots of other ways you could build out these concepts, this is just an example.
And...
public class Button extends JLabel {
would get a very large, no, from me. There is already a button component within the API and you should use it. It even supports things like roll over, for example and example, as well as a verity of other functionalities, which you're going to be spending a lot of time re-building.
See How to Use Buttons, Check Boxes, and Radio Buttons. And, yes, you can remove the Look And Feel fill background and borders if you really want to.
I don't know about you, and I don't use Intellij, but return ImageIO.read(new File(GFX_PATH name)); broke for me.
Resources like these should really be embedded within the application's runtime context (tech babble for "included in the Jar"). This will prevent issues with trying to locate the resources at runtime when the "working directory" context is not the same as the location of the res folder.
You should be using...
return ImageIO.read(getClass().getResource(GFX_PATH name));
but how you configure Intellji to include the context of the res folder into your application context is beyond me.
public void seeWindow(GameState state){
// Use a CardLayout
switch(state){
case TITLE -> setContentPane(getTitleWindow());
case MENU -> setContentPane(getMenuWindow());
case SETTINGS -> setContentPane(getSettingsWindow());
}
pack();
}
is, well, short sighted. Instead you should be using a CardLayout which will do this for you, and in away which generally will work reliably.
See How to Use CardLayout for more details
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/457799.html
