【问题标题】:Java JDialogs How To Pass Information Between?Java JDialogs之间如何传递信息?
【发布时间】:2014-01-10 02:21:11
【问题描述】:

找了3个小时的答案,我都快要放弃这个想法了:

我正在制作一个显示 Twitch 主播关注者的应用程序。 我正在尝试添加的几个功能:

显示框架是一个独立于控件框架的窗口。 我正在尝试使用(JFrame 作为显示窗口)(JDialog 作为控件框架) 此外:设置在另一个 JDialog 中(这个有 Modal(true)) 设置需要能够发送 JFrame 信息,例如:“用户名”和“文本颜色” 并且设置 JDialog 只会通过单击控件 JDialog 上的“设置”弹出。 当您单击“保存设置”或 X 时,它将 setVisible(false)。 在控件上,JDialog (b_console) 需要接收错误消息和类似的信息。 在同一个 JDialog 上,“filler”需要接收关注者数量之类的信息。

下面是我的涉及上述转移的代码:

package javafollowernotifier;
import java.awt.*;
import java.awt.event.*;
import java.awt.Graphics.*;
import javax.swing.*;
import java.io.*;
import java.net.URL;

public class JavaFollowerNotifier extends JFrame implements ComponentListener
{
    Settings settings = new Settings();
    ControlPanel ctrlPnl = new ControlPanel();

    public JavaFollowerNotifier()
    {        
        try
        {
            settings.readSettings();
        }
        catch(Exception e)
        {
            ctrlPnl.b_console.setText("Error");
            System.out.println(e);
        }
    }

    public void grabFollower()
    {
        ctrlPnl.b_console.setText("Retrieving Info...");

        try
        {
            URL twitch = new URL("https://api.twitch.tv/kraken/channels/" + savedSettings[1] + "/follows?limit=1&offset=0");

            ctrlPnl.b_console.setText("Retrieved");
        }
        catch(Exception e)
        {
            ctrlPnl.b_console.setText("Error");
            System.out.println(e);
        }
    }

    public void grabStats()
    {            
        ctrlPnl.b_console.setText("Retrieving Info...");

        try
        {
            URL twitch = new URL("https://api.twitch.tv/kraken/channels/" + savedSettings[1] + "/follows?limit=1&offset=0");

            ctrlPnl.filler.setText("Followers: " + totalFollowers + "\nLatest: " + lastFollower);
            ctrlPnl.b_console.setText("Retrieved");
        }
        catch(Exception e)
        {
            ctrlPnl.b_console.setText("Error");
            System.out.println(e);
        }
    }

    public void componentMoved(ComponentEvent arg0)
    {
        //this is only to *attach this JDialog to the JFrame and make it move together my plan is to have it undecorated as well
        int x = this.getX() + this.getWidth();
        int y = this.getY();
        ctrlPnl.movePanel(x, y);
    }

    public void paint(Graphics g)
    {
        if(clearPaint == false)
        {
            //any "savedSettings[n]" are saved in Settings.java (just not in this version)
            g.setColor(Color.decode(savedSettings[3]));
            scaledFont = scaleFont(follower + " followed!", bounds, g, new Font(savedSettings[2], Font.PLAIN, 200));
        }
    }
}



package javafollowernotifier;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.imageio.ImageIO;
import javax.swing.*;

public class Settings extends JDialog implements ActionListener
{
    JavaFollowerNotifier jfollow = new JavaFollowerNotifier();
    ControlPanel ctrlPnl = new ControlPanel();

    //here are the settings mention above
    String[] savedSettings = {"imgs/b_b.jpg","username","font","color","Nightbot"};

    public Settings()
    {         
        try
        {
           UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        }
        catch (Exception e)
        {
            ctrlPnl.b_console.setText("Error");
            System.out.println(e);
        }
    }

