import javax.swing.*;
import java.awt.*;
public class Main extends JPanel {
private int baseColor = 0; // значение цвета
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
int c = (i + j) * 255 / 6;
// добавляем пользовательский цвет
int colorValue = Math.min(255, c + baseColor);
g.setColor(new Color(colorValue, colorValue, colorValue));
g.fillRect(i * getWidth() / 4,
j * getHeight() / 4,
getWidth() / 4,
getHeight() / 4);
}
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("Градиент");
Main panel = new Main();
JTextField input = new JTextField(5);
JButton button = new JButton("Изменить цвет");
// панель для управления
JPanel controlPanel = new JPanel();
controlPanel.add(new JLabel("Введите 0-255:"));
controlPanel.add(input);
controlPanel.add(button);
// обработка кнопки
button.addActionListener(e -> {
try {
int value = Integer.parseInt(input.getText());
if (value < 0 || value > 255) {
JOptionPane.showMessageDialog(frame, "Введите число от 0 до 255");
return;
}
panel.baseColor = value;
panel.repaint(); // перерисовка панели
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(frame, "Введите число!");
}
});
frame.setLayout(new BorderLayout());
frame.add(panel, BorderLayout.CENTER);
frame.add(controlPanel, BorderLayout.SOUTH);
frame.setSize(400, 450);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}