Setting Multi-Line label on the Button

Objective:to set the multi line label on the button in Java Swing Applications.

This program uses html class from javax.swing.text.html*; package and then breaks the text label of the button into two lines. If you run the program it will look like following image:

Multiline Labe of the Button

Setting Multi-Line label on the Button

This section shows you how to set the multi line label on the button in Java Swing Applications.

This program uses html class from javax.swing.text.html*; package and then breaks the text label of the button into two lines. If you run the program it will look like following image:

Multiline Labe of the Button

HTML:

This is the class from the javax.swing.text.html.*; package of Java. This class provides the facility to use the html tags in java application for texts. There are tag and
tag have been used in this program. Tags of html are used with the string which is the label of the button.

Here is the code of the program:


import javax.swing.*;
import javax.swing.text.html.*;
import java.awt.*;

public class MultilineLabelButton{
public static void main(String[] args){
JFrame frame = new JFrame("Multiline Label for Button");
String lbl = "" + "This label" + "
" + "is in two lines" + "";
Panel panel = new Panel();
JButton button = new JButton(lbl);
panel.add(button);
// frame.add(button);
frame.add(panel, BorderLayout.NORTH);
frame.setSize(300, 200);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

Advertisements

Previous Post

JButtonTableExample.java file:


import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;

/**
* @version 1.0 11/09/98
*/
public class JButtonTableExample extends JFrame {

public JButtonTableExample(){
super( “JButtonTable Example” );

DefaultTableModel dm = new DefaultTableModel();
dm.setDataVector(new Object[][]{{“button 1″,”foo”},
{“button 2″,”bar”}},
new Object[]{“Button”,”String”});

JTable table = new JTable(dm);
table.getColumn(“Button”).setCellRenderer(new ButtonRenderer());
table.getColumn(“Button”).setCellEditor(new ButtonEditor(new JCheckBox()));
JScrollPane scroll = new JScrollPane(table);
getContentPane().add( scroll );
setSize( 400, 100 );
setVisible(true);
}

public static void main(String[] args) {
JButtonTableExample frame = new JButtonTableExample();
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}

ButtonEditor.java:


import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;

/**
* @version 1.0 11/09/98
*/
public class ButtonEditor extends DefaultCellEditor {
protected JButton button;
private String label;
private boolean isPushed;

public ButtonEditor(JCheckBox checkBox) {
super(checkBox);
button = new JButton();
button.setOpaque(true);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
fireEditingStopped();
}
});
}

public Component getTableCellEditorComponent(JTable table, Object value,
boolean isSelected, int row, int column) {
if (isSelected) {
button.setForeground(table.getSelectionForeground());
button.setBackground(table.getSelectionBackground());
} else{
button.setForeground(table.getForeground());
button.setBackground(table.getBackground());
}
label = (value ==null) ? “” : value.toString();
button.setText( label );
isPushed = true;
return button;
}

public Object getCellEditorValue() {
if (isPushed) {
//
//
JOptionPane.showMessageDialog(button ,label + “: Ouch!”);
// System.out.println(label + “: Ouch!”);
}
isPushed = false;
return new String( label ) ;
}

public boolean stopCellEditing() {
isPushed = false;
return super.stopCellEditing();
}

protected void fireEditingStopped() {
super.fireEditingStopped();
}
}

 

ButtonRenderer.java file


import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;

/**
* @version 1.0 11/09/98
*/
public class ButtonRenderer extends JButton implements TableCellRenderer {

public ButtonRenderer() {
setOpaque(true);
}

public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
if (isSelected) {
setForeground(table.getSelectionForeground());
setBackground(table.getSelectionBackground());
} else{
setForeground(table.getForeground());
setBackground(UIManager.getColor(“Button.background”));
}
setText( (value ==null) ? “” : value.toString() );
return this;
}
}

 

Demo Image Loader


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.*;

class ImagePanel extends JPanel{

private BufferedImage image;

public ImagePanel() {
try {
image = ImageIO.read(new File("photo.jpeg"));
} catch (IOException ex) {
// handle exception...
}

}

@Override
public void paintComponent(Graphics g) {
g.drawImage(image, 0, 0, null); // see javadoc for more info on the parameters

}

}

public class DemoImageLoader
{
JFrame mf;
ImagePanel ip;
JPanel jp;
DemoImageLoader()
{
mf=new JFrame("Image Loader");
ip=new ImagePanel();
jp=new JPanel();
jp.add(ip);
mf.add(ip);

mf.setSize(200,300);
mf.setVisible(true);
}
public static void main(String []a)
{
new DemoImageLoader();
}
}

Image Frame Example


import javax.swing.*;
import java.awt.*;
import javax.imageio.*;
import java.io.*;
import java.awt.event.*;
//panel used to draw image on

