public ButtonGrid(int width, int length){ //constructor
frame.setTitle("MPC");
frame.setLayout(new GridLayout(width,length)); //set layout
grid=new JButton[width-1][length]; //allocate the size of grid
for(int y=0; y<length; y++){
for(int x=0; x<width-1; x++){
grid[x][y]=new JButton("("+x+","+y+")"); //creates new button
frame.add(grid[x][y]); //adds button to grid
grid[x][y].addActionListener(this);
grid[x][y].addKeyListener(this);
//grid[x][y].setMnemonic(KeyEvent.VK_0);
grid[x][y].setPreferredSize(new Dimension(75,75));
}
}
for(int i =0; i<boxList.length; i++)
box.addItem(boxList[i]);
box.addActionListener(this);
frame.add(box);
frame.add(met_speed);
frame.add(Play);
Play.addActionListener(this);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack(); //sets appropriate size for frame
frame.setVisible(true); //makes frame visible
}
public void newWindow(){
JFrame frame1 = new JFrame();
frame1.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
JTextField[] btn = new JTextField[12];
JLabel[] lbl = new JLabel[12];
JLabel name = new JLabel("Preset Name");
JTextField name1 = new JTextField();
name1.setPreferredSize(new Dimension(100,25));
gbc.gridx = 0;
gbc.gridy = 0;
frame1.add(name, gbc);
gbc.gridx++;
frame1.add(name1, gbc);
gbc.gridx = 0;
gbc.gridy = 1;
for(int i = 0; i<12; i++){
lbl[i] = new JLabel("Button" + (i+1));
frame1.add(lbl[i], gbc);
gbc.gridy++;
}
gbc.gridx = 1;
gbc.gridy = 1;
for(int i = 0; i<12; i++){
btn[i] = new JTextField();
btn[i].setPreferredSize(new Dimension(75,25));
frame1.add(btn[i], gbc);
gbc.gridy++;
}
gbc.gridx = 0;
gbc.gridy = 14;
JButton save = new JButton("Save");
frame1.add(save, gbc);
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame1.pack(); //sets appropriate size for frame
frame1.setVisible(true); //makes frame visible
}
第一個功能ButtonGrid在main中被調用並且包含真正的程序。按下按鈕之後,newWindow()被稱爲彈出窗口。到目前爲止,它工作正常,但是當我關閉frame1時,它會關閉frame並結束程序。不用退出程序關閉java彈出框架
我這樣做是否正確,或者是否有我需要添加的東西?
你'frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)'這意味着完全相同 – khelwood 2014-12-02 00:57:34
看看[使用多個JFrames,好/壞實踐?](http://stackoverflow.com/q/9554636/418556),爲什麼你應該避免顯示多個幀... – MadProgrammer 2014-12-02 00:58:49
'grid [x ] [y] .setPreferredSize(new Dimension(75,75));'請參閱[我應該避免使用Java Swing中的set(Preferred | Maximum | Minimum)Size方法嗎?](http://stackoverflow.com/q/7229226/418556)(是) – 2014-12-02 01:11:27