如下面的代码所示,我从数据库中获取了x和y值。然后将它们存储在数组x
中。之后,我试图在框架上绘制这条线,但它没有被绘制。我如何在Frame上画线?
public class TestFrame{
static JFrame test;
public static void main(String ar[]){
test=new JFrame("Test");
JButton openLine=new JButton(new AbstractAction("Open Line"){
public void actionPerformed(ActionEvent e) {
String lineId=JOptionPane.showInputDialog("Enter Line id");
ImageComponent image=new ImageComponent();
image.openLine(lineId);
}
});
test.add(openLine, BorderLayout.NORTH);
test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
test.setSize(600,600);
test.setVisible(true);
}
static class ImageComponent extends JComponent{
static int[] x=new int[100];
static ArrayList al=new ArrayList();
public void openLine(String line_id){
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:image");
Statement pstm=con.createStatement();
ResultSet rs=pstm.executeQuery("select * from Line where ID= '"+line_id+"'");
while(rs.next()){
x[0]=rs.getInt(3);
x[1]=rs.getInt(4);
x[2]=rs.getInt(5);
x[3]=rs.getInt(6);
al.add(x);
}
repaint();
} catch (Exception ex) {
System.out.println("Exception : "+ex);
}
}
public Graphics2D gd;
Line2D[] line=new Line2D[100];
protected void paintComponent(Graphics g) {
super.paintComponent(g);
gd=(Graphics2D)g;
gd.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
for(int i=0;i<al.size();i++){
line[i]=new Line2D.Double(x[0], x[1],x[2],x[3]);
gd.draw(line[i]);
}
}
}
}
答案 0 :(得分:4)
以下是一种使用BufferedImage
as a rendering surface的方法。
该问题中的OP询问了applet,但我在选项窗格中显示了该图像。它也非常适合在框架等中显示,而不会混淆是否覆盖paint(Graphics)
或paintComponent(Graphics)
。 ;)
答案 1 :(得分:1)
您可以使用Graphics
对象并覆盖paint()
方法,如下所示:
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setPaint(Color.gray);
int x = 5;
int y = 7;
g2.draw(new Line2D.Double(x, y, 200, 200));
g2.drawString("Line2D", x, 250);
}
取自here
答案 2 :(得分:1)
您不应该直接在JFrame上。 JFrame主体中的所有渲染都在contentpane中完成。菜单内容在JMenuBar中完成
答案 3 :(得分:1)
一个问题是,每次单击按钮时都会创建一个新的ImageComponent,但它不会添加到您的框架中。 另一个是你填写了一个arraylist(al)但是没有用它来实际绘制你的线。
这适用于x [0],x [1],x [2],x [3]的虚拟值:
static JFrame test;
static ImageComponent image = new ImageComponent(); //declared as a class member
public static void main(String ar[]) {
test = new JFrame("Test");
JButton openLine = new JButton(new AbstractAction("Open Line") {
public void actionPerformed(ActionEvent e) {
String lineId = JOptionPane.showInputDialog("Enter Line id");
image.openLine(lineId);
}
});
test.add(openLine, BorderLayout.NORTH);
test.add(image); //ADD THE IMAGE TO THE FRAME
image.setVisible(true);
test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
test.setSize(600, 600);
test.setVisible(true);
}