Java GUI JButton для actionlistner - PullRequest
       49

Java GUI JButton для actionlistner

0 голосов
/ 11 января 2012

Я сделал графический интерфейс в NetBeans. Это программа чата, и у меня есть 4 коммандос, как / присоединиться, / уйти, / шепот и / уйти

private void CommandoActionPerformed(java.awt.event.ActionEvent evt) {                                                 
        JOptionPane.showMessageDialog(rootPane, "The following commandos are:" + "\n" + "\n" + "/join Channel name" + "\n" + "/leave channel name" + "\n" + "/whisper nick message" + "\n" + "/quit - quit the program");
    }  

И это нормально, но мне нужен список действий вместо showMessageDialog, чтобы я мог нажать на них, и он появился в моем JTextField. Я думаю, что могу получить их там, но я не знаю, как объединить actionlistener с этим.

EDIT: Я хочу нажать кнопку «Коммандос» и открыть окно, в котором у меня есть 4 новые кнопки, каждая с одним коммандо (/ join, / exit, / whisper и / exit), поэтому, когда я нажимаю 1 из этих кнопок, я получаю коммандос в моем текстовом поле, поэтому мне просто нужно написать остальное. Поэтому, если я нажимаю кнопку «/ присоединиться», мне просто нужно написать название канала.

РЕДАКТИРОВАТЬ2: Если я плохо описал проблему, я могу показать, что я хотел и сделал до сих пор:

 private void showCommandActionPerformed(java.awt.event.ActionEvent evt) {                                                 
        Object[] options = { "/join", "/leave", "/whisper", "/quit", "Ingenting" };


        int choice= JOptionPane.showOptionDialog(rootPane, "What do u want to do? ", null, WIDTH, WIDTH, null, options, rootPane);

        switch (choice) {
                case 0:
                    skrivTekst.setText("/Join ");
                skrivTekst.requestFocus();
                    break;
                case 1:
                    skrivTekst.setText("/Leave");
                skrivTekst.requestFocus();
                    break;
                case 2:
                    skrivTekst.setText("/Whisper");
                skrivTekst.requestFocus();
                    break;
                case 3:
                skrivTekst.setText("/Join ");
                skrivTekst.requestFocus();

                case 4:

                    System.exit(1); //this is wrong. i just want to close this window, not the whole program 
                default:

                    JOptionPane.showMessageDialog(null, "donno what!?!?!?!?!?!?!" + choice);
            }


    }                 

Я надеюсь, что это шоу, что я хотел и что я сделал. Ты всем :) Поэтому единственная проблема, которую я оставил, - это закрытие одного окна JOptionPane, а не программы

Ответы [ 3 ]

2 голосов
/ 11 января 2012

1) вы можете реализовать JRadioButtons в ButtonGroup , тогда для выбора будет доступен только один из вариантов, там вы можете реализовать ActionListener и внутри ActionListener setText() для JTextField

2) пожалуйста, используйте стандартный Swing JComponents вместо подготовленного Components из palette, иногда слишком сложно переопределить основные методы Swing

enter image description here

простой пример на основе примера для JRadioButton из учебника

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;

import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;

/*
 * RadioButtonDemo.java is a 1.4 application that requires these files:
 * images/Bird.gif images/Cat.gif images/Dog.gif images/Rabbit.gif
 * images/Pig.gif
 */
public class RadioButtonDemo extends JPanel implements ActionListener {

    private static String birdString = "Bird";
    private static String catString = "Cat";
    private static String dogString = "Dog";
    private static String rabbitString = "Rabbit";
    private static String pigString = "Pig";
    private static final long serialVersionUID = 1L;
    private JLabel picture;

    public RadioButtonDemo() {
        super(new BorderLayout());
        //Create the radio buttons.
        JRadioButton birdButton = new JRadioButton(birdString);
        birdButton.setMnemonic(KeyEvent.VK_B);
        birdButton.setActionCommand(birdString);
        birdButton.setSelected(true);
        JRadioButton catButton = new JRadioButton(catString);
        catButton.setMnemonic(KeyEvent.VK_C);
        catButton.setActionCommand(catString);
        JRadioButton dogButton = new JRadioButton(dogString);
        dogButton.setMnemonic(KeyEvent.VK_D);
        dogButton.setActionCommand(dogString);
        JRadioButton rabbitButton = new JRadioButton(rabbitString);
        rabbitButton.setMnemonic(KeyEvent.VK_R);
        rabbitButton.setActionCommand(rabbitString);
        JRadioButton pigButton = new JRadioButton(pigString);
        pigButton.setMnemonic(KeyEvent.VK_P);
        pigButton.setActionCommand(pigString);
        //Group the radio buttons.
        ButtonGroup group = new ButtonGroup();
        group.add(birdButton);
        group.add(catButton);
        group.add(dogButton);
        group.add(rabbitButton);
        group.add(pigButton);
        //Register a listener for the radio buttons.
        birdButton.addActionListener(this);
        catButton.addActionListener(this);
        dogButton.addActionListener(this);
        rabbitButton.addActionListener(this);
        pigButton.addActionListener(this);
        //Set up the picture label.
        picture = new JLabel("Narrative");
        //The preferred size is hard-coded to be the width of the
        //widest image and the height of the tallest image.
        //A real program would compute this.
        //picture.setPreferredSize(new Dimension(177, 122));
        //Put the radio buttons in a column in a panel.
        JPanel radioPanel = new JPanel(new GridLayout(0, 1));
        radioPanel.add(birdButton);
        radioPanel.add(catButton);
        radioPanel.add(dogButton);
        radioPanel.add(rabbitButton);
        radioPanel.add(pigButton);
        add(radioPanel, BorderLayout.LINE_START);
        pigButton.setVisible(false);
        rabbitButton.setVisible(false);
        add(picture, BorderLayout.CENTER);
        setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
    }

    /** Listens to the radio buttons.
     * @param e
     */
    public void actionPerformed(ActionEvent e) {
        String narr = e.getActionCommand();
        picture.setText(narr);
    }

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

    /**
     * Create the GUI and show it. For thread safety, this method should be
     * invoked from the event-dispatching thread.
     */
    private static void createAndShowGUI() {
        //Make sure we have nice window decorations.
        JFrame.setDefaultLookAndFeelDecorated(true);
        //Create and set up the window.
        JFrame frame = new JFrame("RadioButtonDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //Create and set up the content pane.
        JComponent newContentPane = new RadioButtonDemo();
        newContentPane.setOpaque(true); //content panes must be opaque
        frame.setContentPane(newContentPane);
        //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();
            }
        });
    }
}
1 голос
/ 11 января 2012

Вам нужно 4 кнопки, каждая из которых устанавливает текст команды в текстовом поле, это верно?

joinButton.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        theTextField.setText("/join");
    }
});

И то же самое с остальными 3 кнопками.

Этодействительно простые вещи.Прочитайте учебник о слушателях событий .

0 голосов
/ 11 января 2012

Как то так?

public void actionPerformed(ActionEvent event) {
    Object source = event.getSource();
    if (source == join) {
        textField.setText("/join");
    } else if (source == leave) {
        textField.setText("/leave");
    } else if (source == whisper) {
        textField.setText("/join");
    } else {
        textField.setText("/exit");
    }
}

Это происходит при условии, что ваши кнопки называются «присоединиться, выйти, прошептать и выйти».

...