【问题标题】:Java - Set half of a JFrame to a specific colorJava - 将 JFrame 的一半设置为特定颜色
【发布时间】:2013-12-13 19:19:18
【问题描述】:

我试图设置 JFrame 的水平一半以显示光标所在的颜色。 这是我目前得到的。

enter code here
package finalproject;

import java.awt.Canvas;
import javax.swing.JFrame;
import java.awt.AWTException;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.MouseInfo;
import java.awt.Point;
import java.awt.Robot;
import java.awt.PointerInfo;
import javax.swing.JLabel;
import javax.swing.*;
import java.awt.event.MouseMotionListener;
import java.awt.Container;
import java.awt.Graphics;
import java.awt.*;
public class FinalProject {
    public static void main(String[] args) throws AWTException {
        JFrame frame = new JFrame();
        JLabel rgbLabel = new JLabel();
        rgbLabel.setVerticalAlignment(SwingConstants.NORTH);
        rgbLabel.setHorizontalAlignment(SwingConstants.CENTER);
        frame.setLocationRelativeTo(null);
        frame.add(rgbLabel);
        rgbLabel.setAlignmentX(50);
        rgbLabel.setAlignmentY(10);
        rgbLabel.setVisible(true);
        frame.setLocation(650, 350);
        frame.setVisible(true);
        frame.pack();
        frame.setTitle(display.TITLE);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(display.WIDTH, display.HEIGHT);
        frame.setResizable(true);
        frame.setVisible(true);
        while (true){
            PointerInfo cursorLocation = MouseInfo.getPointerInfo();
            Point position = cursorLocation.getLocation(); 
            int x = (int)position.getX(); 
            int y = (int)position.getY();
            Robot robot = new Robot();
            Color pixelColor = robot.getPixelColor(x, y);
            int colorRed = pixelColor.getRed(); 
            int colorGreen = pixelColor.getGreen(); 
            int colorBlue = pixelColor.getBlue();
            rgbLabel.setText("Red: " + colorRed + " Green: " + colorGreen + " Blue: "     + colorBlue + "\n" );

            }
        }
    public static class display {
        public static final int WIDTH = 250;
        public static final int HEIGHT = 135;
        public static final String TITLE = "Colorblind Assistant";
    }
}

我知道放

frame.getContantPane().setBackground(pixelColor);

在while循环下会将整个帧更改为颜色,但我只需要帧的下半部分为该颜色。

我们将不胜感激。 谢谢。

【问题讨论】:

  • 用适当的paint 方法在一半的框架上绘制一个彩色框(例如,扩展 JFrame)。背景颜色在“清除”期间填充整个图形区域,并在子级渲染之前完成。
  • 看看this example 寻求帮助;)

标签: java swing colors jframe setbackground


【解决方案1】:
  • 使用 MouseListener,而不是 while (true),它会占用 Swing 事件线程。
  • 将所有代码从 main 方法中取出并放入适当的类中。 main 方法除了启动您的程序之外什么都不做。
  • 让您的 JFrame 在 GridLayout 中保存两个 JPanel,并在其中一个 JPanel 的背景中由 MouseListener 设置。

【讨论】:

    猜你喜欢
    • 2010-11-08
    • 2021-05-24
    • 2021-04-19
    • 1970-01-01
    • 1970-01-01
    • 2017-06-02
    • 1970-01-01
    • 2010-11-29
    • 2014-09-24
    相关资源
    最近更新 更多