-2
import java.io.*;
import java.awt.*;
import org.xml.sax.*;
import java.awt.event.*;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.xml.parsers.*;
import org.xml.sax.helpers.DefaultHandler;
public class ch17_05 extends DefaultHandler
{
static int totalFigures = 0;
static int x[] = new int[100];
static int y[] = new int[100];
static int width[] = new int[100];
public static void main(String args[])
{
ch17_05 obj = new ch17_05();
obj.childLoop("C:\\Users\\xxxx\\Desktop\\ch17_04.xml");
AppFrame frame = new AppFrame(totalFigures, x, y, width);
frame.setSize(400, 400);
frame.addWindowListener(new WindowAdapter() {public void
windowClosing(WindowEvent e) {System.exit(0);}});
frame.show();
}
public void childLoop(String uri)
{
DefaultHandler defaultHandler = this;
SAXParserFactory factory = SAXParserFactory.newInstance();
try {
SAXParser saxParser = factory.newSAXParser();
saxParser.parse(new File(uri), defaultHandler);
} catch (Throwable t) {}
}
public void startElement(String uri, String localName,
String qualifiedName, Attributes attrs)
{
if (qualifiedName.equals("square")) {
x[totalFigures] = Integer.parseInt(attrs.getValue("x"));
y[totalFigures] = Integer.parseInt(attrs.getValue("y"));
width[totalFigures] = Integer.parseInt(attrs.getValue("width"));
totalFigures++;
}
}
public void warning(SAXParseException exception)
{
System.err.println("Warning: " +
exception.getMessage());
}
public void error(SAXParseException exception)
{
System.err.println("Error: " +
exception.getMessage());
}
public void fatalError(SAXParseException exception)
{
System.err.println("Fatal error: " +
exception.getMessage());
}
}
class AppFrame extends Frame
{
/**
*
*/
private static final long serialVersionUID = 1L;
int totalFigures;
int[] xValues;
int[] yValues;
int[] widthValues;
public AppFrame(int number, int[] x, int[] y, int[] width)
{
totalFigures = number;
xValues = x;
yValues = y;
widthValues = width;
final JButton[] buttons = new JButton[totalFigures];
for(int loopIndex = 0; loopIndex < totalFigures; loopIndex++){
//System.out.println(" "+xValues[loopIndex]);
buttons[loopIndex] = new JButton(""+loopIndex);
buttons[loopIndex].setBounds(xValues[loopIndex], yValues[loopIndex],widthValues[loopIndex], widthValues[loopIndex]);
add(buttons[loopIndex]);
System.out.println(xValues[loopIndex]);
}
}
/* public void paint(Graphics g)
{
for(int loopIndex = 0; loopIndex < totalFigures; loopIndex++){
g.drawRect(xValues[loopIndex], yValues[loopIndex],
widthValues[loopIndex], widthValues[loopIndex]);
}
}*/
}
這是我的xml文件:在這裏,我解析XML在Java然後製作的JButton
<?xml version = "1.0" encoding="UTF-8"?>
<!DOCTYPE document [
<!ELEMENT document (square)*>
<!ELEMENT square EMPTY>
<!ATTLIST square
x CDATA #IMPLIED
y CDATA #IMPLIED
width CDATA #IMPLIED>
]>
<document>
<square x='10' y='130' width='50' />
<square x='140' y='180' width='15' />
</document>
第一個按鈕顯示正確地,第二按鈕顯示整個幀。 請儘快給出答案。
這裏我解析XML並在Java中製作Jbutton。
你究竟想要達到什麼目的?你是否遇到過這個問題?你得到的結果與你得到的結果有什麼不同? – npinti