【发布时间】:2025-12-07 12:45:01
【问题描述】:
我正在构建一个 Swing 程序,我希望能够使用一个按钮来更改 JComponents(JLabel、JButton)的某些功能(字体、前景色、背景色等)。
如果所有组件都已显式声明和定义,我可以毫无问题地做到这一点,但如果它们是使用泛型方法隐式构建的,我无法弄清楚如何做到这一点。
以下是我目前所拥有的要点,减去一些不重要的细节。单击styleButton1 和 2 时,我想刷新或重建 JFrame,以便通过更改 @987654326 为组件(testButton1 和 2)使用功能/样式的新值(在本例中为字体) @ 然后重新绘制。
我没有收到任何错误,但frame 和组件没有被重建/刷新,即,单击样式按钮时没有任何反应。
关于如何使这项工作发挥作用的任何想法?或者我可以使用任何其他方法来获得所需的效果?
//imports
public class GuiTesting extends JFrame {
public static void main(String[] args) {
frame = new GuiTesting();
frame.setVisible(true);
}
static JFrame frame;
static Font standardFont = new Font("Arial", Font.BOLD, 10);
static Font secondFont = new Font("Times New Roman", Font.PLAIN, 10);
static Font currentFont = standardFont;
public GuiTesting() {
setTitle("GUI Testing");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
JPanel mainPanel = new JPanel();
getContentPane().add(mainPanel);
mainPanel.add(basicButton("Button1"));
mainPanel.add(basicButton("Button2"));
mainPanel.add(style1Button("Style 1"));
mainPanel.add(style2Button("Style 2"));
}
public static JButton basicButton(String title) {
JButton button = new JButton(title);
button.setPreferredSize(new Dimension(80, 30));
button.setFont(currentFont);
return button;
}
public static JButton style1Button(String title) {
JButton button = new JButton(title);
button.setPreferredSize(new Dimension(80, 30));
button.setFont(standardFont);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
currentFont = standardFont;
frame.repaint();
}
});
return button;
}
public static JButton style2Button(String title) {
JButton button = new JButton(title);
button.setPreferredSize(new Dimension(80, 30));
button.setFont(secondFont);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
currentFont = secondFont;
frame.repaint();
}
});
return button;
}
}
【问题讨论】:
标签: java swing events listener jcomponent