首页 \ 问答 \ 使用JComboBox Java Swing选择颜色(Pick Color with JComboBox Java Swing)

使用JComboBox Java Swing选择颜色(Pick Color with JComboBox Java Swing)

我有一个JComboBox,我希望用户选择颜色。 JComboBox只显示颜色,没有任何文字。 我想出了这个解决方案。 请告诉我这是好还是应该避免,为什么。 我是Swing和Java的新手,所以请耐心等待:)

public class ToolBar{
    private MainFrame mainFrame;

    public ToolBar (MainFrame mainFrame) {
        this.mainFrame = mainFrame;
    }

    public JPanel getToolBar(){

        JPanel toolbarPanel = new JPanel(new FlowLayout(FlowLayout.LEADING,2,2));
        toolbarPanel.setPreferredSize(new Dimension(mainFrame.getScreenWidth(),60));
        toolbarPanel.setBorder(BorderFactory.createLineBorder(Color.gray));

        JButton fillButton = new JButton("Fill: ");
        fillButton.setPreferredSize(new Dimension(60,20));
        //fillButton.setBackground(Color.red);
        toolbarPanel.add(fillButton);

        String[] test = {" ", " " , " " , " " , " " , " "};
        JComboBox colorBox = new JComboBox(test);
        colorBox.setMaximumRowCount(5);
        colorBox.setPreferredSize(new Dimension(50,20));
        colorBox.setRenderer(new MyCellRenderer());
        toolbarPanel.add(colorBox);

        return toolbarPanel;
    }
    class MyCellRenderer extends JLabel implements ListCellRenderer {  
         public MyCellRenderer() {  
             setOpaque(true);  
         }  
         public Component getListCellRendererComponent(  
             JList list,  
             Object value,  
             int index,  
             boolean isSelected,  
             boolean cellHasFocus)  
         {  
             setText(value.toString()); 
             switch (index) {
                case 0:  setBackground(Color.white);
                break;
                case 1:  setBackground(Color.red);
                break;
                case 2:  setBackground(Color.blue);
                break;
                case 3:  setBackground(Color.yellow);
                break;
                case 4:  setBackground(Color.green);
                break;
                case 5:  setBackground(Color.gray);
                break;
             }
             return this;  
         }  
    }
}

这很好用。 它在JComboBox中显示不同颜色的空选择元素。 问题是当用户选择颜色时,JComboBox中的选择颜色不会改变。 我应该添加哪些代码行,以便当用户从列表中选择颜色时,JComboBox字段中会显示颜色?

我尝试了一些解决方案,但结果是当用户选择JComboBox中的颜色​​选择时总是变为灰色...

我已经查看了几个类似的问题但我无法弄清楚当选择完成时哪部分代码正在处理JComboBox的颜色变化...


I have a JComboBox where I want for user to select color. JComboBox is displaying just the colors, without any text. I've come up with this solution. Please advise me if this is good or it should be avoided and why. I am new to Swing and Java in general so please be patient :)

public class ToolBar{
    private MainFrame mainFrame;

    public ToolBar (MainFrame mainFrame) {
        this.mainFrame = mainFrame;
    }

    public JPanel getToolBar(){

        JPanel toolbarPanel = new JPanel(new FlowLayout(FlowLayout.LEADING,2,2));
        toolbarPanel.setPreferredSize(new Dimension(mainFrame.getScreenWidth(),60));
        toolbarPanel.setBorder(BorderFactory.createLineBorder(Color.gray));

        JButton fillButton = new JButton("Fill: ");
        fillButton.setPreferredSize(new Dimension(60,20));
        //fillButton.setBackground(Color.red);
        toolbarPanel.add(fillButton);

        String[] test = {" ", " " , " " , " " , " " , " "};
        JComboBox colorBox = new JComboBox(test);
        colorBox.setMaximumRowCount(5);
        colorBox.setPreferredSize(new Dimension(50,20));
        colorBox.setRenderer(new MyCellRenderer());
        toolbarPanel.add(colorBox);

        return toolbarPanel;
    }
    class MyCellRenderer extends JLabel implements ListCellRenderer {  
         public MyCellRenderer() {  
             setOpaque(true);  
         }  
         public Component getListCellRendererComponent(  
             JList list,  
             Object value,  
             int index,  
             boolean isSelected,  
             boolean cellHasFocus)  
         {  
             setText(value.toString()); 
             switch (index) {
                case 0:  setBackground(Color.white);
                break;
                case 1:  setBackground(Color.red);
                break;
                case 2:  setBackground(Color.blue);
                break;
                case 3:  setBackground(Color.yellow);
                break;
                case 4:  setBackground(Color.green);
                break;
                case 5:  setBackground(Color.gray);
                break;
             }
             return this;  
         }  
    }
}

This works ok. It is displaying empty selection elements in JComboBox with different colors. Problem is that when user selects color, color of selection in JComboBox does not change. Which lines of code should I add and where so that when user selects the color from a list that color is displayed in JComboBox field?

I tried some solutions but result was that when user picks color selection in JComboBox always changes to gray...

I've looked through several similar questions but I just can't figure out which part of code is dealing with changing of color of JComboBox when the selection has been done...


原文:https://stackoverflow.com/questions/18830098
更新时间:2022-05-18 08:05

最满意答案

你说过“子进程不应该以任何方式使用main()的参数”。 但是,我发现您的子进程正在使用argc 。 这不会打败你的限制吗?

你还说你想要“为每个角色写一个电话”。 您当前的实现使用一个调用来为每个参数写入,而不是每个字符。 这是一个错字吗? 如果没有,你会想要使用更像这样的东西:

