在半透明的秋千窗口内创建jtable

时间:2014-07-30 08:27:43

标签: java swing jtable

我需要在java中创建一个半透明的swing窗口,里面有一个表和一个按钮。表格内容是从xml文件中导入的..我的代码就是这个

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import static java.awt.GraphicsDevice.WindowTranslucency.*;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class Swings extends JFrame {
    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    public File xml = null;
    public Document dom = null;
    public JScrollPane jScrollPane1;
    public DefaultTableModel model;
    public JTable jTable1;
    public JButton update_button;

    public Swings() {
        setUndecorated(true);
        setBackground(new Color(0, 0, 0, 0));
        setSize(new Dimension(600, 500));
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        // statusLabel.setSize(350,100);
        JPanel panel = new JPanel() {
            private static final long serialVersionUID = 1L;

            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                if (g instanceof Graphics2D) {
                    final int R = 220;
                    final int G = 220;
                    final int B = 250;
                    Paint p = new GradientPaint(0.0f, 0.0f, new Color(R, G, B, 0), 0.0f, getHeight(), new Color(R, G, B, 255), true);
                    Graphics2D g2d = (Graphics2D) g;
                    g2d.setPaint(p);
                    g2d.fillRect(0, 0, getWidth(), getHeight());
                    Font font = new Font("Serif", Font.PLAIN, 45);
                    g2d.setFont(font);
                    g2d.Color(Color.red);
                    g2d.drawString("Service Now Notification", 40, 120);
                }
            }
        };
        xml = new File(System.getProperty("user.dir") + File.separator + "Html1.xml");
        installGUI();
        setContentPane(panel);
        setLayout(new GridBagLayout());
        add(jtable1);
        add(update_button);
    }

    public void installGUI() {
        Container ctr = getContentPane();
        ctr.setLayout(new BorderLayout());
        model = new DefaultTableModel() {
            private static final long serialVersionUID = 1L;

            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        // creates an instance of the table class and sets it up in a scrollpane
        jTable1 = new JTable(model);
        jTable1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        jScrollPane1 = new JScrollPane(jTable1);
        ctr.add(BorderLayout.CENTER, jScrollPane1);
        // add some columns
        model.addColumn("Number");
        model.addColumn("Priority");
        model.addColumn("State");
        model.addColumn("Assigned");
        model.addColumn("Short_desc");
        model.addColumn("Task");
        if (xml.exists() && xml.length() != 0) {
            dom = parseFile(xml);
            insertTableRows(model, dom);
        }
    }

    // creates an instance of a Document object
    public Document parseFile(File file) {
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            dom = (Document) builder.parse(file);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return dom;
    }

    public void insertTableRows(DefaultTableModel tableModel, Document doc) {
        Element root = doc.getDocumentElement();
        NodeList list = root.getElementsByTagName("MS");
        for (int i = 0; i < list.getLength(); ++i) {
            Element e = (Element) list.item(i);
            if (e.getNodeType() == Element.ELEMENT_NODE) {
                Object[] row = { getArticleInfo("S", e) };
                tableModel.addRow(row);
            }
        }
        tableModel.fireTableStructureChanged();
        tableModel.fireTableDataChanged();
    }

    public Object getArticleInfo(String tagName, Element elem) {
        NodeList list = elem.getElementsByTagName(tagName);
        for (int i = 0; i < list.getLength(); ++i) {
            Node node = (Node) list.item(i);
            if (node.getNodeType() == Node.ELEMENT_NODE) {
                Node child = (Node) node.getFirstChild();
                return child.getTextContent().trim();
            }
            return null;
        }
        return null;
    }

    public static void main(String[] args) {
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        GraphicsDevice gd = ge.getDefaultScreenDevice();
        boolean isPerPixelTranslucencySupported = gd.isWindowTranslucencySupported(PERPIXEL_TRANSLUCENT);
        if (!isPerPixelTranslucencySupported) {
            System.out.println("Per-pixel translucency is not supported");
            System.exit(0);
        }
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                Swing gtw = new Swing();
                // gtw.runn();
                gtw.setVisible(true);
            }
        });
    }
}

xml文件内容是:

<Objs Version="1.1.0.1" xmlns="http://schemas.microsoft.com/powershell/2004/04">
    <Obj RefId="0">
        <TN RefId="0">
            <T>Selected.System.Management.Automation.PSCustomObject</T> 
            <T>System.Management.Automation.PSCustomObject</T> 
            <T>System.Object</T> 
        </TN>
        <MS>
            <S N="Number">INC0811168</S> 
            <S N="Priority">2 - High</S> 
            <S N="State">Assigned</S> 
            <S N="Assigned">New</S> 
            <S N="Short_desc">Review Ad-Hoc Service Request for Lavon A Gudmundson</S> 
            <S N="Task">Catalog Task</S> 
        </MS>
    </Obj>
