//간단한 색상표를 만들어 보자
package swing;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
//복사해서 쓸것
//Java5.0버전 이후 프레임 앞에 컨테이너가 기본으로 하나가 있다.
//따라서 컨테이너를 바꿔준다.
public class SliderTest extends JFrame implements ChangeListener
{
Container cp;
JSlider sdRed,sdGreen,sdBlue;
JLabel lblRed,lblGreen,lblBlue;
JPanel pColor;
//rgb값 설정
int r=0,g=0,b=0; //기본값을 0으로 줘서 if 문에서 값을 못받더라도 초기값을 0으로 설정해줌
public SliderTest(String title)
{
super(title);
cp=this.getContentPane();
this.setDesign();
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setBounds(300,100,400,400);
cp.setBackground(new Color(255, 255, 200));
this.setVisible(true);
}
@Override
public void stateChanged(ChangeEvent e)
{
Object ob=e.getSource();
if(ob==sdRed)
r=sdRed.getValue();
else if(ob==sdGreen)
g=sdGreen.getValue();
else if(ob==sdBlue)
b=sdBlue.getValue();
lblRed.setText(String.valueOf(r));
lblBlue.setText(String.valueOf(b));
lblGreen.setText(String.valueOf(g));
pColor.setBackground(new Color(r,g,b));
}
public void setDesign()
{
JPanel p1=new JPanel();
JPanel p2=new JPanel();
JPanel p3=new JPanel();
JPanel pTop=new JPanel(new GridLayout(3,1));
cp.setLayout(new GridLayout(2,1));
//sb.setLayout(new BorderLayout());
sdRed=new JSlider(JSlider.HORIZONTAL,0,255,255);
lblRed=new JLabel("255",JLabel.CENTER);
p1.add(new JLabel("빨강"));
p1.add(sdRed);
p1.add(lblRed);
pTop.add(p1);
sdGreen=new JSlider(JSlider.HORIZONTAL,0,255,0);
lblGreen=new JLabel("0",JLabel.CENTER);
p2.add(new JLabel("초록"));
p2.add(sdGreen);
p2.add(lblGreen);
pTop.add(p2);
sdBlue=new JSlider(JSlider.HORIZONTAL,0,255,255);
lblBlue=new JLabel("255",JLabel.CENTER);
p3.add(new JLabel("파랑"));
p3.add(sdBlue);
p3.add(lblBlue);
pTop.add(p3);
cp.add("North",pTop);
pColor=new JPanel();
pColor.setBackground(new Color(255,0,255));
cp.add(pColor);
//이벤트 발생
sdRed.addChangeListener(this);
sdGreen.addChangeListener(this);
sdBlue.addChangeListener(this);
}
public static void main(String[] args)
{
new SliderTest("stanrd swing form");
}
}
본 블로그는 페이스북 댓글을 지원합니다.