简体   繁体   English

如何修改此程序以包含八个 colors 的 JList,可用于更改此小程序的背景颜色?

[英]How do I modify this program to include a JList of eight colors that can be used the change the background color of this applet?

I am trying to add a JList of eight items so a user can change the background color of the applet here.我正在尝试添加一个包含八个项目的 JList,以便用户可以在此处更改小程序的背景颜色。 I am not sure in which section I should include these added details, or where exactly to turn to.我不确定我应该在哪个部分包含这些添加的细节,或者确切地转向哪里。 The book I am using is outdated and I would just like to get some advice or a solution as to how to alter this code to carry out a background change function.我正在使用的这本书已经过时了,我想就如何更改此代码以执行背景更改 function 获得一些建议或解决方案。

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

public class Ch12_PrExercise1 extends JApplet {

    int number;

    @Override
    public void init() {
        String input;

        input = JOptionPane.showInputDialog("Enter a digit");

        number = Integer.parseInt(input);
    }

    @Override
    public void paint(Graphics g) {
        super.paint(g);

        switch (number) {
            case 0:
                g.fillRect(50, 25, 125, 25);
                g.fillRect(50, 50, 25, 175);
                g.fillRect(50, 200, 125, 25);
                g.fillRect(150, 25, 25, 175);
                break;

            case 1:
                g.fillRect(75, 25, 75, 25);
                g.fillRect(100, 50, 50, 125);
                g.fillRect(50, 175, 150, 25);
                break;

            case 2:
                g.fillRect(50, 25, 125, 25);
                g.fillRect(150, 50, 25, 50);
                g.fillRect(50, 100, 125, 25);
                g.fillRect(50, 175, 125, 25);
                g.fillRect(50, 125, 25, 50);
                break;

            case 3:
                g.fillRect(150, 50, 25, 175);
                g.fillRect(50, 50, 100, 25);
                g.fillRect(50, 125, 100, 25);
                g.fillRect(50, 200, 100, 25);
                break;

            case 4:
                g.fillRect(50, 25, 25, 75);
                g.fillRect(50, 100, 100, 25);
                g.fillRect(150, 25, 25, 175);
                break;

            case 5:
                g.fillRect(50, 25, 125, 25);
                g.fillRect(50, 50, 25, 50);
                g.fillRect(50, 100, 125, 25);
                g.fillRect(50, 175, 125, 25);
                g.fillRect(150, 125, 25, 50);
                break;

            case 6:
                g.fillRect(50, 25, 125, 25);
                g.fillRect(50, 50, 25, 50);
                g.fillRect(50, 100, 125, 25);
                g.fillRect(50, 175, 125, 25);
                g.fillRect(150, 125, 25, 50);
                g.fillRect(50, 125, 25, 50);
                break;

            case 7:
                g.fillRect(50, 25, 125, 25);
                g.fillRect(150, 50, 25, 150);
                break;

            case 8:
                g.fillRect(50, 25, 125, 25);
                g.fillRect(50, 50, 25, 50);
                g.fillRect(50, 100, 125, 25);
                g.fillRect(50, 175, 125, 25);
                g.fillRect(150, 125, 25, 50);
                g.fillRect(50, 125, 25, 50);
                g.fillRect(150, 50, 25, 50);
                break;

            case 9:
            default:
                g.fillRect(50, 25, 125, 25);
                g.fillRect(50, 50, 25, 50);
                g.fillRect(50, 100, 125, 25);
                g.fillRect(50, 175, 125, 25);
                g.fillRect(150, 125, 25, 50);
                g.fillRect(150, 50, 25, 50);
                break;
        }
    }
}

Here is an implementation with a few tweaks:这是一个带有一些调整的实现:

  1. It paint to a panel rather than a top-level container such as an applet as the custom painted component.它绘制到一个面板而不是一个顶级容器,例如作为自定义绘制组件的小程序。
  2. It uses a frame rather than an applet to display the panel.它使用框架而不是小程序来显示面板。
  3. It defines a NamedColor to encapsulate a name and a color.它定义了一个NamedColor来封装名称和颜色。 This is handy for the list, as it means it can contain named colors rather than using strings or indexes to map to a color.这对于列表来说很方便,因为这意味着它可以包含名为 colors 而不是使用 map 到颜色的字符串或索引。
  4. The custom painted component ( ColoredNumberPanel ) defines a preferred size, so the top level container can be packed to fit it properly.自定义绘制组件 ( ColoredNumberPanel ) 定义了首选大小,因此可以打包顶级容器以适合它。