</Objs>

我正在获得一个半透明的通知窗口,其中有一个按钮作为输出..

1 个答案:

答案 0 :(得分:1)

暂时忽略透明窗口(看起来你已经弄明白了),基本上有两种方法可以根据你想要实现的目标来实现你想要实现的目标,但是,基本方法是阅读XML文件仍然是一样的......

您可以将XML数据预加载到匹配的POJO中,并将它们添加到某种管理结构中(例如List)并将这些值应用于TableModel或包装{{围绕XML文档本身建模并让它管理整个过程...

此示例执行后者,但分离加载过程并执行前者并不需要太多...

XMLTable

TableModel

您可能想了解一些关于透明方法的说明...... import java.awt.EventQueue; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; import javax.swing.table.AbstractTableModel; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpression; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; public class XMLTableExample { public static void main(String[] args) { new XMLTableExample(); } public XMLTableExample() { EventQueue.invokeLater(new Runnable() { @Override public void run() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { ex.printStackTrace(); } JTable table = new JTable(); try { table.setModel(new XMLTableModel(new File("Html1.xml"))); } catch (ParserConfigurationException | SAXException | IOException | XPathExpressionException ex) { ex.printStackTrace(); } JFrame frame = new JFrame("Testing"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(new JScrollPane(table)); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } }); } public static class XMLTableModel extends AbstractTableModel { protected static final String[] COLUMN_NAMES = { "Number", "Priority", "State", "Assigned", "Description", "Task" }; private List<MSEntity> rows; public XMLTableModel(File file) throws ParserConfigurationException, SAXException, IOException, XPathExpressionException { rows = new ArrayList<>(25); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document dom = db.parse(file); setDocument(dom); } protected String getMSValue(Node msNode, String name) throws XPathExpressionException { XPath xpath = XPathFactory.newInstance().newXPath(); XPathExpression expression = xpath.compile("S[@N='" + name + "']"); Node sNode = (Node)expression.evaluate(msNode, XPathConstants.NODE); return sNode != null ? sNode.getTextContent() : null; } @Override public int getRowCount() { return rows.size(); } @Override public int getColumnCount() { return COLUMN_NAMES.length; } @Override public String getColumnName(int column) { return COLUMN_NAMES[column]; } @Override public Class<?> getColumnClass(int columnIndex) { return String.class; } public MSEntity getEntityAtRow(int row) { return rows.get(row); } @Override public Object getValueAt(int rowIndex, int columnIndex) { MSEntity entity = getEntityAtRow(rowIndex); Object value = null; switch (columnIndex) { case 0: value = entity.getNumber(); break; case 1: value = entity.getPriority(); break; case 2: value = entity.getState(); break; case 3: value = entity.getAssigned(); break; case 4: value = entity.getDesc(); break; case 5: value = entity.getTask(); break; } return value; } public void setDocument(Document dom) throws XPathExpressionException { XPath xpath = XPathFactory.newInstance().newXPath(); XPathExpression expression = xpath.compile("/Objs/Obj/MS"); NodeList nl = (NodeList)expression.evaluate(dom, XPathConstants.NODESET); for (int index = 0; index < nl.getLength(); index++) { Node node = nl.item(index); String number = getMSValue(node, "Number"); String priority = getMSValue(node, "Priority"); String state = getMSValue(node, "State"); String assigned = getMSValue(node, "Assigned"); String desc = getMSValue(node, "Short_desc"); String task = getMSValue(node, "Task"); MSEntity entity = new MSEntity(number, priority, state, assigned, desc, task); rows.add(entity); } fireTableDataChanged(); } public class MSEntity { private final String number; private final String priority; private final String state; private final String assigned; private final String desc; private final String task; public MSEntity(String number, String priority, String state, String assigned, String desc, String task) { this.number = number; this.priority = priority; this.state = state; this.assigned = assigned; this.desc = desc; this.task = task; } public String getAssigned() { return assigned; } public String getDesc() { return desc; } public String getNumber() { return number; } public String getPriority() { return priority; } public String getState() { return state; } public String getTask() { return task; } } } } 是不透明的,JScrollPane是不透明的,JViewport是不透明的。如果你希望看到抛出这些组件,你将不得不改变这些状态