class ImagePanel extends JPanel
{
//path of image
private String path;
//image object
private Image img;
public ImagePanel(String path) throws IOException
{
//save path
this.path = path;
//load image
img = ImageIO.read(new File(path));
}
//override paint method of panel
public void paint(Graphics g)
{
//draw the image
if( img != null)
g.drawImage(img,0,0, this);
}
}

//example of using image panel
public class ImageFrame implements ActionListener
{
JFrame f = new JFrame();
JButton btn=new JButton("Open");
ImagePanel panel=null;

public ImageFrame()
{

f.setLayout(null);
btn.addActionListener(this);
//f.getContentPane().add(panel);
btn.setBounds(10,10,20,20);

f.add(btn);

f.setSize(200,200);
//f.setBounds(0,0,600,400);
f.setVisible(true);
}
public void actionPerformed(ActionEvent ae)
{
System.out.println ( "inside");
JFileChooser chooser = new JFileChooser();
System.out.println ( "inside2");
chooser.showOpenDialog(f);
try
{
panel = new ImagePanel( chooser.getSelectedFile().getPath() );
}
catch(Exception e)
{
System.out.println ( "Please verify that you selected a valid image file");
}
panel.setBounds(10,25,100,100);
f.add(panel);

}

public static void main(String[] args) throws IOException
{

new ImageFrame();

}
}

JRadioButton


import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class SelectRadioButton{
JLabel label;
final JButton btn;
final ButtonGroup bg;
final JFrame frame;
public static void main(String[] args){
SelectRadioButton sr = new SelectRadioButton(1);
}
public SelectRadioButton(){}
public SelectRadioButton(int a){
frame = new JFrame("Radio button selection");
btn=new JButton("Show");

JRadioButton first = new JRadioButton("First");
JRadioButton second = new JRadioButton("Second");
JRadioButton third = new JRadioButton("Third");
JRadioButton fourth = new JRadioButton("Fofurth");
JRadioButton fifth = new JRadioButton("Fifth");
JPanel panel = new JPanel();

panel.add(btn);
panel.add(first);
panel.add(second);
panel.add(third);
panel.add(fourth);
panel.add(fifth);

bg = new ButtonGroup();
bg.add(first);
bg.add(second);
bg.add(third);
bg.add(fourth);
bg.add(fifth);

btn.addActionListener(new MyAction());
first.addActionListener(new MyAction());
second.addActionListener(new MyAction());
third.addActionListener(new MyAction());
fourth.addActionListener(new MyAction());
fifth.addActionListener(new MyAction());
label = new JLabel("https://playjava.wordpress.com");
frame.add(panel, BorderLayout.NORTH);
frame.add(label, BorderLayout.CENTER);
frame.setSize(400, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public class MyAction extends SelectRadioButton implements ActionListener{
public void actionPerformed(ActionEvent e)
{
// if(e.getSource()==btn)
// {
// String msg = bg.getSelection().toString();
// JOptionPane.showMessageDialog(frame,msg,"DEMO",JOptionPane.INFORMATION_MESSAGE);
// }
// else{
label.setText(e.getActionCommand());
JOptionPane.showMessageDialog(null,"This is the " + e.getActionCommand() +" radio button.");}
// }
}
}

JTable:popupmenu for a cell on click event

Requirement:To Display Popupmenu for a cell within JTable on click event
Basically we need to
(1) get the colum and row index of the cell on which you clicked:
jTable.columnAtPoint(p);
jTable.rowAtPoint(p);
(2) convert the column index to the table’s model index:
jTable.convertColumnIndexToModel(col);
(3) create popup menu and add menu items specific for the row and/or
column
(4) show the popup menu

Here’s a complete example:


import java.awt.BorderLayout;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;

import javax.swing.CellEditor;
import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;

public class TableMenu extends JFrame {
public static void main(String[] args) {
TableMenu app = new TableMenu();
app.getTableModel().addItem("Apple", 1.39, 3);
app.getTableModel().addItem("Pear", 2.19, 2);
app.getTableModel().addItem("Banana", 1.52, 4);
app.setVisible(true);
}

private static final String PROP_CHANGE_QUANTITY = "CHANGE_QUANTITY";

private static String getClipboardContents(Object requestor) {
Transferable t = Toolkit.getDefaultToolkit()
.getSystemClipboard().getContents(requestor);
if (t != null) {
DataFlavor df = DataFlavor.stringFlavor;
if (df != null) {
try {
Reader r = df.getReaderForText(t);
char[] charBuf = new char[512];
StringBuffer buf = new StringBuffer();
int n;
while ((n = r.read(charBuf, 0, charBuf.length)) > 0) {
buf.append(charBuf, 0, n);
}
r.close();
return (buf.toString());
} catch (IOException ex) {
ex.printStackTrace();
} catch (UnsupportedFlavorException ex) {
ex.printStackTrace();
}
}
}
return null;
}

private static boolean isClipboardContainingText(Object requestor) {
Transferable t = Toolkit.getDefaultToolkit()
.getSystemClipboard().getContents(requestor);
return t != null
&& (t.isDataFlavorSupported(DataFlavor.stringFlavor) || t
.isDataFlavorSupported(DataFlavor.plainTextFlavor) );
}

private static void setClipboardContents(String s) {
StringSelection selection = new StringSelection(s);
Toolkit.getDefaultToolkit().getSystemClipboard().s etContents(
selection, selection);
}

private JPanel jContentPane;

private JScrollPane jScrollPane;

private JTable jTable;

private ExampleTableModel tableModel;

public TableMenu() {
super();
initialize();
}

private JTable getJTable() {
if (jTable == null) {
jTable = new JTable();
jTable.setModel(getTableModel());
jTable.addMouseListener(new MouseAdapter() {

private void maybeShowPopup(MouseEvent e) {
if (e.isPopupTrigger() && jTable.isEnabled()) {
Point p = new Point(e.getX(), e.getY());
int col = jTable.columnAtPoint(p);
int row = jTable.rowAtPoint(p);

// translate table index to model index
int mcol = jTable.getColumn(
jTable.getColumnName(col)).getModelIndex();

if (row >= 0 && row 0) {
contextMenu.show(jTable, p.x, p.y);
}
}
}
}

public void mousePressed(MouseEvent e) {
maybeShowPopup(e);
}

public void mouseReleased(MouseEvent e) {
maybeShowPopup(e);
}
});
}
return jTable;
}

private void cancelCellEditing() {
CellEditor ce = getJTable().getCellEditor();
if (ce != null) {
ce.cancelCellEditing();
}
}

private JPopupMenu createContextMenu(final int rowIndex,
final int columnIndex) {
JPopupMenu contextMenu = new JPopupMenu();

JMenuItem copyMenu = new JMenuItem();
copyMenu.setText("Copy");
copyMenu.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Object value = getTableModel().getValueAt(rowIndex,
columnIndex);
setClipboardContents(value == null ? "" : value
.toString());
}
});
contextMenu.add(copyMenu);

