java构造方法题目在窗口上显示三个滑板,分别控制窗口背景颜色中红黄蓝...
发布网友
发布时间:2024-09-27 06:23
我来回答
共2个回答
热心网友
时间:2024-10-04 10:13
我正好也想写个颜色混合后显示的程序,顺便写了个,供参考
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class TestFrame implements ChangeListener, ActionListener {
JSlider jsr = new JSlider(SwingConstants.HORIZONTAL, 0, 255, 0);
JSlider jsg = new JSlider(SwingConstants.HORIZONTAL, 0, 255, 0);
JSlider jsb = new JSlider(SwingConstants.HORIZONTAL, 0, 255, 0);
JPanel pc = new JPanel();
int r = jsr.getValue();
int b = jsb.getValue();
int g = jsg.getValue();
JTextField tr, tg, tb;
public TestFrame() {
pc.setBackground(new Color(r, g, b));
jsr.setFocusable(false);
jsg.setFocusable(false);
jsb.setFocusable(false);
JFrame f = new JFrame();
JPanel p = new JPanel(new GridBagLayout());
JLabel l;
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = GridBagConstraints.RELATIVE;
p.add(l = new JLabel("R"), c);
l.setDisplayedMnemonic('r');
l.setLabelFor(jsg);
p.add(l = new JLabel("G"), c);
l.setDisplayedMnemonic('g');
l.setLabelFor(jsg);
p.add(l = new JLabel("B"), c);
l.setDisplayedMnemonic('b');
l.setLabelFor(jsb);
c.gridx = 1;
c.weightx = 1;
c.fill = GridBagConstraints.HORIZONTAL;
p.add(jsr, c);
p.add(jsg, c);
p.add(jsb, c);
c.gridx = 2;
c.weightx = 0;
c.fill = 0;
p.add(tr = new JTextField(3), c);
p.add(tg = new JTextField(3), c);
p.add(tb = new JTextField(3), c);
tr.setText(jsr.getValue() + "");
tg.setText(jsr.getValue() + "");
tb.setText(jsr.getValue() + "");
jsr.addChangeListener(this);
jsg.addChangeListener(this);
jsb.addChangeListener(this);
tr.addActionListener(this);
tg.addActionListener(this);
tb.addActionListener(this);
f.add(p, BorderLayout.SOUTH);
f.add(pc);
f.setSize(300, 200);
f.setDefaultCloseOperation(3);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public static void main(String[] args) {
new TestFrame();
}
@Override
public void stateChanged(ChangeEvent e) {
if (jsr == e.getSource()) {
r = jsr.getValue();
tr.setText(r + "");
}
if (jsg == e.getSource()) {
g = jsg.getValue();
tg.setText(g + "");
}
if (jsb == e.getSource()) {
b = jsb.getValue();
tb.setText(b + "");
}
pc.setBackground(new Color(r, g, b));
}
@Override
public void actionPerformed(ActionEvent e) {
if (tr == e.getSource()) {
r = Integer.parseInt(tr.getText());
jsr.setValue(r);
}
if (tg == e.getSource()) {
g = Integer.parseInt(tg.getText());
jsg.setValue(g);
}
if (tb == e.getSource()) {
b = Integer.parseInt(tb.getText());
jsb.setValue(b);
}
pc.setBackground(new Color(r, g, b));
}
}
热心网友
时间:2024-10-04 10:07
嗯。。。。。。。。你啥专业