简体   繁体   English

如何在作为BufferedImage()的JFrame中添加JPanel

[英]How to add JPanel in a JFrame that is a BufferedImage()

So far I have this: 到目前为止,我有这个: 在此处输入图片说明

The logic is that: 逻辑是:

a.)I will press the keybutton 'S' then the game will start 我将按下按键``S'',然后游戏将开始

b.)The JTextArea will show the conversation of the users(note: I didn't disable it for debugging purposes) b。)JTextArea将显示用户的对话(注意:我不是出于调试目的而禁用它)

c.)The JTextField will be the field the user will type text. c。)JTextField将是用户将键入文本的字段。

I have these working code: 我有这些工作代码:

package game;

//import 


public class Game extends JFrame {


public static final String SERVER_IP = "localhost";


public static final int WIDTH = 1200;
public static final int HEIGHT = 800;
public static final int SCALE = 1;


private final int FPS = 60;
private final long targetTime = 1000 / FPS;

private BufferedImage backBuffer;

public KeyboardInput input;
private Stage stage;

public String username = "";

public GameClient client;
public static Game game;

public static String message = "";

private Tank tank;

private javax.swing.JButton jButton1;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextArea jTextArea1;
private javax.swing.JTextField jTextField1;

public Game() throws HeadlessException {
    setSize(1000, 1000);
    addWindowListener(new WinListener());
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setLocationRelativeTo(null);
    setResizable(false);
    setVisible(true);
    //setUndecorated(false);
    addKeyListener(input);
    setVisible(true);
}    
public void init() {
    this.game = this;
    input = new KeyboardInput();

    //this.setSize(WIDTH, HEIGHT);
    //this.setLocationRelativeTo(null);
    //this.setResizable(false);


  Dimension expectedDimension = new Dimension(900, 50);
  Dimension expectedDimension2 = new Dimension(100, 50);
   jButton1 = new JButton("jButton1");

jTextArea1 = new JTextArea(6,6);
jTextArea1.setBounds(0,200,200,200);
jTextArea1.setBackground(Color.BLUE);
//jTextArea1.setFocusable(false);
jTextField1 = new JTextField("jTextField1");
JPanel panel2 = new JPanel();
panel2.setLayout(new FlowLayout());
panel2.add(jTextField1);
panel2.add(jButton1);
panel2.setBackground(Color.BLACK); // for debug only
panel2.setPreferredSize(expectedDimension);
panel2.setMaximumSize(expectedDimension);
panel2.setMinimumSize(expectedDimension);
jPanel1 = new JPanel();
jPanel1.setLayout(new BoxLayout(jPanel1, BoxLayout.Y_AXIS));
jPanel1.add(jTextArea1);
jPanel1.add(panel2);
jPanel1.setBackground(Color.RED); // for debug only
jPanel1.setPreferredSize(expectedDimension2);
jPanel1.setMaximumSize(expectedDimension2);
jPanel1.setMinimumSize(expectedDimension2);
jScrollPane1 = new JScrollPane(jPanel1,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
setContentPane(jScrollPane1);

System.out.println("init");
revalidate();

    client = new GameClient(SERVER_IP, this);

    backBuffer = new BufferedImage(800* SCALE,600 * SCALE, BufferedImage.TYPE_INT_RGB);
}

public Stage getStage() {
    return stage;
}

public class WinListener extends WindowAdapter {

    @Override
    public void windowClosing(WindowEvent e) {
        disconnect();
        System.exit(0);
    }

}


public void disconnect() {
    Packet01Disconnect p = new Packet01Disconnect(username);
    p.writeData(client);
    client.closeSocket();
    System.exit(0);
}

private Font font = new Font("Munro Small", Font.PLAIN, 96);
private Font font2 = new Font("Munro Small", Font.PLAIN, 50);
private Font fontError = new Font("Munro Small", Font.PLAIN, 25);
private int op = 0;


public void updateMenu() {
    if (input.up.isPressed()) {
        if (op == 1) {
            op = 0;
        } else {
            op++;
        }
        input.up.toggle(false);
    } else if (input.down.isPressed()) {
        if (op == 0) {
            op = 1;
        } else {
            op--;
        }
        input.down.toggle(false);
    } else if (input.enter.isPressed() && op == 0) {
        runningMenu = false;
        input.enter.toggle(false);
    } else if (input.enter.isPressed() && op == 1) {
        System.exit(0);
    }
}


public void drawMenu() {
    Graphics g = getGraphics();
    Graphics bbg = backBuffer.getGraphics();
    bbg.setFont(font);
    bbg.setColor(Color.white);

    bbg.drawString("Sample", 189, 180);
    bbg.setFont(font2);
    if (op == 0) {
        bbg.setColor(Color.red);
        bbg.drawString("Start", 327, 378);
        bbg.setColor(Color.white);
        bbg.drawString("Quit", 342, 425);
    } else if (op == 1) {
        bbg.setColor(Color.white);
        bbg.drawString("Start", 327, 378);
        bbg.setColor(Color.red);
        bbg.drawString("Quit", 342, 425);
    }

    g.drawImage(backBuffer, 0, 0, this);
}

public void draw() {
    Graphics g = getGraphics();
    Graphics bbg = backBuffer.getGraphics();
    bbg.setColor(Color.black);
    bbg.fillRect(0, 0, WIDTH, HEIGHT);
    stage.drawStage(bbg, this);
    for (Tank t : stage.getPlayers()) {
        t.draw(bbg, SCALE, this);
    }
    g.drawImage(backBuffer, 0, 0, this);
}


public void update() {

    tank.update(stage);

    stage.update();
}

private long time = 0;


public void updateLogin() {
    if (username.length() < 8) {
        if (input.letter.isPressed()) {
            username += (char) input.letter.getKeyCode();
            input.letter.toggle(false);
        }
    }

    if (input.erase.isPressed() && username.length() > 0) {
        username = username.substring(0, username.length() - 1);
        input.erase.toggle(false);
    }

    if (input.enter.isPressed() && username.length() > 0) {
        input.enter.toggle(false);
        time = System.currentTimeMillis();
        Packet00Login packet = new Packet00Login(username, 0, 0, 0); 
        packet.writeData(client);
    }

    if (message.equalsIgnoreCase("connect server success")) {
        time = 0;
        runningLogin = false;
        return;
    }

    if (message.equalsIgnoreCase("Username already exists")) {
        drawLogin();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException ex) {
        }
        message = "";
        username = "";
        time = 0;
    }

    if (message.equalsIgnoreCase("Server full")) {
        drawLogin();
        try {
            Thread.sleep(2000);
        } catch (Exception e) {
        }
        System.exit(0);
    }

    if (time != 0 && message.equals("") && (System.currentTimeMillis() - time) >= 5000) {
        message = "cannot connect to the server";
        drawLogin();
        try {
            Thread.sleep(2000);
        } catch (InterruptedException ex) {
        }
        message = "";
        time = 0;
    }
}


public void drawLogin() {
    Graphics g = getGraphics();
    Graphics bbg = backBuffer.getGraphics();
    bbg.setColor(Color.black);
    bbg.fillRect(0, 0, 800, 600);
    bbg.setColor(Color.red);
    bbg.setFont(fontError);
    bbg.drawString(message, 100, 100);
    bbg.setFont(font2);
    bbg.setColor(Color.white);
    bbg.drawString("Username", 284, 254);
    bbg.setColor(Color.red);
    bbg.drawString(username, 284, 304);
    g.drawImage(backBuffer, 0, 0, this);
}


public static String waitPlayers = "Waiting for others players";
public String auxWaitPlayers = waitPlayers;
public static int quantPlayers = 0;

public class StringWait extends Thread {