char nul='\0', endl='\n';
for (a=1; a < argc; ++a) {
    for (c=0; c < strlen(argv[a]); ++c) {
        write(fdest[1], &argv[a][c], 1);
    }
    write(fdest[1], &nul, 1);
}
write(fdest[1], &endl, 1);

这将一次写入一个字符,每个参数作为以NULL结尾的字符串和最后的换行符。 换行符仅用作标记,表示不再发送数据(并且可以安全使用,因为您不会在CLI参数中传递换行符)。

子进程只需要是一个循环,逐个读取传入的字节,如果字节不是'\0''\n' ,则递增计数器。 当它读取换行符时,它会突破输入处理循环并报告计数器的值。


You said that "the child process should not use the arguments to main() in any way whatsoever". However, I see that your child process is using argc. Doesn't this defeat your restriction?

You also say that you want "one call to write for each character". Your current implementation uses one call to write for each argument, not each character. Was this a typo? If not, you will want to use something more like this:

char nul='\0', endl='\n';
for (a=1; a < argc; ++a) {
    for (c=0; c < strlen(argv[a]); ++c) {
        write(fdest[1], &argv[a][c], 1);
    }
    write(fdest[1], &nul, 1);
}
write(fdest[1], &endl, 1);

This will write one character at a time, with each argument as a NULL-terminated string and a newline character at the end. The newline is only there to serve as a marker to indicate that there is no more data to send (and is safe to use since you won't be passing in a newline in a CLI argument).

The child process will just need to be a loop that reads incoming bytes one by one and increments a counter if the byte is not '\0' or '\n'. When it reads the newline character, it breaks out of the input processing loop and reports the value of the counter.

相关问答

更多
  • 以下按预期工作。 错误不在代码的这一部分。 相反,由于内存问题导致幻像进程退出,导致无法创建渲染图像文件。 var Path = require('path') var Phantomjs = require('phantomjs2') var phantomjsPath = Phantomjs.path var childArgs = [ '--ignore-ssl-errors=true', '--ssl-protocol=any', '--web-security= ...
  • 有几个选择: ps -fp cat /proc//cmdline Linux中的/proc/有更多的信息,看看。 在其他Unix上可能会有所不同。 ps命令将无处不在, /proc东西是操作系统的特定的。 例如在AIX上, /proc没有cmdline 。 There are several options: ps -fp cat /proc//cmdline | sed -e "s/\x00/ /g"; echo There is more inf ...
  • 您根本无法隐藏命令行参数。 您可能希望检查如何清除进程命令行? 问题并在那里看到答案和评论。 如果你想坚持使用传递命令行参数,Raymond Chen就如何优雅地做了一篇非常好的帖子: http : //blogs.msdn.com/b/oldnewthing/archive/2003/12/11/56043.aspx 。 基本思想是使用匿名共享内存块来存储要在进程之间传递的实际数据,并将句柄的数值传递给它。 一个重量级的选择可能是加密/解密通过命令行传递的数据。 或附加一些生成的“秘密词”,以便被调用者可 ...
  • 您无法隐藏进程或启动它的完整命令。 无论你通过什么命令Runtime#exec都会显示,并且无法绕过它。 您的替代方案是: 将功能集成到您的应用程序中,而不是启动新进程。 如果它是您自己的本机代码,您可以使用JNI来运行它。 如果不是您的代码,您可以寻找能够完成其工作的Java库。 这就是我的建议。 通过IPC传递参数(stdin / out,tcp等)。 从临时配置文件中读取参数,该文件将在进程启动后删除。 You cannot hide the process or the full command t ...
  • 更新:根据我在2011年底发布的补丁,您现在可以使用mono-service的预期界面。 AFAICT没有办法 。 处理事务的惯用方法是使用app.config文件来包含配置节 (以XML格式)。 更新 这看起来很奇怪。 assebmblyArgs [ sic ]作为activationAttributes一部分传递给AppDomain.CreateInstanceAndUnwrap Method (String, String, Boolean, BindingFlags, Binder, Object[ ...
  • 对于WIndows,命令行参数保留在进程环境块( PEB )中,该块在创建进程时在用户进程地址空间中分配。 您可以阅读Windows Internals以获取更多详细信息。 这是第5章 - 进程,线程和作业的片段 。 我认为对于Unix风格来说它是一样的。 此数据需要位于进程内存中,以便进程本身可以访问它。 For WIndows, the command line arguments are kept in the process environment block (PEB), which is all ...
  • 如何将命令行参数传递给子进程? 你不需要做任何特别的事情; fork确保每个进程获取所有局部变量,包括argv 。 How do I pass command line arguments to a child process? You don't need to do anything special; fork ensures that each process gets all local variables, including argv.
  • 码: #include #include #include #include #include #include int main(int argc, char *argv[]) { pid_t pid; int status; int comm[2]; char buffer[BUFSIZ]; // ...
  • http://www.hanselman.com/blog/TheWeeklySourceCode31SingleInstanceWinFormsAndMicrosoftVisualBasicdll.aspx Visual Basic dll有一个WindowsFormsApplicationBase,它具有StartupNextInstance事件,您可以在其中获取第二个实例的参数,第二个实例可以在检测到其他实例时自行终止。 这已被问过C#:如何 - 接受新参数的单实例应用程序? http://www.h ...
  • 你说过“子进程不应该以任何方式使用main()的参数”。 但是,我发现您的子进程正在使用argc 。 这不会打败你的限制吗? 你还说你想要“为每个角色写一个电话”。 您当前的实现使用一个调用来为每个参数写入,而不是每个字符。 这是一个错字吗? 如果没有,你会想要使用更像这样的东西: char nul='\0', endl='\n'; for (a=1; a < argc; ++a) { for (c=0; c < strlen(argv[a]); ++c) { write(fdest ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)