我正在构建一个 Swing 程序,我希望能够使用按钮来更改 JComponents
(JLabel) 的某些功能(字体、前景色、背景色等)
、JButton
)。
如果组件都已显式声明和定义,我可以毫无问题地执行此操作,但如果它们是使用通用方法隐式构建的,我无法弄清楚如何执行此操作。
下面是我到目前为止所掌握的内容的要点,去掉了一些不重要的细节。单击 styleButton1
和 2 时,我想刷新或重建 JFrame,以便为组件使用功能/样式(在本例中为 Font)的新值 (testButton1
和 2),通过更改 currentFont
然后重新绘制。
我没有收到任何错误,但是框架
和组件没有被重建/刷新,即,单击样式按钮时没有任何反应。
关于如何实现这项工作有什么想法吗?或者我可以使用任何其他方法来获得所需的效果?
//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;
}
}
最佳答案
您可以将需要刷新样式的组件存储在列表中:
private static List<JComponent> components = new ArrayList<JComponent>();
然后在您的 basicButton()
方法中添加新组件以刷新组件:components.add(button);
然后在 ActionListener
中,您可以执行下一行来刷新样式:
for(JComponent c : components){
c.setFont(currentFont);
}
或者您可以将组件直接传递给 ActionListener
,如下所示:
JButton b1;
JButton b2;
mainPanel.add(b1 = basicButton("Button1"));
mainPanel.add(b2 = basicButton("Button2"));
mainPanel.add(style1Button("Style 1",b1,b2));
和style1Button()
代码:
public static JButton style1Button(String title,final JComponent... components) {
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;
for(JComponent c : components){
c.setFont(currentFont);
}
frame.repaint();
}
});
return button;
}
关于java - 从监听器/事件更改 JComponent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20668281/