Ⅰ 用java畫一元二次方程的圖形,a、b、c用三個滑竿JSlider改變值,具體見下圖
按照你的要求編寫的Java程序如下:
importjava.awt.BorderLayout;
importjava.awt.Color;
importjava.awt.Component;
importjava.awt.Container;
importjava.awt.Graphics;
importjava.awt.GridLayout;
importjava.util.ArrayList;
importjava.util.Dictionary;
importjava.util.Hashtable;
importjava.util.List;
importjavax.swing.JFrame;
importjavax.swing.JLabel;
importjavax.swing.JPanel;
importjavax.swing.JSlider;
importjavax.swing.event.ChangeEvent;
importjavax.swing.event.ChangeListener;
{
Containercon;
JLabeljl1=newJLabel("avalue");
JLabeljl2=newJLabel("bvalue");
JLabeljl3=newJLabel("cvalue");
JPaneljp=newJPanel();
JPaneljp1=newJPanel();
JPaneljp2=newJPanel();
JPaneljp3=newJPanel();
JCurvePaneljcp=newJCurvePanel();
JSliderjs1=newJSlider(JSlider.HORIZONTAL,0,100,50);
JSliderjs2=newJSlider(JSlider.HORIZONTAL,0,100,50);
JSliderjs3=newJSlider(JSlider.HORIZONTAL,0,100,50);
inta=1;
intb=2;
intc=1;
KKK(){
js1.setPaintTicks(true);
js1.setMinorTickSpacing(5);
js1.setMajorTickSpacing(100);
js1.setPaintLabels(true);
Dictionary<Integer,Component>labels=newHashtable<Integer,Component>();
labels.put(0,newJLabel("0"));
labels.put(20,newJLabel("20"));
labels.put(40,newJLabel("40"));
labels.put(60,newJLabel("60"));
labels.put(80,newJLabel("80"));
labels.put(100,newJLabel("100"));
js1.setLabelTable(labels);
js2.setPaintTicks(true);
js2.setMinorTickSpacing(5);
js2.setMajorTickSpacing(100);
js2.setPaintLabels(true);
js2.setLabelTable(labels);
js3.setPaintTicks(true);
js3.setMinorTickSpacing(5);
js3.setMajorTickSpacing(100);
js3.setPaintLabels(true);
js3.setLabelTable(labels);
js1.addChangeListener(this);
js2.addChangeListener(this);
js3.addChangeListener(this);
jp.setLayout(newGridLayout(3,1));
jp1.add(js1);jp1.add(jl1);
jp2.add(js2);jp2.add(jl2);
jp3.add(js3);jp3.add(jl3);
jp.add(jp1);jp.add(jp2);jp.add(jp3);
con=getContentPane();
jp.setBackground(Color.WHITE);
con.add(jp,BorderLayout.EAST);
con.add(jcp,BorderLayout.CENTER);
setSize(700,500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
publicstaticvoidmain(String[]args){
newKKK();
}
@Override
publicvoidstateChanged(ChangeEventce){
if(ce.getSource()==js1){
a=js1.getValue();
}
if(ce.getSource()==js2){
b=js2.getValue();
}
if(ce.getSource()==js3){
c=js3.getValue();
}
repaint();
}
classJCurvePanelextendsJPanel{
JCurvePanel(){
this.setBackground(Color.BLACK);
this.setForeground(Color.WHITE);
}
publicvoidpaint(Graphicsg){
super.paint(g);
intx0,y0;
x0=this.getWidth()/2;
y0=this.getHeight()/2;
inttriangleYX[]={x0-5,x0+5,x0};
inttriangleYY[]={50,50,45};
g.setColor(Color.WHITE);
g.drawLine(x0,50,x0,y0*2-50);
g.fillPolygon(triangleYX,triangleYY,3);
for(inti=y0;i>50;i-=10){
g.drawLine(x0,i,x0+5,i);
}
for(inti=y0;i<y0*2-50;i+=10){
g.drawLine(x0,i,x0+5,i);
}
inttriangleXX[]={x0*2-50,x0*2-50,x0*2-45};
inttriangleXY[]={y0-5,y0+5,y0};
g.drawLine(50,y0,x0*2-50,y0);
g.fillPolygon(triangleXX,triangleXY,3);
for(inti=x0;i>50;i-=10){
g.drawLine(i,y0,i,y0-5);
}
for(inti=x0;i<x0*2-50;i+=10){
g.drawLine(i,y0,i,y0-5);
}
List<Integer>listx=newArrayList<Integer>();
List<Integer>listy=newArrayList<Integer>();
for(intj=-200;j<200;j++){
listx.add(j);
listy.add(-(a*j*j+b*j+c));
}
for(inti=0;i<listx.size()-1;i++){
g.drawLine(listx.get(i)+x0,listy.get(i)+y0,listx.get(i+1)+x0,listy.get(i+1)+y0);
}
}
}
}
運行結果:
Ⅱ Java swing Jslider問題
//不知道為什麼翻牌控制項與滑塊控制項無法同時顯示代碼如下
import javax.swing.*;
import java.awt.*;
public class Test extends JFrame
{
public static void main(String []args)
{
Test frame =new Test();
}
public Test()
{
super("測試");
Container c=getContentPane();
// c.setLayout(new FlowLayout(FlowLayout.CENTER));
JSlider js=new JSlider();
js.setMajorTickSpacing(2);
js.setPaintTicks(true);
c.add(js,BorderLayout.NORTH);
// Container c1=getContentPane();
// CardLayout card =new CardLayout();
// c1.setLayout(null);
JPanel cardPanel = new JPanel();
cardPanel.setLayout(null);
JButton b1=new JButton("ok");
JButton b2=new JButton("ko");
b1.setBounds(70, 50, 60, 20);
b2.setBounds(150, 50, 60, 20);
cardPanel.add(b1,"1");
cardPanel.add(b2,"2");
c.add(cardPanel,BorderLayout.CENTER);
pack();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300,300);
setLocationRelativeTo(null);
setVisible(true);
}
}
Ⅲ java中的JSlider如果要實現一個窗口透明度的程序 怎麼實現每次拖動窗口立刻會變、線程嗎
1.動態改變num
添加一個Listener也就是監聽器這樣就可以的了吧。類似radiousSlider.addChangeListener(
new ChangeListener(){
public void stateChanged(ChangeEvent e)
{
int radious=radiousSlider.getValue(); //錯誤在此!
} });
這只是提供參考,具體要看你是如何獲取這個num值的,能能夠根據您的動作而設置監聽類型
2.設置Jslider的初始值
JSlider(int min, int max,int value):建立一個水平的JSlider的對象,自定義刻度與初始值.在Value填上你要設置的初始值就可以的了
希望可以幫助到你。。
Ⅳ Java中使用JSlider做成一個滑桿、兩個滑塊的效果
我試了,2個都可以動的。只是,前面的軌道會擋住後面的滑塊。不美觀。除非自己重寫一個組件了。試了一會,感覺好累。。。
Ⅳ 求java jslider的例子,如何實現下圖右邊的滑動條
jSlider.setUI(new MetalSliderUI() {
@Override
public void paintThumb(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setColor(Color.red);
//
g2d.fillRect(thumbRect.x, thumbRect.y, thumbRect.width,
//
thumbRect.height);
g2d.drawImage(img, x, y, width, height, observer);
}
});
同樣道理可以改改滑動條的填充顏色,不過有些復雜。你可以參考javax.swing.plaf.basic.BasicSliderUI、javax.swing.plaf.metal.MetalSliderUI等類中的paintTrack方法來實現怎麼自定義自己的滑動條哈。
Ⅵ 怎樣將javaJSlider的滑塊設置為滑鼠點擊不動
把setEnabled 置成 false
Ⅶ JAVA中如何用Jslider控制聲音大小
jslier.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
int volume = ((JSlider)e.getSource()).getValue();
//設置音量
}
});
Ⅷ 在java中如何通過JSlider控制 來實現以下效果急 !拖動滑動條的時候坐標系會隨著縮放。講明思路哈
寫一個畫坐標的方法:hua(int suofang)//此處的suofang通過slider的值而變化,用來控制控制坐標的變化,然後把hua(int suofang)方法寫道paint方法裡面,然後在slider的vlaueChanged事件裡面寫上repaint()方法,就ok了,不懂可以繼續追問
Ⅸ java 中JSlider和Jspinner的使用
import javax.swing.*;
import java.awt.Color;
import java.awt.Container;
import java.util.Calendar;
import java.util.Date;
public class SpinnerDemo extends JPanel {
public SpinnerDemo(boolean cycleMonths) {
super(new SpringLayout());
String[] labels = {"Month: ", "Year: ", "Another Date: "};
int numPairs = labels.length;
Calendar calendar = Calendar.getInstance();
JFormattedTextField ftf = null;
//Add the first label-spinner pair.
String[] monthStrings = getMonthStrings(); //get month names
SpinnerListModel monthModel = null;
if (cycleMonths) { //use custom model
monthModel = new CyclingSpinnerListModel(monthStrings);
} else { //use standard model
monthModel = new SpinnerListModel(monthStrings);
}
JSpinner spinner = addLabeledSpinner(this,
labels[0],
monthModel);
//Tweak the spinner's formatted text field.
ftf = getTextField(spinner);
if (ftf != null ) {
ftf.setColumns(8); //specify more width than we need
ftf.setHorizontalAlignment(JTextField.RIGHT);
}
//Add second label-spinner pair.
int currentYear = calendar.get(Calendar.YEAR);
SpinnerModel yearModel = new SpinnerNumberModel(currentYear, //initial value
currentYear - 100, //min
currentYear + 100, //max
1); //step
//If we're cycling, hook this model up to the month model.
if (monthModel instanceof CyclingSpinnerListModel) {
((CyclingSpinnerListModel)monthModel).setLinkedModel(yearModel);
}
spinner = addLabeledSpinner(this, labels[1], yearModel);
//Make the year be formatted without a thousands separator.
spinner.setEditor(new JSpinner.NumberEditor(spinner, "#"));
//Add the third label-spinner pair.
Date initDate = calendar.getTime();
calendar.add(Calendar.YEAR, -100);
Date earliestDate = calendar.getTime();
calendar.add(Calendar.YEAR, 200);
Date latestDate = calendar.getTime();
SpinnerModel dateModel = new SpinnerDateModel(initDate,
earliestDate,
latestDate,
Calendar.YEAR);//ignored for user input
spinner = addLabeledSpinner(this, labels[2], dateModel);
spinner.setEditor(new JSpinner.DateEditor(spinner, "MM/yyyy"));
//Lay out the panel.
SpringUtilities.makeCompactGrid(this,
numPairs, 2, //rows, cols
10, 10, //initX, initY
6, 10); //xPad, yPad
}
/**
* Return the formatted text field used by the editor, or
* null if the editor doesn't descend from JSpinner.DefaultEditor.
*/
public JFormattedTextField getTextField(JSpinner spinner) {
JComponent editor = spinner.getEditor();
if (editor instanceof JSpinner.DefaultEditor) {
return ((JSpinner.DefaultEditor)editor).getTextField();
} else {
System.err.println("Unexpected editor type: "
+ spinner.getEditor().getClass()
+ " isn't a descendant of DefaultEditor");
return null;
}
}
/**
* DateFormatSymbols returns an extra, empty value at the
* end of the array of months. Remove it.
*/
static protected String[] getMonthStrings() {
String[] months = new java.text.DateFormatSymbols().getMonths();
int lastIndex = months.length - 1;
if (months[lastIndex] == null
|| months[lastIndex].length() <= 0) { //last item empty
String[] monthStrings = new String[lastIndex];
System.array(months, 0,
monthStrings, 0, lastIndex);
return monthStrings;
} else { //last item not empty
return months;
}
}
static protected JSpinner addLabeledSpinner(Container c,
String label,
SpinnerModel model) {
JLabel l = new JLabel(label);
c.add(l);
JSpinner spinner = new JSpinner(model);
l.setLabelFor(spinner);
c.add(spinner);
return spinner;
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event dispatch thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("SpinnerDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Add content to the window.
frame.add(new SpinnerDemo(false));
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//Schele a job for the event dispatch thread:
//creating and showing this application's GUI.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
//Turn off metal's use of bold fonts
UIManager.put("swing.boldMetal", Boolean.FALSE);
createAndShowGUI();
}
});
}
}
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
/*
* SliderDemo.java requires all the files in the images/doggy
* directory.
*/
public class SliderDemo extends JPanel
implements ActionListener,
WindowListener,
ChangeListener {
//Set up animation parameters.
static final int FPS_MIN = 0;
static final int FPS_MAX = 30;
static final int FPS_INIT = 15; //initial frames per second
int frameNumber = 0;
int NUM_FRAMES = 14;
ImageIcon[] images = new ImageIcon[NUM_FRAMES];
int delay;
Timer timer;
boolean frozen = false;
//This label uses ImageIcon to show the doggy pictures.
JLabel picture;
public SliderDemo() {
setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
delay = 1000 / FPS_INIT;
//Create the label.
JLabel sliderLabel = new JLabel("Frames Per Second", JLabel.CENTER);
sliderLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
//Create the slider.
JSlider framesPerSecond = new JSlider(JSlider.HORIZONTAL,
FPS_MIN, FPS_MAX, FPS_INIT);
framesPerSecond.addChangeListener(this);
//Turn on labels at major tick marks.
framesPerSecond.setMajorTickSpacing(10);
framesPerSecond.setMinorTickSpacing(1);
framesPerSecond.setPaintTicks(true);
framesPerSecond.setPaintLabels(true);
framesPerSecond.setBorder(
BorderFactory.createEmptyBorder(0,0,10,0));
Font font = new Font("Serif", Font.ITALIC, 15);
framesPerSecond.setFont(font);
//Create the label that displays the animation.
picture = new JLabel();
picture.setHorizontalAlignment(JLabel.CENTER);
picture.setAlignmentX(Component.CENTER_ALIGNMENT);
picture.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createLoweredBevelBorder(),
BorderFactory.createEmptyBorder(10,10,10,10)));
updatePicture(0); //display first frame
//Put everything together.
add(sliderLabel);
add(framesPerSecond);
add(picture);
setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
//Set up a timer that calls this object's action handler.
timer = new Timer(delay, this);
timer.setInitialDelay(delay * 7); //We pause animation twice per cycle
//by restarting the timer
timer.setCoalesce(true);
}
/** Add a listener for window events. */
void addWindowListener(Window w) {
w.addWindowListener(this);
}
//React to window events.
public void windowIconified(WindowEvent e) {
stopAnimation();
}
public void windowDeiconified(WindowEvent e) {
startAnimation();
}
public void windowOpened(WindowEvent e) {}
public void windowClosing(WindowEvent e) {}
public void windowClosed(WindowEvent e) {}
public void windowActivated(WindowEvent e) {}
public void windowDeactivated(WindowEvent e) {}
/** Listen to the slider. */
public void stateChanged(ChangeEvent e) {
JSlider source = (JSlider)e.getSource();
if (!source.getValueIsAdjusting()) {
int fps = (int)source.getValue();
if (fps == 0) {
if (!frozen) stopAnimation();
} else {
delay = 1000 / fps;
timer.setDelay(delay);
timer.setInitialDelay(delay * 10);
if (frozen) startAnimation();
}
}
}
public void startAnimation() {
//Start (or restart) animating!
timer.start();
frozen = false;
}
public void stopAnimation() {
//Stop the animating thread.
timer.stop();
frozen = true;
}
//Called when the Timer fires.
public void actionPerformed(ActionEvent e) {
//Advance the animation frame.
if (frameNumber == (NUM_FRAMES - 1)) {
frameNumber = 0;
} else {
frameNumber++;
}
updatePicture(frameNumber); //display the next picture
if ( frameNumber==(NUM_FRAMES - 1)
|| frameNumber==(NUM_FRAMES/2 - 1) ) {
timer.restart();
}
}
/** Update the label to display the image for the current frame. */
protected void updatePicture(int frameNum) {
//Get the image if we haven't already.
if (images[frameNumber] == null) {
images[frameNumber] = createImageIcon("images/doggy/T"
+ frameNumber
+ ".gif");
}
//Set the image.
if (images[frameNumber] != null) {
picture.setIcon(images[frameNumber]);
} else { //image not found
picture.setText("image #" + frameNumber + " not found");
}
}
/** Returns an ImageIcon, or null if the path was invalid. */
protected static ImageIcon createImageIcon(String path) {
java.net.URL imgURL = SliderDemo.class.getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("SliderDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
SliderDemo animator = new SliderDemo();
//Add content to the window.
frame.add(animator, BorderLayout.CENTER);
//Display the window.
frame.pack();
frame.setVisible(true);
animator.startAnimation();
}
public static void main(String[] args) {
/* Turn off metal's use of bold fonts */
UIManager.put("swing.boldMetal", Boolean.FALSE);
//Schele a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
需要的圖片自己載入了。
Ⅹ java JSlider組件怎麼添加事件啊!
應該是監聽 JSlider.addChangeListener(ChangeListener l); 這個事件