    public void run() {
        while (true) {
            try {
                waitPlayers = "waiting  for  others  players";
                Thread.sleep(1000);
                waitPlayers = "waiting  for  others  players.";
                Thread.sleep(1000);
                waitPlayers = "waiting  for  others  players..";
                Thread.sleep(1000);
                waitPlayers = "waiting  for  others  players...";
                Thread.sleep(1000);
            } catch (InterruptedException ex) {
            }
        }
    }
}


public void updateWaitPlayers() {
    if (quantPlayers == 1) {
        runningWaitPlayer = false;
    }
}


public void drawWaitPlayers() {
    Graphics g = getGraphics();
    Graphics bbg = backBuffer.getGraphics();
    bbg.setColor(Color.black);
    bbg.fillRect(0, 0, 800, 600);
    bbg.setColor(Color.white);
    bbg.setFont(fontError);
    bbg.drawString(waitPlayers, 100, 100);
    g.drawImage(backBuffer, 0, 0, this);
}

public boolean runningMenu = true, runningLogin = true, runningWaitPlayer = true, runningGame = true;

public int op2 = 0;


public void start() {
    long start;
    long elapsed;
    long wait;
    init();
    while (true) {
        runningGame = true;
        runningMenu = true;
        runningWaitPlayer = true;
        runningLogin = true;
        switch (op2) {
            //..
    }
}


public void setGameState(boolean state) {
   //...
}

public static void main(String[] args) throws InterruptedException {
    Game g = new Game();
    Thread.sleep(1000);
    g.start();
}

} }

