我想将我JToggleButton
的设置为禁用状态,即用户无法通过单击来切换它。我试过btn.setEnabled(false);
了,但它使我的图标变灰,我不想要那个。是否有任何其他方法不会使图标变灰,但不会让用户切换按钮?
问问题
1377 次
3 回答
2
但要显示我自己的自定义图标。
您还可以指定切换按钮要使用的“禁用图标”。它可能是您默认使用的相同图标,也可能是稍微不同的图标。
当您指定自己的图标时,您不会获得灰色效果。
于 2015-12-27T23:46:52.940 回答
2
您可以取消图标与按钮的关联,并使用适当的布局约束来提供关系的视觉线索,而是使用 aJLabel
来显示图标,例如...
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JToggleButton;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
} catch (IOException ex) {
ex.printStackTrace();
}
}
});
}
public class TestPane extends JPanel {
public TestPane() throws IOException {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
BufferedImage img = ImageIO.read(new File("/Volumes/Disk02/Dropbox/MegaTokyo/thumnails/2.jpg"));
JLabel label = new JLabel(new ImageIcon(img));
add(label, gbc);
JToggleButton btn = new JToggleButton("Click");
btn.setEnabled(false);
add(btn, gbc);
}
}
}
就个人而言,我认为 aJCheckBox
可能更适合这种风格
于 2015-12-27T23:42:08.117 回答
0
只允许单击 JToggleButton 一次。
如果有 N 个 JToggleButtons,则声明 N 个 int 类变量等于 0。
(int jtbIntValue1=0, jtbIntValue1=0 ,...jtbIntValueN = 0)
在允许用户按下 JToggle 按钮之前检查 if(jtbIntValue N != 0)
当单击 JToggle 按钮时,更新相应的 JToggleButton int 值等于 1。(从 jtbIntValue N = 0 到 jtbIntValue N = 1)。
public class Development1 { int b1 = 0 ; // For one Button public Development1() { ........... ........... JToggleButton jtb1 = new JToggleButton(); jtb1.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e1) { if(b1!=1) { if(SwingUtilities.isRightMouseButton(e1) && e1.getClickCount() == 1) { jtb1.setIcon(icRight); // Or do whatever you want to } else if(SwingUtilities.isLeftMouseButton(e1) && e1.getClickCount() == 1) { jtb1.setIcon(icLeft); } } b1 = 1; } });
于 2018-09-16T16:57:45.820 回答