java jbutton边框颜色_在Java Swing中更改JButton的边框颜色,以保留插图

这篇博客介绍了如何在JavaSwing中修改JButton的边框颜色,同时保持按钮的原始插图不变。通过使用CompoundBorder,可以在不删除填充的情况下,将边框颜色更改为红色,确保与标准JButton的外观一致。文章还提醒不要扩展JFrame,而应创建其实例,并提到在EDT中执行 Swing 应用程序的重要性。
摘要由CSDN通过智能技术生成

我想更改Java Swing中JButton组件的边框颜色.

我尝试了以下方法:

package com.example.test;

import java.awt.Color;

import java.util.logging.Level;

import java.util.logging.Logger;

import javax.swing.BorderFactory;

import javax.swing.JButton;

import javax.swing.JFrame;

import javax.swing.JPanel;

import javax.swing.UIManager;

import javax.swing.UnsupportedLookAndFeelException;

public class Test extends JFrame {

public Test() {

JPanel panel = new JPanel();

JButton button1 = new JButton("Test Button 1");

JButton button2 = new JButton("Test Button 2");

button2.setBorder(BorderFactory.createLineBorder(Color.RED));

panel.add(button1);

panel.add(button2);

this.add(panel);

setSize(400, 400);

setVisible(true);

}

public static void main(String[] args) {

try {

UIManager.setLookAndFeel( UIManager.getCrossPlatformLookAndFeelClassName() );

} catch (ClassNotFoundException ex) {

Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);

} catch (InstantiationException ex) {

Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);

} catch (IllegalAccessException ex) {

Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);

} catch (UnsupportedLookAndFeelException ex) {

Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);

}

Test t = new Test();

}

}

这会生成两个按钮,在button2组件上,我尝试更改边框颜色,但删除了填充.无论如何,是否可以保留标准JButton的原始插图并仅更改颜色?

注意:我认为在分配新的边框时,插图将被移除.但是我对此不是100%肯定的.

b31a0543a90ba6fe492c60fcccdd232e.png

解决方法:

而不是创建LineBorder,请使用CompoundBorder:

button2.setBorder(BorderFactory.createCompoundBorder(

BorderFactory.createLineBorder(Color.RED, 1),

BorderFactory.createEmptyBorder(

button1.getBorder().getBorderInsets(button1).top,

button1.getBorder().getBorderInsets(button1).left,

button1.getBorder().getBorderInsets(button1).bottom,

button1.getBorder().getBorderInsets(button1).right)));

我为button1设置了BorderInsets,以便它们都具有相同的大小.

我的答案基于this question的@MadProgrammer答案

ad6f0c5c4bf7b53c62fa6ba149f68824.png

顺便说一句,不要扩展JFrame,而是为其创建一个实例,如果您确实需要扩展组件,可以将其作为JPanel:Extends JFrame vs. creating it inside the program

也别忘了打电话

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

在您的JFrame实例上,以便您的程序在关闭时终止.

而且您也错过了将程序放在EDT上的详细信息,请参见this answer

标签:border,swing,jbutton,java

来源: https://codeday.me/bug/20191024/1922394.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值