所以我製作了3個不同的類,一個用於構建文本字段,一個用於標籤,另一個用於滑塊。我遇到的問題是,在滑塊偵聽器中,如果設置爲1(滿分爲3),將標籤設置爲「randomInt + randomInt」,我知道如何隨機化數字,它只是更改標籤的文本在不同的階級中製作。 這裏是我的主要fnctn其次是兩類:Java GUI組件
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的文本,我不能弄清楚如何做到這一點,而不創建一個新的對象
參考正如已經建議你在你前面的問題,你將要學習和遵循的Java命名約定包括給出以大寫字母開頭的類名稱。所以不是colorLabel,而是ColorLabel。請進行此更改。 –