为什么这句没有效果, 弹出来的没有跟着 main frame ??dialog.setLocationRelativeTo(this);import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class t2 extends JPanel {
JButton button ;
public t2() {
button = new JButton("Open");
setLayout(new FlowLayout());
add(button);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dialog dialog = new dialog(new Frame(), true);
dialog.setLocationRelativeTo(this);
}
});
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("TimeTabling System");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JComponent newContentPane = new t2();
newContentPane.setOpaque(true);
frame.setContentPane(newContentPane);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
class dialog extends JDialog{
JButton OKBtn, CancelBtn;
public dialog(Frame parent, boolean modal){
super(parent, modal);
setLayout(new FlowLayout());
OKBtn = new JButton("OK");
CancelBtn = new JButton("CancelBtn");
add(OKBtn);
add(CancelBtn);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
pack();
setVisible(true);
}
}
import java.awt.event.*;
import javax.swing.*;
public class t2 extends JPanel {
JButton button ;
public t2() {
button = new JButton("Open");
setLayout(new FlowLayout());
add(button);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dialog dialog = new dialog(new Frame(), true);
dialog.setLocationRelativeTo(this);
}
});
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("TimeTabling System");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JComponent newContentPane = new t2();
newContentPane.setOpaque(true);
frame.setContentPane(newContentPane);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
class dialog extends JDialog{
JButton OKBtn, CancelBtn;
public dialog(Frame parent, boolean modal){
super(parent, modal);
setLayout(new FlowLayout());
OKBtn = new JButton("OK");
CancelBtn = new JButton("CancelBtn");
add(OKBtn);
add(CancelBtn);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
pack();
setVisible(true);
}
}
这里的"this"是指ActionListener,当然不行了.
那如何取得父frame…然后set(父frame)
是这样吗?
此例中就是frame