我有一个有两个 JFrames 的类,并试图在特定帧上画一条线。
我尝试了下面的代码,但它只出现在第一帧中,即成功帧。
它也出现在成功框架的所有其他组件之上,从而使所有其他组件
组件不可见。它不会出现在合成框架中。
我该如何纠正这一点。
这是我到目前为止的代码:
import javax.swing.*;
import java.awt.*;
import java.awt.geom.*;
import java.awt.event.*;
public class lineGUI{
public static void main(String []args){
Success s=new Success();
s.setVisible(true);
}
}
class Success extends JFrame{
JPanel alas =new JPanel();
JFrame comp =new JFrame();
public Success(){
JPanel panel=new JPanel();
getContentPane().add(panel);
setSize(450,450);
JButton button =new JButton("press");
panel.add(button);
comp.setSize(650,500);
comp.setTitle("View Report");
JRootPane compPane=comp.getRootPane();
Container contePane=compPane.getContentPane();
contePane.add(alas);
ActionListener action =new ActionListener(){
public void actionPerformed(ActionEvent e){
if (e.getSource()==button){
comp.setVisible(true);
}
}
};
button.addActionListener(action);
JButton button2=new JButton("access");
alas.add(button2);
}
public void paint(Graphics g) {
comp.paint(g);
Graphics2D g2 = (Graphics2D) g;
Line2D lin = new Line2D.Float(100, 100, 250, 260);
g2.draw(lin);
}
}
你有一些疯狂的代码。建议:
- 不要直接在 JFrame 中绘制,而是在派生自 JComponent 的对象的 paintComponent 方法中绘制,例如 JPanel 或 JComponent 本身。
- 直接使用另一个组件的 paint(...) 方法绘制的绘图根本不是犹太洁食。为什么不简单地在类之间共享数据,并使用数据(整数)在需要的地方绘制。
- 您很少希望 GUI 一次显示多个 JFrame。通常一个窗口是主窗口(JFrame),它通常拥有任何其他窗口,这些窗口将是对话窗口,如JDialogs。
- 阅读图形教程以了解执行摆动图形的正确方法
两件事:
如果要在"comp"帧中绘制,则应显式扩展该帧以重载其绘制方法。现在你正在重载"成功"框架的绘画方法。comp.paint(g)
线使用 comp 的绘制方法(标准 JFrame)在"成功"帧的图形对象上绘制。您可能希望将其转换为super.paint(g)
,然后将此绘制函数放入它自己的JFrame中,并从中创建comp。
http://pastebin.com/ZLYBHpmj
(抱歉,第一篇文章,无法弄清楚如何让 Stackoverflow 停止抱怨格式)