JMenuItem pasteMenu = new JMenuItem();
pasteMenu.setText("Paste");
if (isClipboardContainingText(this)
&& getTableModel().isCellEditable(rowIndex, columnIndex)) {
pasteMenu.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String value = getClipboardContents(TableMenu.this);
getTableModel().setValueAt(value, rowIndex,
columnIndex);
}
});
} else {
pasteMenu.setEnabled(false);
}
contextMenu.add(pasteMenu);

switch (columnIndex) {
case ExampleTableModel.COLUMN_NAME:
break;
case ExampleTableModel.COLUMN_PRICE:
break;
case ExampleTableModel.COLUMN_QUANTITY:
contextMenu.addSeparator();
ActionListener changer = new ActionListener() {

public void actionPerformed(ActionEvent e) {
JMenuItem sourceItem = (JMenuItem) e.getSource();
Object value = sourceItem
.getClientProperty(PROP_CHANGE_QUANTITY);
if (value instanceof Integer) {
Integer changeValue = (Integer) value;
Integer currentValue = (Integer) getTableModel()
.getValueAt(rowIndex, columnIndex);
getTableModel().setValueAt(
new Integer(currentValue.intValue()
+ changeValue.intValue()), rowIndex,
columnIndex);
}
}
};
JMenuItem changeItem = new JMenuItem();
changeItem.setText("+1");
changeItem.putClientProperty(PROP_CHANGE_QUANTITY,
new Integer(1));
changeItem.addActionListener(changer);
contextMenu.add(changeItem);

changeItem = new JMenuItem();
changeItem.setText("-1");
changeItem.putClientProperty(PROP_CHANGE_QUANTITY,
new Integer(-1));
changeItem.addActionListener(changer);
contextMenu.add(changeItem);

changeItem = new JMenuItem();
changeItem.setText("+10");
changeItem.putClientProperty(PROP_CHANGE_QUANTITY,
new Integer(10));
changeItem.addActionListener(changer);
contextMenu.add(changeItem);

changeItem = new JMenuItem();
changeItem.setText("-10");
changeItem.putClientProperty(PROP_CHANGE_QUANTITY,
new Integer(-10));
changeItem.addActionListener(changer);
contextMenu.add(changeItem);

changeItem = null;
break;
case ExampleTableModel.COLUMN_AMOUNT:
break;
default:
break;
}
return contextMenu;
}

private JPanel getJContentPane() {
if (jContentPane == null) {
jContentPane = new JPanel();
jContentPane.setLayout(new BorderLayout());
jContentPane.add(getJScrollPane(),
java.awt.BorderLayout.CENTER);
}
return jContentPane;
}

