這是我的代碼,我在其中實作了一個名為“開始/停止”的按鈕
- 當我按下按鈕一次時,我停止了按鈕上的文本,但我的按鈕顏色沒有改變。當我第二次按下此按鈕時,我開始作為按鈕的新名稱并在其上顯示為綠色。當按鈕上的文本為“停止”時,如何設定紅色?
這是我的代碼......
//Buttons for start and stop
btnStartStop = new JToggleButton("Start/Stop");
//btnStartStop.setEnabled(false);
btnStartStop.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (chk_start) {
tout_textPane.setText("Stop Magnetic Levitation Project");
btnStartStop.setText("start");
btnStartStop.setBackground(new Color(170, 255, 0));
btnStartStop.setForeground(Color.WHITE);
btnStartStop.setSelected(false);
CommandHandler(".plot");
chk_start = false;
} else {
tout_textPane.setText("Starting Magnetic Levitation Project");
btnStartStop.setText("stop");
btnStartStop.setBackground(Color.RED);
btnStartStop.setForeground(Color.WHITE);
btnStartStop.setSelected(true);
chk_start = true;
}
CommandHandler(".isr");
}
});
btnStartStop.setBounds(27, 10, 210, 21);
panel_ctrl_i.add(btnStartStop);
uj5u.com熱心網友回復:
我嘗試了兩個命令 btnStartStop.setBorderPainted(false); btnStartStop.setOpaque(false); 但仍然無法正常作業
對我來說很好,不,你似乎無法擺脫“選定”的亮點,這是由外觀和感覺控制的東西,完全是另一回事
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagLayout;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JToggleButton;
public class Main {
public static void main(String[] args) {
new Main();
}
public Main() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
GradientButton btn = new GradientButton();
btn.setOpaque(true);
btn.setBorderPainted(false);
btn.setBackground(Color.RED);
add(btn);
btn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (btn.isSelected()) {
btn.setBackground(Color.GREEN);
} else {
btn.setBackground(Color.RED);
}
}
});
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.dispose();
}
}
private static class GradientButton extends JToggleButton {
private GradientButton() {
super("Gradient Button");
setContentAreaFilled(false);
setFocusPainted(false); // used for demonstration
}
@Override
protected void paintComponent(Graphics g) {
final Graphics2D g2 = (Graphics2D) g.create();
g2.setPaint(new GradientPaint(
new Point(0, 0),
Color.WHITE,
new Point(0, getHeight()),
Color.PINK.darker()));
g2.fillRect(0, 0, getWidth(), getHeight());
g2.dispose();
super.paintComponent(g);
}
}
}
您還應該在jbutton 更改背景上進行搜索,因為它基本上是相同的問題
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/467711.html
下一篇:將選定欄位發送到另一個反應組件
