我有一個主JFrame(屏幕)和單獨的JPanels,它們都包含在它們自己的方法中。主方法調用另一個承載JFrame的方法(create),後者將所有其他JPanel添加到它。我的問題是這些JPanel中只有一個顯示,每次運行代碼時它都會更改。我試過有1個主JPanel和方法添加它們的組件(JLables ...),但我得到同樣的問題。那麼我怎麼能有多種方法,並同時在1個窗口中顯示全部。我相信我可以全部用1種方法,但這會變得很長。雖然不是現在,但我會有很多方法來把自己獨特的東西放在窗口上。請看我目前的代碼如下:在單個JFrame上顯示來自不同方法的多個JPanel
import java.awt.Frame;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class GUI extends JPanel
{
/**
* Creation of variables used throughout the GUI Class.
*/
private static final long serialVersionUID = 1L;
private int lookReplyX = 5;
private int lookReplyY = 5;
public static void main(String[] args)
{
GUI g = new GUI();
g.create();
}
private void create()
{
JFrame screen = new JFrame("Dungeon of Doom");
screen.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//set size to full screen.
screen.setExtendedState(Frame.MAXIMIZED_BOTH);
screen.setVisible(true);
//Add all JPanes to screen
screen.getContentPane().add(lookReplyGUI());
screen.getContentPane().add(titlePanel());
}
private JPanel lookReplyGUI()
{
JPanel lookReplyGUIPanel = new JPanel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
for(int y = lookReplyY; y>0; y--)
{
for(int x = lookReplyX; x>0; x--)
{
JLabel lookx = new JLabel(" " + y + "" + x);
c.gridwidth = 1;
c.gridheight = 1;
c.gridx = x+1;
c.gridy = y+1;
lookReplyGUIPanel.add(lookx, c);
}
}
return lookReplyGUIPanel;
}
private JPanel titlePanel()
{
JPanel titlePanel = new JPanel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
JLabel title = new JLabel("DOD");
titlePanel.add(title, c);
c.gridwidth = 7;
c.gridheight = 1;
c.gridx = lookReplyX+2;
c.gridy = 1;
return titlePanel;
}
}
謝謝!
感謝,這就是工作! ,非常感謝 – pokeairguy
我很高興它幫助 – MadProgrammer