簡體   English   中英

在擴展JFrame的類中的另一個JFrame上繪制一條線

[英]Drawing a line on another JFrame in a class that extends JFrame

我有一個有兩個JFrame的類,我試圖在特定的幀上繪制一條線。

我嘗試了下面的代碼,但它只出現在第一幀,即成功幀。

它也出現在成功框架的所有其他組件之上,從而使其他所有組件成為可能

組件不可見。 它沒有出現在comp框架中。

我該如何糾正這個問題。

這是我到目前為止的代碼:

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(...)方法中繪制的圖形根本不是猶太圖像。 為什么不簡單地在類之間共享數據,並使用數據(int)來繪制所需的位置。
  • 您很少希望GUI一次顯示多個JFrame。 通常一個窗口是主窗口(JFrame),它通常擁有任何其他窗口,這些窗口可以是對話窗口,例如JDialogs。
  • 閱讀圖形教程,了解正確的Swing Graphics方法

兩件事情:

如果要繪制“comp”框架,則應明確擴展該框架以重載其paint方法。 現在你正在重載“成功”框架的繪制方法。 comp.paint(g)行使用comp(標准JFrame)的paint方法繪制“Success”框架的Graphics對象。 您可能希望將其轉換為super.paint(g) ,然后將此paint函數放入其自己的JFrame中並從中創建comp。

http://pastebin.com/ZLYBHpmj

(對不起,第一篇文章,無法弄清楚如何讓Stackoverflow退出抱怨格式)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM