Как заставить переключатели динамически изменять текст в Java - PullRequest
0 голосов
/ 09 декабря 2010

Я довольно новичок в GUI. Я пытаюсь сделать так, чтобы в зависимости от того, какой переключатель выбран, JLabel меняет свое значение. Например, если выбрано «id», на нем будет отображаться «http://steamcommunity.com/id/"», а если выбрано «profile», на нем будет отображаться «http://steamcommunity.com/profiles/".. У меня есть некоторый код, работающий и почти завершенный:

package sgt;

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.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;


public class RadioButtonPrompt extends JPanel
                             implements ActionListener {

 private static final long serialVersionUID = 1L;
 static String idString = "ID";
    static String profileString ="Profile";
    static String type = idString;

    public RadioButtonPrompt() {
        super(new BorderLayout());

        // Create radio buttons.
        JRadioButton idButton = new JRadioButton(idString, true);
        idButton.setMnemonic(KeyEvent.VK_I);
        idButton.setActionCommand(idString);

        JRadioButton profileButton = new JRadioButton(profileString);
        profileButton.setMnemonic(KeyEvent.VK_P);
        profileButton.setActionCommand(profileString);

        // Group radio buttons.
        ButtonGroup group = new ButtonGroup();
        group.add(idButton);
        group.add(profileButton);

        idButton.addActionListener(this);
        profileButton.addActionListener(this);

        JPanel radioPanel = new JPanel(new GridLayout(0, 1));
        radioPanel.add(idButton);
        radioPanel.add(profileButton);

        JPanel textPanel = new JPanel ();
        JLabel URL = new JLabel(setJLabelValue());

        JTextField text = new JTextField("sampletextfield");
        text.setPreferredSize(new Dimension(100, 20));

        textPanel.add(URL);
        textPanel.add(text);

        JPanel buttonPanel = new JPanel(new GridLayout(1, 0));
        JButton submit = new JButton("Submit");
        submit.setMnemonic(KeyEvent.VK_S);

        buttonPanel.add(submit);


        add(radioPanel, BorderLayout.LINE_START);
  add(textPanel, BorderLayout.CENTER);
  add(buttonPanel, BorderLayout.PAGE_END);

        setBorder(BorderFactory.createCompoundBorder());
    }

    private String setJLabelValue() {
     if (type.equals("ID")) {
      return "http://steamcommunity.com/id/";
     }
     return "http://steamcommunity.com/profiles/";

 }

    public void actionPerformed(ActionEvent e) {

     // Returns either "Profile" or "ID"
        type = ((JRadioButton)e.getSource()).getText();
        System.out.println(type);


    }

    private static void createAndShowGUI() {
        JFrame frame = new JFrame("Steam Game Tracker");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JComponent newContentPane = new RadioButtonPrompt();
        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) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}

Ответы [ 2 ]

2 голосов
/ 09 декабря 2010

Взгляните на эту ТАКУЮ ветку.

0 голосов
/ 09 декабря 2010

в actionPerformed () вам нужно преобразовать textpanel.setText () в любое, что вы хотите, основываясь на том, какая кнопка была нажата.Я догадываюсь по названию метода, некоторое время не занимался интерфейсом с Java.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...