java_Swing之彈窗設計初次接觸。
阿新 • • 發佈:2019-02-17
使用Swing實現的一個簡單彈窗功能,基本容器的使用辦法,程式碼如下:
package test1;
import java.awt.Color;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
/**
*與awt元件不同,Swing元件不能直接的新增到頂層容器中,他必須天驕到一個與Swing頂層容器相關聯的
* 內容模板(content pane)上;內容面板是頂層容器包含的一個普通容器,它是一個輕量級元件。基本規則如下:
(1)把Swing元件放入一個頂層Swing容器的內容面板上
(2)避免使用非Swing的重量級元件。
*
*
*/
public class MyJFrame extends JFrame{
/**
*
*/
private static final long serialVersionUID = 1L;
public void CreatFrame(){
JFrame jf = new JFrame();
//一般情況下,他不能被直接放在頂層容器中
Container con = jf.getContentPane();
JLabel jb = new JLabel("this is a pane");
JButton jt = new JButton("alert a new window");
jt.setBounds(10, 10, 100, 21);
jt.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
new MyDialog1(MyJFrame.this).setVisible(true );
}
});
jb.setHorizontalAlignment(MAXIMIZED_HORIZ);
con.add(jt);
con.add(jb);
con.setBackground(Color.RED);
jf.setVisible(true);
jf.setSize(200, 150);
jf.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String []args){
new MyJFrame().CreatFrame();
}
}
class MyDialog1 extends JDialog{
/**
*
*/
private static final long serialVersionUID = 1L;
public MyDialog1(JFrame frame){
super(frame,"alert the window");
Container conn = getContentPane();
conn.add(new JLabel("test lable"));
setBounds(100,100,100,100);
System.out.println("test succesfully");
}
}
執行結果如下:
有疑問歡迎交流!!