    public void saveSettings()
    {
            savedSettings[4] = jfollow.lastFollower;

        try
        {
            PrintWriter save = new PrintWriter("config.cfg");
            ctrlPnl.b_console.setText("Saving...");
            for(int i = 0; i < 5; i++)
            {
                save.println(savedSettings[i]);
            }
            save.close();
            ctrlPnl.b_console.setText("Saved");
        }
        catch(Exception e)
        {
            ctrlPnl.b_console.setText("Error");
            System.out.println(e);
            canClose = false;
        }

        readSettings();
        this.repaint();
    }

    public void readSettings()
    {
        ctrlPnl.b_console.setText("Loading...");

        try
        {
        }
        catch(Exception e)
        {
            ctrlPnl.b_console.setText("Error");
            System.out.println(e);
        }

        jfollow.lastFollower = savedSettings[4];

        try
        {
        }
        catch(Exception e)
        {
            ctrlPnl.b_console.setText("Error");
            System.out.println(e);
        }

        ctrlPnl.b_console.setText("Loaded Settings");
    }
}



package javafollowernotifier;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class ControlPanel extends JDialog implements ActionListener
{      
    public ControlPanel()
    {
        try
        {
        }
        catch (Exception e)
        {
            b_console.setText("Error");
            System.out.println(e);
        }
    }

    public void movePanel(int x, int y)
    {
        //here is where i *attach the JDialog to the JFrame
        controlPanel.setLocation(x, y);
    }

    public void actionPerformed(ActionEvent ie)
    {
        if(ie.getSource() == b_settings)
        {
            settings.frame.setVisible(true);
        }
    }
}

【问题讨论】:

  • 真正的问题/疑问是什么?
  • 是的,@peeskillet 已经问过了。你有什么问题?
  • 也说明你需要通过这样的小麦信息
  • 我已经定义了需要传递的信息:组件,以便我可以从另一个类中使用 .setText(),也可以来回传递变量。我的问题是,如果我这样设置:我得到一个无限循环。但是如果我只有主类调用他们两个:他们不能相互转移!

标签: java swing jframe jdialog


【解决方案1】:

我试图修复你的程序,但我不太确定它的流程。所以我创建了另一个简单的。我所做的是将标签从主框架传递给对话框的构造函数。在对话框中,我使用了这些标签并使用在其文本字段中输入的文本对其进行了更改。如果您在从对话框中写入文本后按 Enter,您将看到框架中的文本发生变化

public class JavaFollowerNotifier1 extends JFrame{

    private JLabel controlDialogLabel = new JLabel("  ");
    private JLabel settingDialogLabel = new JLabel("  ");
    private ControlDialog control;
    private SettingsDialog settings;

    public JavaFollowerNotifier1() {
        control = new ControlDialog(this, true, controlDialogLabel);
        settings = new SettingsDialog(this, true, settingDialogLabel);

....

class ControlDialog extends JDialog {
    private JLabel label;

    public ControlDialog(final Frame frame, boolean modal, final JLabel label) {
        super(frame, modal);
        this.label = label;

....

class SettingsDialog extends JDialog {
    private JLabel label;

    public SettingsDialog(final Frame frame, boolean modal, final JLabel label) {
        super(frame, modal);
        this.label = label;

测试一下,如果您有任何问题,请告诉我

import java.awt.BorderLayout;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

public class JavaFollowerNotifier1 extends JFrame{

    private JLabel controlDialogLabel = new JLabel("  ");
    private JLabel settingDialogLabel = new JLabel("  ");

    private JButton showControl = new JButton("Show Control");
    private JButton showSetting = new JButton("Show Settings");

    private ControlDialog control;
    private SettingsDialog settings;

    public JavaFollowerNotifier1() {
        control = new ControlDialog(this, true, controlDialogLabel);
        settings = new SettingsDialog(this, true, settingDialogLabel);


        showControl.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e) {
                control.setVisible(true);
            }
        });
        showSetting.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e) {
                settings.setVisible(true);
            }
        });

        JPanel buttonPanel = new JPanel();
        buttonPanel.add(showControl);
        buttonPanel.add(showSetting);

        add(buttonPanel, BorderLayout.SOUTH);
        add(controlDialogLabel, BorderLayout.NORTH);
        add(settingDialogLabel, BorderLayout.CENTER);

        pack();
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new JavaFollowerNotifier1();
            }
        });
    }

}

