单击按钮后,我将启动Window2。它没有立即启动,但在3秒后启动。我想要的是将它显示在屏幕的顶部。如果Window1仍然在屏幕上,但是如果我最小化Window1则失败。
代码在这里:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class TopTest {
public static void main(String[] args) {
TopTest test = new TopTest();
test.createUI();
}
public void createUI(){
JFrame frame = new JFrame("Window1");
JPanel panel = new JPanel();
JButton button = new JButton("show");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
Window window = new Window();
try {
Thread.sleep(3000);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
window.createUI();
}
});
panel.add(button);
frame.add(panel,BorderLayout.CENTER);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
class Window {
public void createUI(){
JFrame frame = new JFrame("Window2");
frame.setExtendedState(Frame.MAXIMIZED_BOTH);
frame.add(new MainPanel());
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
@SuppressWarnings("serial")
class MainPanel extends JPanel{
@Override
public Dimension getPreferredSize() {
// TODO Auto-generated method stub
return new Dimension(800,600);
}
protected void paintComponent(Graphics g){
g.setFont(new Font("Arial", Font.BOLD, 50));
g.drawString("I am Window2", 200, 200);
}
}
}
}
提前感谢您的帮助。
答案 0 :(得分:1)
将此行添加到createGUI
方法
frame.setAlwaysOnTop(true);