Java从另一个JFrame获取选定的组合框 [英] Java Get Selected Combobox from Another JFrame

查看:144
本文介绍了Java从另一个JFrame获取选定的组合框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新手。对任何错误的信息或任何其他不好的东西很抱歉。



此问题是这个stackoverflow问题。我已经知道 JFrame 问题 JFrame Bad Practice 。问题是我是一个新手使用Netbeans来编码Java。我所知道的是如何使用 JFrame 来制作程序。下面是我所做的代码。请帮助我纠正它,所以我的代码的目的(设置回答类文本从 TheCombo 类选择的组合框)可以已完成。



请更正此代码(我有3个课程)。我想得到 ComboBox 选择的项目在答案类中使用。



主类:

 包测试; 

public class Testing {

public static void main(String [] args){
new TheCombo()。setVisible(true);
}

}

组合类:

 包测试; 

public class TheCombo extends javax.swing.JFrame {

public TheCombo(){
initComponents();
}

public String getItem()
{
String theItem = jComboBox1.getSelectedItem()。toString();
return theItem;
}


@SuppressWarnings(unchecked)
//< editor-fold defaultstate =collapseddesc =Generated Code>
private void initComponents(){

jComboBox1 = new javax.swing.JComboBox();
jButton1 = new javax.swing.JButton();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String [] {Item 1,Item 2,Item 3,Item 4}));

jButton1.setText(Go);
jButton1.addActionListener(new java.awt.event.ActionListener(){
public void actionPerformed(java.awt.event.ActionEvent evt){
jButton1ActionPerformed(evt);
}
});

javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane()。setLayout(layout);
layout.setHorizo​​ntalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jComboBox1,javax.swing.GroupLayout.PREFERRED_SIZE,javax.swing.GroupLayout.DEFAULT_SIZE,javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton1)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE,Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jComboBox1,javax.swing.GroupLayout.PREFERRED_SIZE,javax.swing.GroupLayout.DEFAULT_SIZE,javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton1))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE,Short.MAX_VALUE))
);

pack();
} //< / editor-fold>

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt){
new Answer()。setVisible(true);
this.dispose();
}

public static void main(String args []){
/ *设置Nimbus的外观* /
//< editor-fold defaultstate =collapseddesc =观感设置代码(可选)>
/ *如果Nimbus(在Java SE 6中引入)不可用,保持默认的外观和感觉。
*详情请参阅http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
* /
try {
for(javax.swing .UIManager.LookAndFeelInfo info:javax.swing.UIManager.getInstalledLookAndFeels()){
if(Nimbus.equals(info.getName())){
javax.swing.UIManager.setLookAndFeel .getClassName());
break;
}
}
} catch(ClassNotFoundException ex){
java.util.logging.Logger.getLogger(TheCombo.class.getName())log(java.util。 logging.Level.SEVERE,null,ex);
} catch(InstantiationException ex){
java.util.logging.Logger.getLogger(TheCombo.class.getName())。log(java.util.logging.Level.SEVERE,null,ex) ;
} catch(IllegalAccessException ex){
java.util.logging.Logger.getLogger(TheCombo.class.getName())。log(java.util.logging.Level.SEVERE,null,ex) ;
} catch(javax.swing.UnsupportedLookAndFeelException ex){
java.util.logging.Logger.getLogger(TheCombo.class.getName())。log(java.util.logging.Level.SEVERE, null,ex);
}
//< / editor-fold>

/ *创建并显示表单* /
java.awt.EventQueue.invokeLater(new Runnable(){
public void run(){
new TheCombo ().setVisible(true);
}
});
}

//变量声明 - 不要修改
private javax.swing.JButton jButton1;
private javax.swing.JComboBox jComboBox1;
//变量声明结束
}

在组合类中的ComboBox中选择项目来设置文本JTextField1):

 包测试; 

