Java JDialogs如何在两者之间传递信息?

时间:2014-01-10 02:21:11

标签: java swing jframe jdialog

在寻找3个小时的答案之后,我即将放弃这个想法:

我正在制作一个显示Twitch流光的追随者的应用程序。 我想补充的几个功能:

显示框是与控制框架分开的窗口。 我正在尝试使用(JFrame作为显示窗口)(JDialog作为控件框架) 而且:设置在另一个JDialog中(这个有Modal(true)) 设置需要能够发送JFrame信息,例如:“username”和“text color” 只有点击控件JDialog上的“设置”才能弹出设置JDialog。 单击“保存设置”或X时,它将设置为可见(false)。 在控件上,JDialog(b_console)需要接收错误消息和类似的信息。 在同一个JDialog上,“填充”需要接收跟随者数量等等。

以下是我的代码,涉及上面列出的转移:

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);
        }
    }
}

2 个答案:

答案 0 :(得分:2)

我试图修复你的程序,但我不太确定它的流程。所以我创造了另一个简单的。我所做的是将标签从主框架传递给对话框的构造函数。在对话框中,我获取了这些标签并使用在其文本字段中输入的文本进行了更改。如果在从对话框中写入文本后按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);
            }
        });
    }
}

enter image description here

答案 1 :(得分:0)

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