Why showing path instead of icon in table cell - java

I am newbie on java-swing. I am trying to add icon in table cell. but when i add ImageIcon in cell then it's showing only path instead of icon.
Here is my code.
public void createGUI(ArrayList<String> params, String type) {
try {
DefaultTableModel model = new DefaultTableModel();
model.addColumn("ParameterName");
model.addColumn("ParameterType");
model.addColumn("Operation");
for (int i = 0; i < params.size() - 4; i++) {
String param_name = params.get(i).toString().substring(0, params.get(i).toString().indexOf("["));
String param_type = params.get(i).toString().substring(params.get(i).toString().indexOf("[") + 1, params.get(i).toString().indexOf("]"));
//URL url = ClassLoader.getSystemClassLoader().getResource("");
ImageIcon image = new ImageIcon("/com/soastreamer/resources/delete_idle.png");
// JLabel label = new JLabel(image);
model.addRow(new Object[]{param_name, param_type.toUpperCase(),image});
}
Action delete = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
JTable table = (JTable) e.getSource();
int modelRow = Integer.valueOf(e.getActionCommand());
((DefaultTableModel) table.getModel()).removeRow(modelRow);
}
};
Here is image for clear understanding.
Please give me hint or any reference.
Thank you.

The problem lies with your TableModel, you have to tell the table that it has to render an image in that column overriding the getColumnClass(int column) method of the model.
Look at this answer by camickr.
UPDATE
Minimal example of a JTable with an ImageIcon using DefaultTableModel's renderer to paint it. I borrowed the updateRowHeights() code from this answer again by camickr, without it the icon was bigger than the row and wasn't fully displayed.
The important thing here is that now when the renderer calls getColumnClass(1), it gets ImageIcon.class so the code to render icons will be executed. By default this method would return Object.class and the renderer would ignore the fact that it's an icon.
import java.awt.BorderLayout;
import java.awt.Component;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;
public class ImageIconTable
{
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new ImageIconTable().initGUI();
}
});
}
public void initGUI()
{
JFrame frame = new JFrame();
DefaultTableModel tableModel = new DefaultTableModel()
{
#Override
public Class getColumnClass(int column)
{
if (column == 1) return ImageIcon.class;
return Object.class;
}
};
tableModel.addColumn("Row 1");
tableModel.addColumn("Icons Row");
tableModel.addRow(new Object[]{"This cell is an Object", new ImageIcon("icon.jpg")});
_table = new JTable(tableModel);
updateRowHeights();
frame.add(new JScrollPane(_table), BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
private void updateRowHeights()
{
try
{
for (int row = 0; row < _table.getRowCount(); row++)
{
int rowHeight = _table.getRowHeight();
for (int column = 0; column < _table.getColumnCount(); column++)
{
Component comp = _table.prepareRenderer(_table.getCellRenderer(row, column), row, column);
rowHeight = Math.max(rowHeight, comp.getPreferredSize().height);
}
_table.setRowHeight(row, rowHeight);
}
}
catch(ClassCastException e) {}
}
private JTable _table;
}
It looks like this:

First, I suggest you to use ImageIo.read() and use the BufferedImage returned as argument for your ImageIcon object.
Second, use the Class.getResource() facility
YourClass.class.getResource("/com/soastreamer/resources/delete_idle.png");
Then, everything should work.

Related

How to clear a selected cell in JTable?

I can select and set focus to cells in a JTable by clicking it, now I want to change the value on the focused cell. In order to change the value of it, I have to double click! Is there any way to clear/change the value of that focused cell (by single-clicking)?
I have tried jTable1.setValueAt("", row, column);, this clears the value in the background(It's not updated in the GUI/Same old value appears in the cell).
Table structure:
jTable1.addMouseListener(new MouseAdapter(){
#Override
public void mouseClicked(final MouseEvent e) {
if (e.getClickCount()==1){
final JTable jTable=(JTable)e.getSource();
final int row = jTable.getSelectedRow();
final int column = jTable.getSelectedColumn();
jTable1.editCellAt(row,column);
jTable1.getEditorComponent().requestFocus();
final Double valueInCell = (Double)jTable.getValueAt(row, column);
System.out.println(valueInCell);
}
}
});
If all you desire is to clear or change a JTable cell that holds Strings, why not simply call JTable's setValueAt(Object o, int row, int column) method? To clear, pass in "", to set to something different, then pass in a different String.
For example, my minimal reproducible example:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.*;
import java.util.Arrays;
import java.util.Vector;
import java.util.Random;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
#SuppressWarnings("serial")
public class TableFoo extends JPanel {
private static final Vector<String> COLUMN_NAME_VECTOR = new Vector<String>(
Arrays.asList(new String[] { "A", "B", "C" }));
private static final int COLUMN_COUNT = COLUMN_NAME_VECTOR.size();
private JTable table = new JTable();
public TableFoo() {
table.setFillsViewportHeight(true);
fillTableData();
MyMouse myMouse = new MyMouse();
table.addMouseListener(myMouse);
setLayout(new BorderLayout());
add(new JScrollPane(table), BorderLayout.CENTER);
}
class MyMouse extends MouseAdapter {
#Override
public void mousePressed(final MouseEvent e) {
final int row = table.getSelectedRow();
final int column = table.getSelectedColumn();
table.setValueAt("", row, column);
}
}
public void fillTableData() {
Vector<Vector<String>> matrix = new Vector<Vector<String>>();
int rowCount = 8;
for (int i = 0; i < rowCount ; i++) {
Vector<String> row = new Vector<String>();
for (int j = 0; j < COLUMN_COUNT; j++) {
String rowText = String.format("row %d col %d", i, j);
row.add(rowText );
}
matrix.add(row);
}
DefaultTableModel model = new DefaultTableModel(matrix,
COLUMN_NAME_VECTOR);
table.setModel(model);
}
private static void createAndShowGui() {
TableFoo mainPanel = new TableFoo();
JFrame frame = new JFrame("TableFoo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}

row selection not moving with row moves in JTable

I have following code:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.plaf.nimbus.NimbusLookAndFeel;
import javax.swing.table.DefaultTableModel;
public class NewClass1 extends JFrame {
private JTable table;
private JScrollPane scrollPane;
private DefaultTableModel defaultTableModel;
public NewClass1() {
setLocationByPlatform(true);
setLayout(new BorderLayout());
setPreferredSize(new Dimension(600, 400));
setTitle("Table Issues");
setDefaultCloseOperation(EXIT_ON_CLOSE);
createTableModel();
table = new JTable(defaultTableModel);
scrollPane = new JScrollPane(table);
getContentPane().add(scrollPane, BorderLayout.CENTER);
pack();
}
private void createTableModel() {
Vector cols = new Vector();
cols.add("A");
Vector rows = new Vector();
for (int i = 0; i < 50; i++) {
Vector row = new Vector();
row.add((i + 1) + "");
rows.add(row);
}
defaultTableModel = new DefaultTableModel(rows, cols) {
Class[] types = new Class[]{
String.class
};
#Override
public Class getColumnClass(int columnIndex) {
return types[columnIndex];
}
#Override
public boolean isCellEditable(int row, int column) {
return false;
}
};
}
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(new NimbusLookAndFeel());
} catch (Exception e) {
}
final NewClass1 nc = new NewClass1();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
nc.setVisible(true);
}
});
while (true) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
int row = (int) (Math.random() * 50);
int move = (int) (Math.random() * 50);
nc.defaultTableModel.moveRow(row, row, move);
}
});
try{
Thread.sleep(1000);
}catch(Exception e){
}
}
}
}
Please run the above code and select row.
My problem is with row movement, row selection is not moving. It is staying at fixed position. Suppose I selected row with column value 25, selected row must be of column value 25 after row movements.
Please help me on this.
My real problem is, user will select row and clicks menu to perform action, meanwhile other threads may have moved rows, and performed action will be on other row than actual one.
The easiest way is to remember the selected row somewhere outside of the ListSelectionModel and adjust the selection whenever the TableModel changes. For example you could do this:
public class NewClass1 extends JFrame {
private JTable table;
private DefaultTableModel defaultTableModel;
private JScrollPane scrollPane;
private class SelectionHelper implements ListSelectionListener, TableModelListener {
private Object selectedRow;
#Override
public void valueChanged(ListSelectionEvent event) {
if (!event.getValueIsAdjusting()) return;
int selectedIndex = table.getSelectedRow();
if (selectedIndex >= 0) {
selectedRow = defaultTableModel.getDataVector().get(selectedIndex);
} else {
selectedRow = null;
}
}
#Override
public void tableChanged(TableModelEvent event) {
if (selectedRow == null) return;
int selectedIndex = defaultTableModel.getDataVector().indexOf(selectedRow);
table.getSelectionModel().setSelectionInterval(selectedIndex, selectedIndex);
}
}
public NewClass1() {
// ...
createTableModel();
table = new JTable(defaultTableModel);
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
SelectionHelper helper = new SelectionHelper();
table.getModel().addTableModelListener(helper);
table.getSelectionModel().addListSelectionListener(helper);
// ...
}
// ...
}
Note however, that you should adjust this code for production use, for example in regards to thread safety or portability (using the table and defaultTableModel attributes in the inner class is bad style).

