所以我做了3个不同的类,一个用于构造文本字段,一个用于标签,一个用于滑块。我遇到的问题是,在滑块侦听器中,如果将其设置为1(3个中的一个),则将标签设置为“ randomInt + randomInt”,我知道该如何将数字随机化,这只是在更改标签的文本,即在不同的类别中进行。
这是我的主要功能,后面是两节课:

import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
public class driver
{
    public static void main(String[] args)
    {
        colorfulLabel blueLabel = new colorfulLabel("", Color.yellow);
        colorfulTextField redTextField = new colorfulTextField(Color.red,15);
        RatingSlider mathSlide = new RatingSlider(JSlider.HORIZONTAL , 0, 3, 0);

        JFrame frame = new JFrame("Math");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel panel = new JPanel();
        panel.add(blueLabel);
        panel.add(redTextField);
        panel.add(mathSlide);
        frame.getContentPane().add(panel);
        frame.pack();
        frame.setVisible(true);
    }
}




import javax.swing.*;
import java.awt.*;
public class colorfulLabel extends JLabel
{
    //constructor uses one color parameter to respresent bg color
    //creates label using bg color
    //calls parent constructor using super()
    //private Color color;
    public colorfulLabel(String text,Color bg){
        super(text);
        setBackground(bg);
        setOpaque(true);
    }
}




//RatingSlider
import javax.swing.*;
import java.awt.*;
import java.util.Random;
import javax.swing.event.*;
public class RatingSlider extends JSlider
{
    Random generator = new Random();
    private JSlider difficultySlider;
    //accepts horizontal paramater, a min, a max, and starting point for slider
    public RatingSlider(int horiz, int start, int max, int min){
        super(horiz, start, max, min);

        difficultySlider = new JSlider(horiz, start, max, min);
        difficultySlider.setMajorTickSpacing(1);
        difficultySlider.setMinorTickSpacing(0);

        setPaintTicks(true);
        setPaintLabels(true);
        difficultySlider.setAlignmentX(Component.LEFT_ALIGNMENT);

        JPanel Slide = new JPanel();
        BoxLayout layout = new BoxLayout(Slide, BoxLayout.Y_AXIS);
        Slide.setLayout(layout);
        Slide.add(difficultySlider);
        SliderListener listener = new SliderListener();

        difficultySlider.addChangeListener(listener);
    }
    private class SliderListener implements ChangeListener
    {
        public void stateChanged(ChangeEvent event)
        {
            int num1, num2;
            String lblString = "", num_1, num_2;
            if(difficultySlider.getValue() ==1)
            {
                num1 = generator.nextInt();
                num2 = generator.nextInt();
                lblString = (num1 + " + " + num2);
            }

        }
    }

}


现在,我只需要将colorfulLabel的文本设置为lblString,并且我不知道如何在不创建新对象的情况下做到这一点。

最佳答案

我认为您可以只使用.setText(“”)方法,并且由于扩展了JLabel类,因此应该这样做。但坦率地说,您可以使用Builder设计模式,而无需扩展任何类,它基本上应该对您有用。

09-10 08:42