在此处输入图像描述

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

public class Ch12_PrExercise1_Panel {

    private JComponent ui = null;
    private final NamedColor[] namedColors = {
        new NamedColor("CYAN", Color.CYAN),
        new NamedColor("PINK", Color.PINK),
        new NamedColor("GREEN", Color.GREEN),
        new NamedColor("MAGENTA", Color.MAGENTA),
        new NamedColor("ORANGE", Color.ORANGE),
        new NamedColor("RED", Color.RED),
        new NamedColor("WHITE", Color.WHITE),
        new NamedColor("YELLOW", Color.YELLOW)
    };

    Ch12_PrExercise1_Panel() {
        initUI();
    }

    public final void initUI() {
        if (ui != null) {
            return;
        }
        SpinnerNumberModel numberModel = new SpinnerNumberModel(0, 0, 9, 1);
        JSpinner spinner = new JSpinner(numberModel);
        JOptionPane.showMessageDialog(null, spinner, "Which Number?", JOptionPane.QUESTION_MESSAGE);

        ui = new JPanel(new BorderLayout(4, 4));
        ui.setBorder(new EmptyBorder(4, 4, 4, 4));

        DefaultListModel listModel = new DefaultListModel();
        for (NamedColor namedColor : namedColors) {
            listModel.addElement(namedColor);
        }
        final JList list = new JList(listModel);
        list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        list.setVisibleRowCount(8);
        ui.add(new JScrollPane(list), BorderLayout.LINE_START);

        final ColoredNumberPanel coloredNumberPanel = 
                new ColoredNumberPanel(numberModel.getNumber().intValue());
        ui.add(coloredNumberPanel);

        ListSelectionListener listSelectionListener = new ListSelectionListener() {

            @Override
            public void valueChanged(ListSelectionEvent e) {
                if (!e.getValueIsAdjusting()) {
                    NamedColor namedColor = (NamedColor)list.getSelectedValue();
                    Color color = namedColor.color;
                    coloredNumberPanel.setBackground(color);
                }
            }
        };
        list.addListSelectionListener(listSelectionListener);
    }

    public JComponent getUI() {
        return ui;
    }

    public static void main(String[] args) {
        Runnable r = () -> {
            try {
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            } catch (Exception useDefault) {
            }
            Ch12_PrExercise1_Panel o = new Ch12_PrExercise1_Panel();

            JFrame f = new JFrame(o.getClass().getSimpleName());
            f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            f.setLocationByPlatform(true);

            f.setContentPane(o.getUI());
            f.pack();
            f.setMinimumSize(f.getSize());

            f.setVisible(true);
        };
        SwingUtilities.invokeLater(r);
    }
}

class ColoredNumberPanel extends JPanel {

    int number;
    Dimension preferredSize = new Dimension(200, 250);

    ColoredNumberPanel(int number) {
        this.number = number;
    }