And these is my objective interface: 这些是我的客观界面: 在此处输入图片说明

I hope someone will help me with my problem. 我希望有人能帮助我解决我的问题。

  • Set the "main" containers layout manager to BorderLayout 将“主”容器布局管理器设置为BorderLayout
  • On to this, add the GameInterface in the BorderLayout.CENTER position 对此,在BorderLayout.CENTER位置添加GameInterface
  • Create another ("interaction") container and set it's layout manager to BorderLayout , add this to the "main" container's BorderLayout.SOUTH position 创建另一个(“交互”)容器并将其布局管理器设置为BorderLayout ,然后将其添加到“主”容器的BorderLayout.SOUTH位置
  • Wrap the JTextArea in a JScrollPane and add it to the BorderLayout.CENTER position of your "interaction" container JTextArea包裹在JScrollPane ,并将其添加到“交互”容器的BorderLayout.CENTER位置
  • Create another container ("message"), this could use a GridBagLayout . 创建另一个容器(“消息”),可以使用GridBagLayout On to this add the JTextField (with GridBagConstraints#weightx set to 0 and GridBagConstraints#weightx set to 1 ) and add the button to the next cell ( GridBagConstraints#gridx set to 1 and GridBagConstraints#weightx set to 0 ) 在此JTextField添加JTextField (将GridBagConstraints#weightx设置为0并将GridBagConstraints#weightx设置为1 ),然后将按钮添加到下一个单元格( GridBagConstraints#gridx设置为1并将GridBagConstraints#weightx GridBagConstraints#gridx设置为0

For more details, see: 有关更多详细信息,请参见:

Note: 注意:

Graphics g = getGraphics(); is NOT how custom painting should be done. 不是应该如何定制绘画。 Instead, override the paintComponent of a component like JPanel and perform your custom painting there! 而是重写诸如JPanel之类的组件的paintComponent并在那里执行自定义绘制!

For more details see 有关更多详细信息,请参见

Example

测试版面

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JPanel master = new JPanel(new BorderLayout());
                master.setBackground(Color.BLUE);

                JPanel gameInterface = new JPanel() {
                    @Override
                    public Dimension getPreferredSize() {
                        return new Dimension(400, 400);
                    }
                };
                gameInterface.setBackground(Color.MAGENTA);

                master.add(gameInterface);

                JPanel interactions = new JPanel(new BorderLayout());
                interactions.add(new JScrollPane(new JTextArea(5, 20)));

                JTextField field = new JTextField(15);
                JButton btn = new JButton("Button");

                JPanel message = new JPanel(new GridBagLayout());
                GridBagConstraints gbc = new GridBagConstraints();
                gbc.gridx = 0;
                gbc.weightx = 1;
                gbc.fill = GridBagConstraints.HORIZONTAL;
                message.add(field, gbc);
                gbc.gridx = 1;
                gbc.weightx = 0;
                message.add(btn, gbc);

                interactions.add(message, BorderLayout.SOUTH);

                master.add(interactions, BorderLayout.SOUTH);

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(master);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM