我的任务是通过点击标签来更改jlabel,但我们还没有进入鼠标适配器和鼠标处理,我们只是重复覆盖了5个鼠标事件,以便'我们都可以使用。继承了我到目前为止所做的一切,但它所做的只是更改我的名字的字体,我希望它也可以在我点击我的名字时将JLabel的颜色更改为红色。
class FontFrame extends JFrame implements ActionListener{
JButton FirstFont;
JButton SecondFont;
JLabel myName;
public FontFrame(){
setSize(600, 200);
setLocation(300, 200);
Container contentpane = getContentPane();
myName = new JLabel("Aly");
FirstFont = new JButton("Chalkboard 14");
SecondFont = new JButton("Harrington 18");
JPanel panel = new JPanel();
panel.add(FirstFont);
panel.add(SecondFont);
panel.add(myName);
FirstFont.addActionListener(this);
SecondFont.addActionListener(this);
contentpane.add(panel, "Center");
}
public void actionPerformed(ActionEvent e){
Object source = e.getSource();
Font f1 = new Font("Chalkboard", Font.PLAIN, 14);
Font f2 = new Font("Harrington", Font.PLAIN, 18);
if(source == FirstFont){
myName.setFont(f1);
}
else if(source == SecondFont){
myName.setFont(f2);
}
}
}
class mouseFrame extends FontFrame implements MouseListener{
public mouseFrame(){
addMouseListener(this);
myName.addMouseListener(this);
FirstFont.addMouseListener(this);
SecondFont.addMouseListener(this);
add(myName);
add(FirstFont);
add(SecondFont);
Container contentpane = getContentPane();
contentpane.add(new FontFrame());
}
public void mouseClicked(MouseEvent e) {
int fontbutton = e.getButton();
if(fontbutton == MouseEvent.BUTTON1 ){
myName.setForeground(Color.red);
}
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
}
public class ChangeFont {
public static void main(String[] args){
JFrame frame = new FontFrame();
frame.setVisible(true);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
}
答案 0 :(得分:1)
MouseFrame
MouseFrame
没有调用FontFrame
的构造函数(super()
),而是尝试向其添加FontFrame
的新实例,这是一项非法行动首先更改MouseFrame
,然后调用super
构造函数,只将MouseListener
添加到JLabel
public static class MouseFrame extends FontFrame implements MouseListener {
public MouseFrame() {
super();
myName.addMouseListener(this);
}
public void mouseClicked(MouseEvent e) {
System.out.println("...");
int fontbutton = e.getButton();
if (fontbutton == MouseEvent.BUTTON1) {
myName.setForeground(Color.red);
}
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
}
接下来,在main
方法中,创建MouseFrame
...
public static void main(String[] args) {
JFrame frame = new MouseFrame();
frame.setVisible(true);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}