2

如何使用更改的内容更新 Java 框架?

我想更新一个框架或只是更新内容的面板。我有什么用

这是我想重新验证框架或重新绘制主面板或任何可行的地方,我已经尝试了很多东西,但都没有奏效。

public void actionPerformed(ActionEvent e) {
        //System.out.println(e.getActionCommand());
        if (e.getActionCommand().equals("advance")) {
            multi--;
                    // Revalidate update repaint here <<<<<<<<<<<<<<<<<<<
        }
        else if (e.getActionCommand().equals("reverse")) {
            multi++;
                    // Revalidate update repaint here <<<<<<<<<<<<<<<<<<<       
        }
        else {
            openURL(e.getActionCommand());
        }

        }

这是整个java文件

/*
 *
 *
 */ 

package build;

import java.lang.reflect.Method;
import javax.swing.JOptionPane;
import java.util.Arrays;
import java.util.*;
import java.util.ArrayList;

import javax.swing.*;
import javax.swing.AbstractButton;
import javax.swing.JScrollPane;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.ImageIcon;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;

/* 
 * ButtonDemo.java requires the following files:
 *   images/right.gif
 *   images/middle.gif
 *   images/left.gif
 */
public class StockTable extends JPanel
                        implements ActionListener {
    static int multi = 1;
    int roll = 0;
    static TextVars textvars = new TextVars();
    static final String[] browsers = { "firefox", "opera", "konqueror", "epiphany",
            "seamonkey", "galeon", "kazehakase", "mozilla", "netscape" };
    JFrame frame;
    JPanel mainpanel, panel1, panel2, panel3, panel4, panel2left, panel2center, panel2right;
        JButton stknames_btn[] = new JButton[textvars.getNumberOfStocks()];
    JLabel label[] = new JLabel[textvars.getNumberOfStocks()];
    JLabel headlabel, dayspan, namelabel;
    JRadioButton radioButton;
    JButton button;
    JScrollPane scrollpane;
    int wid = 825;
    public JPanel createContentPane() {

        mainpanel = new JPanel();
        mainpanel.setPreferredSize(new Dimension(wid, 800));
        mainpanel.setLayout(new GridBagLayout());
        GridBagConstraints c = new GridBagConstraints();
        panel1 = new JPanel();
        panel1.setPreferredSize(new Dimension(wid, 25));
        c.gridx = 0;
        c.gridy = 0;
        c.insets = new Insets(0,0,0,0);
        mainpanel.add(panel1, c);

        // Panel 2------------
        panel2 = new JPanel();
        panel2.setPreferredSize(new Dimension(wid, 51));
        c.gridx = 0;
        c.gridy = 1;
        c.insets = new Insets(0,0,0,0);
        mainpanel.add(panel2, c);
        panel2left = new JPanel();
        panel2left.setPreferredSize(new Dimension(270, 51));
        c.gridx = 0;
        c.gridy = 1;
        c.insets = new Insets(0,0,0,0);
        panel2.add(panel2left, c);
        panel2center = new JPanel();
        panel2center.setPreferredSize(new Dimension(258, 51));
        c.gridx = 1;
        c.gridy = 1;
        c.insets = new Insets(0,0,0,0);
        panel2.add(panel2center, c);
        panel2right = new JPanel();
        panel2right.setPreferredSize(new Dimension(270, 51));
        c.gridx = 2;
        c.gridy = 1;
        c.insets = new Insets(0,0,0,0);
        panel2.add(panel2right, c);
        // ------------------

        panel3 = new JPanel();
        panel3.setLayout(new GridBagLayout());
        scrollpane = new JScrollPane(panel3);
        scrollpane.setPreferredSize(new Dimension(wid, 675));
        c.gridx = 0;
        c.gridy = 2;
        c.insets = new Insets(0,0,0,0);
        mainpanel.add(scrollpane, c);


            ImageIcon leftButtonIcon = createImageIcon("images/right.gif");

            //b1 = new JButton("Disable middle button", leftButtonIcon);
            //b1.setVerticalTextPosition(AbstractButton.CENTER);
            //b1.setHorizontalTextPosition(AbstractButton.LEADING); //aka LEFT, for left-to-right locales
            //b1.setMnemonic(KeyEvent.VK_D);
            //b1.setActionCommand("disable");


            //Listen for actions on buttons 1
            //b1.addActionListener(this);

            //b1.setToolTipText("Click this button to disable the middle button.");

            //Add Components to this container, using the default FlowLayout.
            //add(b1);


        headlabel = new JLabel("hellorow1");
            c.gridx = 0;       
            c.gridy = 0;       
        c.insets = new Insets(0, 0, 0, 0);
        panel1.add(headlabel, c);

        radioButton = new JRadioButton("Percentage");
            c.gridx = 2;       
            c.gridy = 0;       
        c.insets = new Insets(0, 0, 0, 0);
        panel1.add(radioButton, c);

        radioButton = new JRadioButton("Days Range");
            c.gridx = 3;      
            c.gridy = 0;      
        c.insets = new Insets(0, 0, 0, 0);
        panel1.add(radioButton, c);

        radioButton = new JRadioButton("Open / Close");
            c.gridx = 4;       
            c.gridy = 0;       
        c.insets = new Insets(0, 0, 0,0 );
        panel1.add(radioButton, c);


        button = new JButton("<<");
        button.setPreferredSize(new Dimension(50, 50));
        button.setActionCommand("reverse");
        button.addActionListener(this);
            c.gridx = 0;       
            c.gridy = 1;       
        c.insets = new Insets(0, 0, 0, 0);
            panel2left.add(button, c);

        dayspan = new JLabel("hellorow2"); 
        dayspan.setHorizontalAlignment(JLabel.CENTER); 
        dayspan.setVerticalAlignment(JLabel.CENTER);
        dayspan.setPreferredSize(new Dimension(270, 50)); 
            c.gridx = 1;       
            c.gridy = 1;
        c.insets = new Insets(0, 0, 0, 0);       
            panel2center.add(dayspan, c);

        button = new JButton(">>");
        button.setPreferredSize(new Dimension(50, 50));
        button.setActionCommand("advance");
        button.addActionListener(this);
        if (multi == 0) {
            button.setEnabled(false);
        }
        else {
            button.setEnabled(true);
        }
            c.gridx = 2;       
            c.gridy = 1;       
        c.insets = new Insets(0, 0, 0, 0);
            panel2right.add(button, c);

        int availSpace_int = textvars.getStocks().size()-textvars.getNumberOfStocks()*7;

        ArrayList<String[]> stocknames = textvars.getStockNames();
        ArrayList<String[]> stocks = textvars.getStocks();
        for (int column = 0; column < 8; column++) {
            for (int row = 0; row < textvars.getNumberOfStocks(); row++) { 

                if (column==0) {
                    if (row==0) {
                        namelabel = new JLabel(stocknames.get(0)[0]); 
                        namelabel.setVerticalAlignment(JLabel.CENTER);
                        namelabel.setHorizontalAlignment(JLabel.CENTER);
                        namelabel.setPreferredSize(new Dimension(100, 25));
                        c.gridx = column;
                        c.gridy = row;
                        c.insets = new Insets(0, 0, 0, 0);
                        panel3.add(namelabel, c);
                    }
                    else {
                        stknames_btn[row] = new JButton(stocknames.get(row)[0], leftButtonIcon); 
                        stknames_btn[row].setVerticalTextPosition(AbstractButton.CENTER);
                        stknames_btn[row].setActionCommand(stocknames.get(row)[1]); 
                        stknames_btn[row].addActionListener(this);
                        stknames_btn[row].setToolTipText("go to Google Finance "+stocknames.get(row)[0]); 
                        stknames_btn[row].setPreferredSize(new Dimension(100, 25));
                        c.gridx = column;
                        c.gridy = row;
                        c.insets = new Insets(0, 0, 0, 0);
                        //scrollpane.add(stknames[row], c);
                        panel3.add(stknames_btn[row], c);
                    }
                }
                else {
                        label[row]= new JLabel(textvars.getStocks().get(columnMulti(multi))[1]);
                        label[row].setBorder(BorderFactory.createLineBorder(Color.black));
                        label[row].setVerticalAlignment(JLabel.CENTER);
                        label[row].setHorizontalAlignment(JLabel.CENTER);
                        label[row].setPreferredSize(new Dimension(100, 25));    
                        c.gridx = column;
                        c.gridy = row;
                        c.insets = new Insets(0,0,0,0);
                        panel3.add(label[row], c);
                }

            }
        }

        return mainpanel;
        }

        public void actionPerformed(ActionEvent e) {
        //System.out.println(e.getActionCommand());
        if (e.getActionCommand().equals("advance")) {
            multi--;
        }
        else if (e.getActionCommand().equals("reverse")) {
            multi++;        
        }
        else {
            openURL(e.getActionCommand());
        }

        }

        /** Returns an ImageIcon, or null if the path was invalid. */
        protected static ImageIcon createImageIcon(String path) {
            java.net.URL imgURL = StockTable.class.getResource(path);
            if (imgURL != null) {
                    return new ImageIcon(imgURL);
            } else {
                    System.err.println("Couldn't find file: " + path);
                    return null;
            }
        }

    public static void openURL(String url) {
        String osName = System.getProperty("os.name");
        try {
            if (osName.startsWith("Mac OS")) {
                Class<?> fileMgr = Class.forName("com.apple.eio.FileManager");
                Method openURL = fileMgr.getDeclaredMethod("openURL",
                    new Class[] {String.class});
                openURL.invoke(null, new Object[] {url});
                        }
            else if (osName.startsWith("Windows")) {    
                Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + url);
            }
            else { //assume Unix or Linux
                boolean found = false;
                for (String browser : browsers)
                    if (!found) {
                        found = Runtime.getRuntime().exec(
                        new String[] {"which", browser}).waitFor() == 0;
                        if (found) 
                            Runtime.getRuntime().exec(new String[] {browser, url}); 
                    }   
                    if (!found)
                        throw new Exception(Arrays.toString(browsers));
                    }
                }   
        catch (Exception e) {   
            JOptionPane.showMessageDialog(null,
                "Error attempting to launch web browser\n" + e.toString());
        }
    }
    int reit = 0;
    int start = textvars.getStocks().size()-((textvars.getNumberOfStocks()*5)*7)-1;
    public int columnMulti(int multi) {
        reit++;
        start++;
        if (reit == textvars.getNumberOfStocks()) {
            reit = 0;
            start=start+64;
        }
        //start = start - (multi*(textvars.getNumberOfStocks()));
        return start;
    }

        /**
        * Create the GUI and show it.  For thread safety, 
        * this method should be invoked from the 
        * event-dispatching thread.
        */
        private static void createAndShowGUI() {

        //Create and set up the window.
            JFrame frame = new JFrame("Stock Table");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

            //Create and set up the content pane.
            StockTable newContentPane = new StockTable();
            //newContentPane.setOpaque(true); //content panes must be opaque
            //frame.setContentPane(newContentPane);
        frame.setContentPane(newContentPane.createContentPane());
        frame.setSize(800, 800);


            //Display the window.
            frame.pack();
            frame.setVisible(true);


        }

    public static void main(String[] args) {
            //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                    public void run() {
                        createAndShowGUI(); 
                    }
            });
        }
}
4