private JScrollPane getJScrollPane() {
if (jScrollPane == null) {
jScrollPane = new JScrollPane();
jScrollPane.setViewportView(getJTable());
}
return jScrollPane;
}

private ExampleTableModel getTableModel() {
if (tableModel == null) {
tableModel = new ExampleTableModel();
}
return tableModel;
}

private void initialize() {
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE );
this.setSize(300, 200);
this.setContentPane(getJContentPane());
this.setTitle("Application");
}

}

class ExampleTableModel extends AbstractTableModel {
private static class Item {
private String name;

private double price;

private int quantity;

public Item(String name, double price, int quantity) {
this.name = name;
this.price = price;
this.quantity = quantity;
}

public double getAmount() {
return quantity * price;
}
}

public static final int COLUMN_AMOUNT = 3;

public static final int COLUMN_NAME = 0;

public static final int COLUMN_PRICE = 1;

public static final int COLUMN_QUANTITY = 2;

private List items = new ArrayList();

public void addItem(String name, double price, int quantity) {
items.add(new Item(name, price, quantity));
}

public Class getColumnClass(int columnIndex) {
switch (columnIndex) {
case COLUMN_NAME:
return String.class;
case COLUMN_PRICE:
case COLUMN_AMOUNT:
return Double.class;
case COLUMN_QUANTITY:
return Integer.class;
default:
return Object.class;
}
}

public int getColumnCount() {
return 4;
}

public String getColumnName(int columnIndex) {
switch (columnIndex) {
case COLUMN_NAME:
return "Name";
case COLUMN_PRICE:
return "Price";
case COLUMN_QUANTITY:
return "Quantity";
case COLUMN_AMOUNT:
return "Amount";

default:
return "# COLUMN " + columnIndex + " #";
}
}

public int getRowCount() {
return items.size();
}

public Object getValueAt(int rowIndex, int columnIndex) {
Item item = (Item) items.get(rowIndex);
switch (columnIndex) {
case COLUMN_NAME:
return item.name;
case COLUMN_PRICE:
return new Double(item.price);
case COLUMN_QUANTITY:
return new Integer(item.quantity);
case COLUMN_AMOUNT:
return new Double(item.getAmount());
default:
return null;
}
}

public boolean isCellEditable(int rowIndex, int columnIndex) {
switch (columnIndex) {
case COLUMN_NAME:
case COLUMN_PRICE:
case COLUMN_QUANTITY:
return true;
case COLUMN_AMOUNT:
default:
return false;
}
}

public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
Item item = (Item) items.get(rowIndex);
switch (columnIndex) {
case COLUMN_NAME:
item.name = aValue.toString();
fireTableCellUpdated(rowIndex, columnIndex);
break;
case COLUMN_PRICE:
try {
item.price = Double.parseDouble(aValue.toString());
} catch (NumberFormatException ex) {
ex.printStackTrace();
}
fireTableCellUpdated(rowIndex, columnIndex);
fireTableCellUpdated(rowIndex, COLUMN_AMOUNT);
break;
case COLUMN_QUANTITY:
try {
item.quantity = Integer.parseInt(aValue.toString());
} catch (NumberFormatException ex) {
ex.printStackTrace();
}
fireTableCellUpdated(rowIndex, columnIndex);
fireTableCellUpdated(rowIndex, COLUMN_AMOUNT);
break;
case COLUMN_AMOUNT:
default:
return;
}
}
}

JMenu Example

This example shows how to construct menus in Java. The main Menu “File” contains three subitems. Each item can be accessed by a mouse click or by its keyboard mnemonic. Once a subitem is clicked a message is displayed explaining wich subitem was clicked.


import javax.swing.*;
import java.awt.event.*;
public class Menu extends JFrame{
public Menu()
{
super("Menu example");

JMenu file = new JMenu("File");
file.setMnemonic('F');
JMenuItem newItem = new JMenuItem("New");
newItem.setMnemonic('N');
file.add(newItem);
JMenuItem openItem = new JMenuItem("Open");
openItem.setMnemonic('O');
file.add(openItem);
JMenuItem exitItem = new JMenuItem("Exit");
exitItem.setMnemonic('x');
file.add(exitItem);

//adding action listener to menu items
newItem.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e)
{
System.out.println("New is pressed");
}
}
);
openItem.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e)
{
System.out.println("Open is pressed");
}
}
);
exitItem.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e)
{
System.out.println("Exit is pressed");
}
}
);
JMenuBar bar = new JMenuBar();
setJMenuBar(bar);
bar.add(file);

getContentPane();
setSize(200, 200);
setVisible(true);
}

public static void main(String[] args)
{
Menu app = new Menu();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}