有人可以幫助指導我的錯誤在哪里嗎?當我將滑鼠懸停時,按鈕和 JSlider 會出現,這讓我很緊張。當我使用按鈕時很好,但是一旦我添加一個按鈕,JSlider 就會丟失并在我懸停并單擊時出現。
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.Point2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.ArrayList;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.event.*;
public class MainDisplay extends JFrame implements MouseMotionListener,
MouseListener, ChangeListener, ActionListener{
private Point mousepnt = new Point();
public static Color penColor = new Color(255,105,180);
private final JSlider penSize = new JSlider(JSlider.HORIZONTAL, 1, 30, 4);
public static int pen = 4;
JButton rbutton = new JButton();
JButton cbutton = new JButton();
JButton tbutton = new JButton();
JButton qbutton = new JButton();
ImageIcon ricon = new ImageIcon(getClass().getResource("ricon.png"));
ImageIcon cicon = new ImageIcon(getClass().getResource("cicon.png"));
ImageIcon ticon = new ImageIcon(getClass().getResource("ticon.png"));
ImageIcon qicon = new ImageIcon(getClass().getResource("qicon.png"));
public MainDisplay(){
JPanel toolbar = new JPanel(new FlowLayout(FlowLayout.LEFT));
JPanel toolbar2 = new JPanel(new FlowLayout(FlowLayout.LEFT));
JPanel jp = new JPanel();
jp.addMouseMotionListener(this);
jp.addMouseListener(this);
toolbar.add(new Label("Drag mouse to draw"));
toolbar.add(penSize);
penSize.addChangeListener(this);
toolbar2.add(new Label("Choose shape to draw"));
rbutton = new JButton(ricon);
rbutton.addActionListener(this);
rbutton.setMargin(new Insets(1, 2, 1, 2));
toolbar2.add(rbutton);
cbutton = new JButton(cicon);
cbutton.addActionListener(this);
cbutton.setMargin(new Insets(1, 2, 1, 2));
toolbar2.add(cbutton);
tbutton = new JButton(ticon);
tbutton.addActionListener(this);
tbutton.setMargin(new Insets(1, 2, 1, 2));
toolbar2.add(tbutton);
qbutton = new JButton(qicon);
qbutton.addActionListener(this);
qbutton.setMargin(new Insets(1, 2, 1, 2));
toolbar2.add(qbutton);
this.add(toolbar,BorderLayout.SOUTH);
this.add(toolbar2,BorderLayout.NORTH);
this.add(jp,BorderLayout.CENTER);
setSize(800,600);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
主班
public class Main {
public static void main(String[] args){
MainDisplay md = new MainDisplay();
}
}
uj5u.com熱心網友回復:
我會做什么:
將 MouseMotionListener 添加到面板:
jp.addMouseMotionListener(new MouseMotionListener() {
@Override
public void mouseDragged(MouseEvent e) {
}
@Override
public void mouseMoved(MouseEvent e) {
System.out.println("motion" e.getPoint());
}
});
將 ChangeListener 添加到 penSize:
penSize.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
System.out.println("new pensize: " penSize.getValue());
}
});
等等。因此,您已將 lsiteners 添加到組件而不是框架中。
我希望現在對你有所幫助。如果您有任何問題,請發布 Andrew 所寫的最小可重現示例。
斯蒂菲
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/457798.html