How to show a message over leading selection cell in JTable?

I have a JTable with a custom ListSelectionModel, which contains a custom selection mode. This selection mode ensures that a selection is only made in one row, but with multiple cells. When a user clicks selects some cells in the table, the selected cells are all in the same row as the first selected cell.
Now I want to create a small message above the upper-right corner of the leading selection cell, which displays some data, i.e. the count of the selected cells. The message should be moved when the leading selection is changed.
But how do I do that? It is not a Tooltip as it is intended to be shown when user clicks into the table and selects cells and not by hovering over it.
Any suggestions?
best regards,
htz
Alternatively (not very pretty but works quite well), you can take advantage of the fact that JTable is a JComponent like all others and therefore you can add child components to it. All you have to do, is make sure to size and locate properly your component (this is only because JTable uses a null-layout).
Here is a small demo with a JLabel that displays the number of selected items. The label is automatically positioned on the first visible row, unless it is the current lead selection, in which case, the label is moved to the second visible row:
import java.awt.BorderLayout;
import java.awt.Point;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class TestTable {
protected void initUI() {
Vector<Vector<Object>> data = new Vector<Vector<Object>>();
Vector<String> colNames = new Vector<String>();
for (int i = 0; i < 5; i++) {
colNames.add("Col-" + (i + 1));
}
for (int i = 0; i < 200; i++) {
Vector<Object> row = new Vector<Object>();
for (int j = 0; j < 5; j++) {
row.add("Cell " + (i + 1) + "-" + (j + 1));
}
data.add(row);
}
table = new JTable(data, colNames);
someText = new JLabel();
someText.setOpaque(true);
table.add(someText);
table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent e) {
int count = table.getSelectedRowCount();
someText.setText("You currently have selected " + count + " item" + (count > 1 ? "s" : ""));
layoutLabel();
}
});
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
scrollpane = new JScrollPane(table);
scrollpane.getViewport().addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent e) {
layoutLabel();
}
});
frame.add(scrollpane, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
private JLabel someText;
private JTable table;
private JScrollPane scrollpane;
private void layoutLabel() {
someText.setSize(someText.getPreferredSize());
Point location = scrollpane.getViewport().getViewRect().getLocation();
int leadSelectionIndex = table.getSelectionModel().getLeadSelectionIndex();
if (leadSelectionIndex > -1) {
if (table.rowAtPoint(location) == leadSelectionIndex) {
location.y += table.getRowHeight(leadSelectionIndex);
}
}
someText.setLocation(location);
}
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException,
UnsupportedLookAndFeelException {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new TestTable().initUI();
}
});
}
}
you can to set Locations for ToolTip with the similair effect like as in MsExcell,
it is not a Tooltip as it is intended to be shown when user clicks into the table and selects cells and not by hovering over it.
you can to use JPopup / JWindow instead of ToolTip, for non_editable contens
JPopup / JWindow by default can't contains editable JComponent (JTextComponents)
for user input you can to use undecorated JDialod only
Yet another option is to implement a per-component glassPane (one of the many roles of JLayer for 1.7, JXLayer for 1.6) like shown below. Note that I didn't try to prettify the location (as #Guillaume did). Also, you'll have to modify the Rob's DragLayout a bit to guarantee that the box is shown inside the table area.
public static class ToolTipUI extends LayerUI<JTable> {
private JLayer<JTable> layer;
private JToolTip toolTip;
#Override
public void installUI(JComponent c) {
super.installUI(c);
this.layer = (JLayer) c;
installGlassPane();
installListeners();
}
private void installListeners() {
ListSelectionListener l = new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent e) {
if (e.getValueIsAdjusting()) return;
updateToolTip();
}
};
getTable().getColumnModel().getSelectionModel().addListSelectionListener(l);
getTable().getSelectionModel().addListSelectionListener(l);
}
private void updateToolTip() {
int[] selectedColumns = getTable().getColumnModel().getSelectedColumns();
int selectedRow = getTable().getSelectedRow();
if (selectedRow < 0 || selectedColumns.length == 0) {
setToolTipText("");
} else {
String text = "selected cells: ";
for (int i = 0; i < selectedColumns.length; i++) {
text += " " + selectedColumns[i];
}
setToolTipText(text);
}
}
private void setToolTipText(String string) {
toolTip.setTipText(string);
Rectangle cellBounds = getTable().getCellRect(getTable().getSelectedRow(), 0, false);
toolTip.setLocation(cellBounds.getLocation());
doLayout(layer);
}
#Override
public void doLayout(JLayer<? extends JTable> l) {
super.doLayout(l);
l.getGlassPane().doLayout();
}
private JTable getTable() {
return layer.getView();
}
private void installGlassPane() {
toolTip = ((JComponent) layer.getView()).createToolTip();
layer.getGlassPane().setBorder(BorderFactory.createLineBorder(Color.RED));
// DragLayout by Rob Camick http://tips4java.wordpress.com/2011/10/23/drag-layout/
layer.getGlassPane().setLayout(new DragLayout());
layer.getGlassPane().add(toolTip);
layer.getGlassPane().setVisible(true);
}
}
// usage:
JTable table = new JTable(new AncientSwingTeam());
JLayer layer = new JLayer<JTable>(table, new ToolTipUI());