    /**
     * Note: The correct method to do custom painting in a JComponent (like
     * JPanel) is paintComponent(..) rather than paint(..) as used for an
     * applet/frame/window..
     */
    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g); // this also needs to be changed

        switch (number) {
            case 0:
                g.fillRect(50, 25, 125, 25);
                g.fillRect(50, 50, 25, 175);
                g.fillRect(50, 200, 125, 25);
                g.fillRect(150, 25, 25, 175);
                break;

            case 1:
                g.fillRect(75, 25, 75, 25);
                g.fillRect(100, 50, 50, 125);
                g.fillRect(50, 175, 150, 25);
                break;

            case 2:
                g.fillRect(50, 25, 125, 25);
                g.fillRect(150, 50, 25, 50);
                g.fillRect(50, 100, 125, 25);
                g.fillRect(50, 175, 125, 25);
                g.fillRect(50, 125, 25, 50);
                break;

            case 3:
                g.fillRect(150, 50, 25, 175);
                g.fillRect(50, 50, 100, 25);
                g.fillRect(50, 125, 100, 25);
                g.fillRect(50, 200, 100, 25);
                break;

            case 4:
                g.fillRect(50, 25, 25, 75);
                g.fillRect(50, 100, 100, 25);
                g.fillRect(150, 25, 25, 175);
                break;

            case 5:
                g.fillRect(50, 25, 125, 25);
                g.fillRect(50, 50, 25, 50);
                g.fillRect(50, 100, 125, 25);
                g.fillRect(50, 175, 125, 25);
                g.fillRect(150, 125, 25, 50);
                break;

            case 6:
                g.fillRect(50, 25, 125, 25);
                g.fillRect(50, 50, 25, 50);
                g.fillRect(50, 100, 125, 25);
                g.fillRect(50, 175, 125, 25);
                g.fillRect(150, 125, 25, 50);
                g.fillRect(50, 125, 25, 50);
                break;

            case 7:
                g.fillRect(50, 25, 125, 25);
                g.fillRect(150, 50, 25, 150);
                break;

            case 8:
                g.fillRect(50, 25, 125, 25);
                g.fillRect(50, 50, 25, 50);
                g.fillRect(50, 100, 125, 25);
                g.fillRect(50, 175, 125, 25);
                g.fillRect(150, 125, 25, 50);
                g.fillRect(50, 125, 25, 50);
                g.fillRect(150, 50, 25, 50);
                break;

            case 9:
            default:
                g.fillRect(50, 25, 125, 25);
                g.fillRect(50, 50, 25, 50);
                g.fillRect(50, 100, 125, 25);
                g.fillRect(50, 175, 125, 25);
                g.fillRect(150, 125, 25, 50);
                g.fillRect(150, 50, 25, 50);
                break;
        }
    }

    @Override
    public Dimension getPreferredSize() {
        return preferredSize;
    }
}

class NamedColor {

    String name;
    Color color;

    public NamedColor(String name, Color color) {
        this.name = name;
        this.color = color;
    }

    @Override 
    public String toString() {
        return name;
    }
}

General Tips一般提示

  1. Why code an applet?为什么要编写小程序? If it is due to the teacher specifying it, please refer them to Why CS teachers should stop teaching Java applets .如果是老师指定的,请参考为什么CS老师应该停止教Java小程序
  2. Applets have become completely unworkable for sites dealing to 'all comers' on the internet.对于在 Internet 上处理“所有来者”的网站,Applet 已经完全无法使用。 Safari and FF both block applets by default, and Chrome and IE are set to completely remove support for them. Safari 和 FF 默认都阻止小程序,Chrome 和 IE 设置为完全取消对它们的支持。 It is best to transition away from applets to pure JS/HTML sooner rather than later.最好尽早从 applet 过渡到纯 JS/HTML。
  3. Use a logical and consistent form of indenting code lines and blocks.使用逻辑一致的缩进代码行和块形式。 The indentation is intended to make the flow of the code easier to follow.缩进旨在使代码流更易于遵循。 Most IDEs have a keyboard shortcut specifically for formatting code.大多数 IDE 都有专门用于格式化代码的键盘快捷键。

Here is a sample of how you should be doing graphics.这是您应该如何做图形的示例。 There is much more to it than this.远不止于此。 I also provide:我还提供:

  • A JList of colors so you could see one way of doing it. colors 的JList ,因此您可以看到一种方法。
  • An inputPanel with a JLabel and JFormattedTextField to accept input instead of a JOptionPane as it is it more easily positioned and allows format control.一个带有JLabelJFormattedTextField的 inputPanel 来接受输入而不是JOptionPane ,因为它更容易定位并允许格式控制。
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;

import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.border.LineBorder;
import javax.swing.text.MaskFormatter;

public class Ch12_PrExercise1 extends JPanel {
    int number;

    JFormattedTextField textField = null;
    JFrame frame = new JFrame("Ch12 PrExercise1");

    // add more if you want.
    MyColor[] colors = { new MyColor(Color.red, "Red"),
            new MyColor(Color.blue, "Blue"),
            new MyColor(Color.green, "Green"),
            new MyColor(Color.orange, "Orange"),
            new MyColor(Color.magenta, "Magenta"),
            new MyColor(new Color(155, 0, 155), "Purple"),
            new MyColor(Color.yellow, "Yellow"),
            new MyColor(new Color(128, 128, 128), "Gray") };

