Note that there are some explanatory texts on larger screens.

plurals
  1. POI can use getActionCommand to change the label content, but I can't use it to change the color?
    primarykey
    data
    text
    <p>So with the help of others here I finally managed to code a button that alternates the label "Hello World!" to "Hello Universe!" and back again. I used the code below, and used the same way to try and change the color, but it didn't work as expected. I've been searching for hours on this, but with no avail. Thank you for reading, anything helps!</p> <p>Code: </p> <pre><code>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(); } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload