j**a简单画线程序

时间:2013.05.02 发布人:tunglin22

j**a简单画线程序

已解决问题

谷歌tunglin22用户在2013.05.02提交了关于“逸动j**a简单画线程序”的提问,欢迎大家涌跃发表自己的观点。目前共有1个回答,最后更新于2024-09-01T14:33:45。希望大家能够帮助她。

详细问题描述及疑问:期待您的答案,你无异于雪中送炭,让我感激涕零 !

希望以下的回答,能够帮助你。

第1个回答

用户名:puinl3c6yrf8  

这个覆盖paint方法就可以了。

我帮你写好了,我采用的方法是:把内容画在一个JPanel里,然后用setCo读ntentPane添加到了JFrame上,这样做是因为**问题:JFrame有边框,绘制组件问答的时候坐标是算边框占位的,但是drawLine的时候是不算的,为了统一算边框,就用了这个办法。

下面是两个文件,第一个MyFrame是一个完整的工粳MyFrame因为继承了JFrame,用起来和JFr型迫质规汽再光贵ame一样用,另外提供了一个接口,addComponent(JComponent)方法可以向里添加组件,会自动连线的。你只要importui就可以用了。

然后第二个是测试类,可以看到我在setVisible之后添加的组件,地它也能正确显示,明addCom基青入准皮一律烟ponent方法可握信记甲吸阶率以随时调用,不用另外刷新。

------------------------表皮左与走阶----MyFrame.j**a--准种第试纪父走席以---------------------------
packageui;

importj**a.线那思材称啊心扬awt.*;
importj**ax.swing.*;
importj**a.util.*;

classMyPanelextendsJPanel{
privateVector<JComponent>comps;

publicMyPanel(){
comps=newVe选紧洲答编ctor<JComponent>();
setLayout(**ll);
}

publicvoidpaint(Graphicsg){
g.setColor(Color.BLACK);
for(inti=1;i<comps.size();取乙奏称底i++){
g.drawLine(comps.get(0).getLocati行诗发法才线自各哪为on().x+comps.get(0).getSize().width/2,
comps.get(0)护饭次及逐.getLocation().y+comps.get(0).get倍盟Size().heigh配欢绿括光费象概你t/2,
comps.get(i).getLocation().x+comps.get(i).getSi皮远乡ze().width/2,
comps.get(i).getLocation().y+comps.get(i).getSize().height/2);
}
super.paintComponents(g);
}

publicvoidaddComp古内类愿应校装移角原onent(JComponentcomp){
comp.setOpaque(true);
comps.add(comp);
add(comp);
repaint();
}
}

publicclassMyFrameextendsJFrame{
privateMyPanelmp;

publicMy少赶求留离Frame(){
setDefaultCloseOperation(JFrame.EXIT_ON_CLO**);
mp=newMyPanel();
setContentPane(mp);
}

publicvoidaddComponent(JComponentcomp){
mp.addComponent(comp);
}
}

----------------稳压刚特历难------------TestMyFrame.j**a-----------------------------
importui.*;
importj**ax.swing.*;
importj**ax.swing.border.*;

publicclassTestMyFrame{
publicstaticvoidmain(Stringargs[]){
MyFramemf=newMyFrame();
mf.setSize(500,500);
mf.setLocationRelativeTo(**ll);
mf.setVisible(true);
testAddComponent(mf);
}

publicstaticvoidtestAddComponent(MyFramemf){
JLabell1=newJLabel("l1");
l1.setBorder(newEtchedBorder());
l1.setBounds(200,100,20,20);
mf.addComponent(l1);

JLabell2=newJLabel("l2");
l2.setBounds(100,150,20,20);
l2.setBorder(newEtchedBorder());
mf.addComponent(l2);

JLabell3=newJLabel("l3");
l3.setBounds(150,150,20,20);
l3.setBorder(newEtchedBorder());
mf.addComponent(l3);

JLabell4=newJLabel("l4");
l4.setBounds(200,150,20,20);
l4.setBorder(newEtchedBorder());
mf.addComponent(l4);
}
}