public class回答扩展javax.swing.JFrame {

TheCombo tc = new TheCombo();

public Answer(){
initComponents();

jTextField1.setText(tc.getItem());
}

@SuppressWarnings(unchecked)
//< editor-fold defaultstate =collapseddesc =Generated Code>
private void initComponents(){

jTextField1 = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

jTextField1.setHorizo​​ntalAlignment(javax.swing.JTextField.CENTER);
jTextField1.setEnabled(false);

jButton1.setText(Back);
jButton1.addActionListener(new java.awt.event.ActionListener(){
public void actionPerformed(java.awt.event.ActionEvent evt){
jButton1ActionPerformed(evt);
}
});

javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane()。setLayout(layout);
layout.setHorizo​​ntalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jTextField1,javax.swing.GroupLayout.PREFERRED_SIZE,50,javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton1)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE,Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextField1,javax.swing.GroupLayout.PREFERRED_SIZE,javax.swing.GroupLayout.DEFAULT_SIZE,javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton1))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE,Short.MAX_VALUE))
);

pack();
} //< / editor-fold>

私人无效jButton1ActionPerformed(java.awt.event.ActionEvent evt){
new TheCombo()。setVisible(true);
this.dispose();
}

public static void main(String args []){
/ *设置Nimbus的外观* /
//< editor-fold defaultstate =collapseddesc =观感设置代码(可选)>
/ *如果Nimbus(在Java SE 6中引入)不可用,保持默认的外观和感觉。
*详情请参阅http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
* /
try {
for(javax.swing .UIManager.LookAndFeelInfo info:javax.swing.UIManager.getInstalledLookAndFeels()){
if(Nimbus.equals(info.getName())){
javax.swing.UIManager.setLookAndFeel .getClassName());
break;
}
}
} catch(ClassNotFoundException ex){
java.util.logging.Logger.getLogger(Answer.class.getName())log(java.util。 logging.Level.SEVERE,null,ex);
} catch(InstantiationException ex){
java.util.logging.Logger.getLogger(Answer.class.getName())。log(java.util.logging.Level.SEVERE,null,ex) ;
} catch(IllegalAccessException ex){
java.util.logging.Logger.getLogger(Answer.class.getName())。log(java.util.logging.Level.SEVERE,null,ex) ;
} catch(javax.swing.UnsupportedLookAndFeelException ex){
java.util.logging.Logger.getLogger(Answer.class.getName())。log(java.util.logging.Level.SEVERE, null,ex);
}
//< / editor-fold>

/ *创建并显示表单* /
java.awt.EventQueue.invokeLater(new Runnable(){
public void run(){
new ().setVisible(true);
}
});
}

//变量声明 - 不要修改
private javax.swing.JButton jButton1;
private javax.swing.JTextField jTextField1;
//变量声明结束
}


解决方案>

有很多方法可以实现这一点,但是基于代码的结构,你似乎想问用户一个问题,然后根据响应,做一些事情。



这只是尖叫对话框。有关详情,请参见如何创建对话



例如...

  import java.awt.EventQueue; 
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.EmptyBorder;

public class Test {

public static void main(String [] args){
new Test();
}

public Test(){
EventQueue.invokeLater(new Runnable(){
@Override
public void run(){
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch(ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex){
ex.printStackTrace();
}

JFrame frame = new JFrame(Testing);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new QuestionPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}

public class FruitPane extends JPanel {

private JComboBox< String> cb;

public FruitPane(){
add(new JLabel(Fruit:));
cb = new JComboBox< String>(new String [] {Bananas,Apples,Pears});
add(cb);
}

public String getSelectedFruit(){
return(String)cb.getSelectedItem();
}

}

public class QuestionPane extends JPanel {

private JTextField field;

public QuestionPane(){
add(new JLabel(Your fruit selection));
field = new JTextField(10);
field.setEditable(false);
add(field);

JButton btn = new JButton(Pick);
add(btn);

btn.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
FruitPane pane = new FruitPane();
pane.setBorder(new EmptyBorder(10,10,10,10));
int option = JOptionPane.showConfirmDialog(QuestionPane.this,pane,Fruit,JOptionPane.OK_CANCEL_OPTION,JOptionPane.PLAIN_MESSAGE);
if(option == JOptionPane.OK_OPTION){
String fruit = pane.getSelectedFruit();
field.setText(fruit);
}
}
});
}

}

}