Java JTable with JComboBox

I'm trying to place a JComboBox inside a certain column of a JTable.
I have this code, and it is working:
model = new DefaultTableModel();
JComboBox<String> optionComboCell = new JComboBox<String>();
optionComboCell.addItem("Option 1");
optionComboCell.addItem("Option 2");
optionComboCell.setSelectedIndex(1);
table = new JTable(model);
// Adding here all the columns, removed for clarity
model.addColumn("Options");
TableColumn optionsColumn = table.getColumn("Options");
optionsColumn.setCellEditor(new DefaultCellEditor(optionComboCell));
My problem with this, is that it doesn't show as JComboBox until a cell in that column is selected.
When the JFrame is loaded, the whole table looks the same, as if all the cells where only text.
When clicked, it shows the combo box's arrow and options, but again when deselected, it looks like a regular cell.
Any way to get around that?
Yes, use a JComboBox to render your cells:
import java.awt.Component;
import java.util.Enumeration;
import java.util.Vector;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
public class Test4 {
private static class ComboBoxCellRenderer extends JComboBox implements TableCellRenderer {
public ComboBoxCellRenderer(int column) {
for (int i = 0; i < 10; i++) {
addItem("Cell (" + i + "," + column + ")");
}
}
#Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
setSelectedItem(value);
return this;
}
}
protected void initUI() {
JFrame frame = new JFrame("test");
frame.add(getTable());
frame.pack();
frame.setVisible(true);
}
private Component getTable() {
Vector<Vector<String>> data = new Vector<Vector<String>>();
for (int i = 0; i < 10; i++) {
Vector<String> row = new Vector<String>();
for (int j = 0; j < 3; j++) {
row.add("Cell (" + i + "," + j + ")");
}
data.add(row);
}
Vector<String> columns = new Vector<String>();
columns.add("Column 1");
columns.add("Column 2");
columns.add("Column 3");
DefaultTableModel model = new DefaultTableModel(data, columns);
JTable table = new JTable(model);
table.setRowHeight(20);
int i = 0;
Enumeration<TableColumn> c = table.getColumnModel().getColumns();
while (c.hasMoreElements()) {
TableColumn column = c.nextElement();
column.setCellRenderer(new ComboBoxCellRenderer(i));
i++;
}
JScrollPane scroll = new JScrollPane(table);
scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
return scroll;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Test4().initUI();
}
});
}
}
You will need to define your own renderer for displaying components on your table, since CellEditors are only needed for editing the value within a tablecell (which is why it only reacts, when you click on a cell).
Maybe have a look at Java Tutorials to learn more about the concept of renderers and editors for JTables.
Try to set the cell renderer as well.

