因此,在其他人的帮助下,我终于设法编写了一个交替标签“Hello World!”的按钮。到“你好宇宙!” 然后再回来。我使用下面的代码,并使用相同的方式尝试更改颜色,但它没有按预期工作。我一直在寻找几个小时,但无济于事。感谢您的阅读,有什么帮助!
代码:
package game;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Javagame extends JPanel implements ActionListener{
protected JButton changetext;
protected JButton red;
protected JButton green;
private JLabel label;
public Javagame() {
add(changetext = new JButton("Button!"));
changetext.setPreferredSize(new Dimension(50, 50));
changetext.setActionCommand("change");
add(red = new JButton("Red"));
red.setPreferredSize(new Dimension(50, 50));
red.setActionCommand("changecolorRed");
add(green = new JButton("Green"));
green.setPreferredSize(new Dimension(50, 50));
green.setActionCommand("changecolorGreen");
changetext.addActionListener(this);
label = new JLabel("Hello World!", SwingConstants.CENTER);
label.setFont(new Font("Arial", Font.BOLD, 20));
label.setForeground(new Color(0x009900));
setLayout(new BorderLayout());
add(label, BorderLayout.CENTER);
add(changetext, BorderLayout.NORTH);
add(red, BorderLayout.WEST);
add(green, BorderLayout.EAST);
}
public void actionPerformed(ActionEvent e) {
if ("change".equals(e.getActionCommand())) {
label.setText("Hello Universe!");
changetext.setActionCommand("changeBack");
}
if ("changeBack".equals(e.getActionCommand())) {
label.setText("Hello World!");
changetext.setActionCommand("change");
}
if ("changecolorRed".equals(e.getActionCommand())) {
label.setForeground(new Color(0xFF0000));
}
if ("changecolorGreen".equals(e.getActionCommand())) {
label.setForeground(new Color(0x009900));
}
}
private static void createWindow(){
JFrame frame = new JFrame("Javagame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension(500,500));
JPanel panel = new JPanel(new BorderLayout());
Javagame newContentPane = new Javagame();
newContentPane.setOpaque(true);
frame.setContentPane(newContentPane);
frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
createWindow();
}
}