I am a newbie here. Sorry for any bad post or any other bad things.

This question is the continuation of this stackoverflow question. And I already know about the JFrame problem JFrame Bad Practice. The problem is I'm a newbie using Netbeans to code Java. All I know is how to make program with JFrame. Below is the code that I have made. Please help me correct it so the purpose of my code (set Answer class text from TheCombo class selected combobox) can be done.

Please correct this codes (I have 3 classes). I want to get the ComboBox selected Item to be used in the answer class.

Main Class:

package testing;

public class Testing {

    public static void main(String[] args) {
        new TheCombo().setVisible(true);
    }

}

Combo Class:

package testing;

public class TheCombo extends javax.swing.JFrame {

public TheCombo() {
    initComponents();
}

public String getItem()
{
    String theItem = jComboBox1.getSelectedItem().toString();
    return theItem;
}


@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
private void initComponents() {

    jComboBox1 = new javax.swing.JComboBox();
    jButton1 = new javax.swing.JButton();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

    jButton1.setText("Go");
    jButton1.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton1ActionPerformed(evt);
        }
    });

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(jButton1)
            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jButton1))
            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    );

    pack();
}// </editor-fold>                        

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    new Answer().setVisible(true);
    this.dispose();
}                                        

public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(TheCombo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(TheCombo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(TheCombo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(TheCombo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new TheCombo().setVisible(true);
        }
    });
}

// Variables declaration - do not modify                     
private javax.swing.JButton jButton1;
private javax.swing.JComboBox jComboBox1;
// End of variables declaration                   
}

The Other Class (I want to set text the JTextField1 with selected item from the ComboBox at Combo Class):

package testing;

public class Answer extends javax.swing.JFrame {

TheCombo tc = new TheCombo();

public Answer() {
    initComponents();

    jTextField1.setText(tc.getItem());
}

@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
private void initComponents() {

    jTextField1 = new javax.swing.JTextField();
    jButton1 = new javax.swing.JButton();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    jTextField1.setHorizontalAlignment(javax.swing.JTextField.CENTER);
    jTextField1.setEnabled(false);

    jButton1.setText("Back");
    jButton1.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton1ActionPerformed(evt);
        }
    });

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
            .addComponent(jButton1)
            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jButton1))
            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    );

    pack();
}// </editor-fold>                        

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    new TheCombo().setVisible(true);
    this.dispose();
}                                        

public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(Answer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(Answer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(Answer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(Answer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new Answer().setVisible(true);
        }
    });
}

// Variables declaration - do not modify                     
private javax.swing.JButton jButton1;
private javax.swing.JTextField jTextField1;
// End of variables declaration                   
}

解决方案

There are a number of ways you might be able to achieve this, but based on the structure of your code, you seem to be wanting to ask the user a question and then based on the response, do something.

This just screams modal dialog. See How to Make Dialogs for more details

And for example...

import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.EmptyBorder;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new QuestionPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class FruitPane extends JPanel {

        private JComboBox<String> cb;

        public FruitPane() {
            add(new JLabel("Fruit: "));
            cb = new JComboBox<String>(new String[]{"Bananas", "Apples", "Pears"});
            add(cb);
        }

        public String getSelectedFruit() {
            return (String) cb.getSelectedItem();
        }

    }

    public class QuestionPane   extends JPanel {

        private JTextField field;

        public QuestionPane() {
            add(new JLabel("Your fruit selection"));
            field = new JTextField(10);
            field.setEditable(false);
            add(field);

            JButton btn = new JButton("Pick");
            add(btn);

            btn.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    FruitPane pane = new FruitPane();
                    pane.setBorder(new EmptyBorder(10, 10, 10, 10));
                    int option = JOptionPane.showConfirmDialog(QuestionPane.this, pane, "Fruit", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
                    if (option == JOptionPane.OK_OPTION) {
                        String fruit = pane.getSelectedFruit();
                        field.setText(fruit);
                    }
                }
            });
        }

    }

}

这篇关于Java从另一个JFrame获取选定的组合框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