2 回答 2

1

当你发现自己想要基于一个小的变化“重新创建”一个 UI 时,应该会敲响警钟。在某些情况下,这将是一个好主意,但在大多数情况下,这是一个糟糕设计的标志。

让我们从...

frame.setContentPane(newContentPane.createContentPane());

这是一个坏主意。你创建一个JPanel只是为了创建另一个JPanel。突然之间,您并没有丢失 UI 的上下文。

而不是createContentPane从窗格的构造函数中简单地构造您的 UIStockTable并将其添加到框架中......更像......

frame.setContentPane(newContentPane);

摆脱面板,直接mainPanel使用。StockTable

我无法运行您的代码,但它看起来很像您试图“模拟”表格布局。相反,简化您的生活并学习使用JTable. 如果您这样做,更新表格会更加容易(更不用说看起来更好)...

于 2012-12-13T05:01:19.457 回答
0

我的建议是,如果您想更新swing component始终使用事件调度程序线程。

我认为这可能会帮助你

public void actionPerformed(ActionEvent e) {
        //System.out.println(e.getActionCommand());
        if (e.getActionCommand().equals("advance")) {
            multi--;

                   Runnable edt = new Runnable() {
                   public void run() {
                       /*Update your components here*/
                       }
                   };

            SwingUtilities.invokeLater(edt);
          }
        else if (e.getActionCommand().equals("reverse")) {
            multi++;
            Runnable edt= new Runnable() {
                  public void run() {
                      /*Update your components here*/
                     }
                };

                 SwingUtilities.invokeLater(edt);
        }
        else {
            openURL(e.getActionCommand());
        }

        }
    }
于 2012-12-13T05:01:46.263 回答