How to strikethrough text of a selected row(having checkbox in first column) of JTable?

I have a Jtable with a checkbox in first column. I want to strikethrough text of a row when the checkbox is selected. (eg same as we do in microsoft outlook when our task is complete.) I have tried using AttributeString, but not able to do it.
Can anyone please guide me to solve it?
String strStrike;
AttributedString as;
public void setTextStrikeThrough() {
for(int r=0;r< taskcells.length;r++) {
if (ttable.getValueAt(r,0).equals(Boolean.TRUE)) {
for(int c=2;c<7;c++) {
strStrike+=taskcells[r][c-1];
}//end inner for as=new
AttributedString(strStrike);
as.addAttribute(TextAttribute.STRIKETHROUGH,
TextAttribute.STRIKETHROUGH_ON);
as.getIterator();
}//end if
}//end for
}
I am not getting exactly where to call this method. I want to strikethrough text of a row when checkbox of that row has been checked.
I don't know that an ActionListener will work well for a JCheckBox in a JTable since the check box isn't a real button but rather a rendering of a checkbox. Perhaps playing with the table model will help. For instance you can use HTML to display a strike through of Strings displayed in table cells. For instance below I create a custom TableModel that extends DefaultTableModel and holds rows with a Boolean object followed by objects of a TextWrapper class that I've created that changes its toString result depending on a boolean.
e.g.,
import java.util.Vector;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
public class StrikeThroughRow {
public static final Object[][] DATA = {{Boolean.TRUE, "Monday", "fe"},
{Boolean.FALSE, "Tuesday", "fi"}, {Boolean.TRUE, "Wednesday", "fo"},
{Boolean.FALSE, "Thursday", "fum"}, {Boolean.TRUE, "Friday", "foo"}};
public StrikeThroughRow() {
}
private static void createAndShowUI() {
JTable table = new JTable(new StrikeThroughModel(DATA));
JScrollPane scrollpane = new JScrollPane(table);
JFrame frame = new JFrame("StrikeThroughRow");
frame.getContentPane().add(scrollpane);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}
class StrikeThroughModel extends DefaultTableModel {
public StrikeThroughModel(Object[][] data) {
super(new String[]{"Check", "Work Day", "Giant Speak"}, 0);
for (int i = 0; i < data.length; i++) {
Vector<Object> rowVect = new Vector<Object>();
rowVect.add(data[i][0]);
if (data[i].length > 1) {
for (int j = 1; j < data[i].length; j++) {
rowVect.add(new TextWrapper(data[i][j].toString(), (Boolean)data[i][0]));
}
}
addRow(rowVect);
}
}
#Override
public Class<?> getColumnClass(int columnIndex) {
if (columnIndex == 0) {
return Boolean.class;
}
return super.getColumnClass(columnIndex);
}
#Override
public void setValueAt(Object value, int row, int column) {
if (column == 0) {
for (int i = 1; i < getColumnCount(); i++) {
TextWrapper textWrapper = (TextWrapper) getValueAt(row, i);
textWrapper.setStrikeThrough((Boolean) value);
fireTableCellUpdated(row, i);
}
}
super.setValueAt(value, row, column);
}
}
class TextWrapper {
private String text;
private boolean strikeThrough = false;
public TextWrapper(String text) {
this.text = text;
}
public TextWrapper(String text, boolean strikeThrough) {
this(text);
this.strikeThrough = strikeThrough;
}
#Override
public String toString() {
if (strikeThrough) {
return "<html><strike>" + text + "</html></strike>";
}
return text;
}
public void setStrikeThrough(boolean strikeThrough) {
this.strikeThrough = strikeThrough;
}
}
I'm betting that there are better solutions including creating a custom renderer for your cells, but the code above offers a quick and dirty fix.
Here is how you can create a "strike through font":
Map attributes = component.getFont().getAttributes();
attributes.put(TextAttribute.STRIKETHROUGH, TextAttribute.STRIKETHROUGH_ON);
component.setFont( new Font(attributes) );
One way to apply the font is to use the Table Row Rendering approach. Take a look at the background color example. Instead of setting the background of the renderer you can set the Font.
Otherwise you would need to create a custom renderer for the columns in your table to use the appropriate Font.
Add a listener to the checkbox which will add/remove the from the label. Here is an example of box and label maybe helpful:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.AbstractButton;
import javax.swing.BorderFactory;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class check {
public static void main(String args[]) {
JFrame frame = new JFrame("for bsm");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JCheckBox box = new JCheckBox("check me");
final JLabel label = new JLabel("<html>text</html>");
label.setFont(new Font("helvetica", Font.PLAIN, 12));
label.setForeground(new Color(50, 50, 25));
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
AbstractButton abstractButton = (AbstractButton) actionEvent.getSource();
if(abstractButton.getModel().isSelected())
label.setText(label.getText().replace("<html>", "<html><strike>").replace("</html>", "</strike></html>"));
else
label.setText(label.getText().replace("<html><strike>", "<html>").replace("</strike></html>", "</html>"));
}
};
box.addActionListener(actionListener);
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout(10, 10));
panel.add(label, BorderLayout.NORTH);
panel.add(box, BorderLayout.SOUTH);
panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
frame.add(panel);
frame.setSize(300, 200);
frame.setVisible(true);
}
}

Categories