    Color color = Color.red;

    class MyColor {
        Color color;
        String name;

        public MyColor(Color color, String name) {
            this.color = color;
            this.name = name;
        }

        public String toString() {
            return name;
        }
    }

    public Ch12_PrExercise1() {
        setPreferredSize(new Dimension(250, 300));
        frame.add(this);
        // create JList here
        JList<MyColor> colorList = new JList<>(colors);
        colorList.setBorder(new LineBorder(Color.black, 1));
        try {
            textField =
                    new JFormattedTextField(new MaskFormatter("#"));
        } catch (Exception e) {
        }
        textField.setColumns(3);
        setLayout(new BorderLayout());
        add(colorList, BorderLayout.EAST);
        JPanel inputPanel = new JPanel();
        inputPanel.add(new JLabel("Please enter a digit: "));
        inputPanel.add(textField);
        add(inputPanel, BorderLayout.SOUTH);

        textField.addActionListener((ae) -> {
            String text = textField.getText();
            number = Integer.parseInt(text);
            textField.setText("");
            repaint();
        });

        // gets the selected color in the JList, sets color to that
        // color and issues a repaint.
        colorList.addListSelectionListener((lde) -> {
            color = ((JList<MyColor>) lde.getSource())
                    .getSelectedValue().color;
            repaint();
        });

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities
                .invokeLater(() -> new Ch12_PrExercise1().start());
    }

    public void start() {
        String input;

    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        // from the list of colors.
        g.setColor(color);
        switch (number) {
            case 0:
                g.fillRect(50, 25, 125, 25);
                g.fillRect(50, 50, 25, 175);
                g.fillRect(50, 200, 125, 25);
                g.fillRect(150, 25, 25, 175);
                break;

            case 1:
                g.fillRect(75, 25, 75, 25);
                g.fillRect(100, 50, 50, 125);
                g.fillRect(50, 175, 150, 25);
                break;

            case 2:
                g.fillRect(50, 25, 125, 25);
                g.fillRect(150, 50, 25, 50);
                g.fillRect(50, 100, 125, 25);
                g.fillRect(50, 175, 125, 25);
                g.fillRect(50, 125, 25, 50);
                break;

            case 3:
                g.fillRect(150, 50, 25, 175);
                g.fillRect(50, 50, 100, 25);
                g.fillRect(50, 125, 100, 25);
                g.fillRect(50, 200, 100, 25);
                break;

            case 4:
                g.fillRect(50, 25, 25, 75);
                g.fillRect(50, 100, 100, 25);
                g.fillRect(150, 25, 25, 175);
                break;

            case 5:
                g.fillRect(50, 25, 125, 25);
                g.fillRect(50, 50, 25, 50);
                g.fillRect(50, 100, 125, 25);
                g.fillRect(50, 175, 125, 25);
                g.fillRect(150, 125, 25, 50);
                break;

            case 6:
                g.fillRect(50, 25, 125, 25);
                g.fillRect(50, 50, 25, 50);
                g.fillRect(50, 100, 125, 25);
                g.fillRect(50, 175, 125, 25);
                g.fillRect(150, 125, 25, 50);
                g.fillRect(50, 125, 25, 50);
                break;

            case 7:
                g.fillRect(50, 25, 125, 25);
                g.fillRect(150, 50, 25, 150);
                break;

            case 8:
                g.fillRect(50, 25, 125, 25);
                g.fillRect(50, 50, 25, 50);
                g.fillRect(50, 100, 125, 25);
                g.fillRect(50, 175, 125, 25);
                g.fillRect(150, 125, 25, 50);
                g.fillRect(50, 125, 25, 50);
                g.fillRect(150, 50, 25, 50);
                break;

            case 9:
            default:
                g.fillRect(50, 25, 125, 25);
                g.fillRect(50, 50, 25, 50);
                g.fillRect(50, 100, 125, 25);
                g.fillRect(50, 175, 125, 25);
                g.fillRect(150, 125, 25, 50);
                g.fillRect(150, 50, 25, 50);
                break;
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM