之後 要改成動態的話,可以由外部讀取檔案決定 按鈕的數目及相關的資訊
import javax.swing.SwingUtilities;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.Rectangle;
import javax.swing.JOptionPane;
import java.awt.Frame;
public class layout extends JFrame{
/// 宣告要產生 button 的數目
private int _programNum=6;
/// JPanel
private JPanel jContentPane = null;
/// 宣告 JButton 的數目
private JButton[] jButtons = new JButton[_programNum];
/**
* @param args
*/
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
layout thisClass = new layout();
thisClass.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
thisClass.setVisible(true);
}
});
}
/**
* This is the default constructor
*/
public layout() {
super();
initialize();
}
/**
* This method initializes this
*
* @return void
*/
private void initialize() {
this.setSize(348, 224);
this.setContentPane(getJContentPane());
this.setTitle("動態產生 JButton");
/// 打開window 的事件
this.addWindowListener(new java.awt.event.WindowAdapter() {
public void windowOpened(java.awt.event.WindowEvent e) {
System.out.println("Open Window");
}
});
}
/**
* This method initializes jContentPane
*
* @return javax.swing.JPanel
*/
private JPanel getJContentPane() {
if (jContentPane == null) {
jContentPane = new JPanel();
jContentPane.setLayout(null);
/// 逐次添加 JButton
for(int i=0;i<_programNum;i++)
{
jContentPane.add(GetJButtons(i), null);
}
}
return jContentPane;
}
/**
* This method initializes JButtons [i]
*
* @return javax.swing.JButton
*/
private JButton GetJButtons(final int i) {
/// 宣告
jButtons[i] = new JButton();
/// 設定範圍
jButtons[i].setBounds(new Rectangle(12, 12+i*50, 310, 59));
/// 設定顯示文字
jButtons[i].setText("範例按鈕"+i);
/// 設定提示
jButtons[i].setToolTipText("快點按我!"+i);
/// 設定按鈕
jButtons[i].addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
System.out.println(" 按了範例按鈕"+i);
Frame frame = new Frame();
JOptionPane.showMessageDialog(frame, "按了範例按鈕"+i);
}
});
return jButtons[i];
}
}
沒有留言:
張貼留言