gpt4 book ai didi

java - 如何使一个类成为 Java Swing 中的组件?

转载 作者:行者123 更新时间:2023-12-02 06:36:24 24 4
gpt4 key购买 nike

我是 Java 编程的初学者,所以我不知道我在这里是否使用了正确的术语。基本上,我有一个任务是编写一个小小程序,将背景颜色更改为按下 4 个颜色按钮中的任何一个。我得到了一个包含 ActionListener 的示例代码,并被告知使用 MouseListener 来实现它。

我能够成功地对其进行编程以使其工作,然后需求发生了变化。下面是我当前有效的代码(在需求更改之前)。

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class ButtonPanel extends JPanel implements MouseListener{
private JButton abutton, bbutton, cbutton, dbutton;

public ButtonPanel(){
abutton = new JButton("Cyan");
bbutton = new JButton("Orange");
cbutton = new JButton("Magenta");
dbutton = new JButton("Yellow");

add(abutton);
add(bbutton);
add(cbutton);
add(dbutton);

/* register the specific event handler into each button */
abutton.addMouseListener(this);
bbutton.addMouseListener(this);
cbutton.addMouseListener(this);
dbutton.addMouseListener(this);
}

/* implementation for the Mouse Event */

public void mouseClicked(MouseEvent evt){
Object source = evt.getSource();
if (source == abutton) setBackground(Color.cyan);
else if (source == bbutton) setBackground(Color.orange);
else if (source == cbutton) setBackground(Color.magenta);
else if (source == dbutton) setBackground(Color.yellow);
repaint();
}

public void mousePressed(MouseEvent evt){

}

public void mouseEntered(MouseEvent evt){

}

public void mouseReleased(MouseEvent evt){

}

public void mouseExited(MouseEvent evt){

}
}

class ButtonFrame extends JFrame{
public ButtonFrame(){
setTitle("Low-level Mouse Event to Set Color");
setSize(50, 50);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){ System.exit(0);}
});
Container contentPane = getContentPane();
contentPane.add(new ButtonPanel());
}
}

public class ME_SetColor {
public static void main(String[] args) {
JFrame frame = new ButtonFrame();
frame.pack();
frame.setSize(400, 250);
frame.setVisible(true);
}
}

新要求是排除 extends JPanel 以及 class ButtonPanel 的任何其他扩展。所以修改后的类必须是 类 ButtonPanel 实现 MouseListener{
私有(private)JButton abutton,bbutton,cbutton,dbutton;

如果没有 JPanel,ButtonPanel 类就不是组件,因此无法将其添加到 contentPane 中。是否有另一种方法可以使此 ButtonPanel 成为一个组件,以便将其添加到 contentPane 中?或者还有其他方法可以实现这个程序吗?

最佳答案

Without JPanel, the ButtonPanel class would not be a component

您可以扩展 JComponent。 JComponent 是 Swing 组件的基类。 JPanel 本身是 JComponent 的简单扩展(有一个细微的差别:JPanel 的 opaque 属性默认为 true,而 JComponent 默认为 false)。

但是,如果您的要求是排除 ButtonPanel 的任何扩展,那么您是对的,您实际上无法将其设为可以添加到容器中的组件。

但是,您可以包含一个组件作为 ButtonPanel 的字段:

class ButtonPanel implements ... {
private JPanel panel;
private JButton abutton, bbutton, cbutton, dbutton;

...

public JPanel getPanel() { return panel; }
}

然后在ButtonFrame中:

add(new ButtonPanel().getPanel());

您不需要顺便调用 getContentPane()contentPane.add ,作为框架自己的 add 方法 automatically do this

关于java - 如何使一个类成为 Java Swing 中的组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19609858/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com