2013-11-27 33 views
1

我試圖設置JFrame的水平一半來顯示光標所在的顏色。 這是我到目前爲止。Java - 將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循環下會整體框架改變顏色,但我只需要在框架的下半部分是顏色。

一些幫助,將不勝感激。 謝謝。

+0

在適當的'paint'方法(例如擴展JFrame)中在一半的框架上繪製一個彩色框。背景顏色在「清除」期間填充整個圖形區域,並在兒童在其上呈現之前完成。 – user2864740

+0

查看http://stackoverflow.com/questions/6118737/how-to-draw-in-jpanel-swing-graphics-java – user2864740

+0

看看[這個例子](http://stackoverflow.com/questions/13061122/getting-rgb-value-from-under-mouse-cursor/13061320#13061320)尋求幫助;) – MadProgrammer

回答

2
  • 使用一個MouseListener,而不是while (true),這將綁定Swing事件線程。
  • 將所有代碼從主要方法中取出並轉換爲適當的類。除了設置程序運行之外,主要方法不應該做任何事情。
  • 讓您的JFrame在GridLayout中保存兩個JPanel,並且在其中一個JPanel的背景中由MouseListener設置。
+0

YESSSSS !!!!!!!!!!!!謝謝!!!!!!!!!!!!!! – MiguelB

+0

@MiguelB:不客氣。 –

相關問題