class ControlDialog extends JDialog {
    private JLabel label;
    private JTextField field = new JTextField(15);
    private JButton button = new JButton("Close");
    private String s = "";

    public ControlDialog(final Frame frame, boolean modal, final JLabel label) {
        super(frame, modal);
        this.label = label;

        setLayout(new BorderLayout());
        add(field, BorderLayout.NORTH);
        add(button, BorderLayout.CENTER);

        pack();
        setLocationRelativeTo(frame);

        field.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e) {
                s = field.getText();
                label.setText("Message from Control Dialog: " + s);
            }
        });
        button.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e) {
                ControlDialog.this.setVisible(false);
            }
        });
    }
}

class SettingsDialog extends JDialog {
    private JLabel label;
    private JTextField field = new JTextField(15);
    private JButton button = new JButton("Close");
    private String s = "";

    public SettingsDialog(final Frame frame, boolean modal, final JLabel label) {
        super(frame, modal);
        this.label = label;

        setLayout(new BorderLayout());
        add(field, BorderLayout.NORTH);
        add(button, BorderLayout.CENTER);

        pack();
        setLocationRelativeTo(frame);

        field.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e) {
                s = field.getText();
                label.setText("Message from Settings Dialog: " + s);
            }
        });
        button.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e) {
                SettingsDialog.this.setVisible(false);
            }
        });
    }
}

【讨论】:

    【解决方案2】:

    通常,当我构建使用模式对话框收集用户输入的 GUI 时,我会构建自己的类,该类扩展 JDialog 或在某些情况下扩展 JFrame。在那个类中,我为一个我通常称为 DialgResult 的对象公开了一个 getter 方法。该对象充当我从用户那里收集的输入的模型。在具有按钮的类中,或者触发向用户询问信息的任何控件中,我创建它,将其显示为模式对话框,然后当它关闭时,我使用相同的 getter 检索对象。

    这是一个非常原始的例子:

    package arg;
    
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    
    import javax.swing.BoxLayout;
    import javax.swing.JButton;
    import javax.swing.JDialog;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    
    public class asdfas extends JFrame {
    
    
    public static void main(String[] args) {
        asdfas ex = new asdfas();
        ex.setVisible(true);
    }
    
    public asdfas() {
        init();
    }
    
    private void init() {
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        this.setBounds(100,100,200,200);
    
        final JButton button = new JButton("Show modal dialog");
        button.addActionListener( new ActionListener() {
    
            @Override
            public void actionPerformed(ActionEvent arg0) {
                Dialog d = new Dialog();
                d.setVisible(true);         
    
                button.setText(d.getDialogResult().value);
                revalidate();
                repaint();
            }
        });
    
        this.add(button);       
    }
    class DialogResult {
        public String value;
    }
    class Dialog extends JDialog {
        JTextField tf = new JTextField(20);
        private DialogResult result = new DialogResult();
        public Dialog() {
            super();
            init();
        }
    
        private void init() {
            this.setModal(true);
    
            this.setSize(new Dimension(100,100));
            JButton ok = new JButton("ok");
            ok.addActionListener( new ActionListener () {
    
                @Override
                public void actionPerformed(ActionEvent arg0) {
                    result = new DialogResult();
                    result.value = tf.getText();
                    setVisible(false);
                }
    
            });
            JPanel p = new JPanel();
            p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS));
            p.add(tf);
            p.add(ok);
            this.add(p);
        }
    
        public DialogResult getDialogResult() {
            return result;
        }
    }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-25
      • 2022-01-01
      • 2018-01-25
      相关资源
      最近更新 更多