Saturday, 12 May 2012
Writing a Toolbar with Java
Posted on 10:54 by Unknown
This Java example shows how to program a Toolbar by the use of a string array and an index for the buttons. It shows how to respond to click events.
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFrame;
public class mButton {
String[] Kommandos = {"xterm" ,"gedit" ,"xclock"}; //Define some buttons
JButton Jb[] = new JButton[Kommandos.length];
public mButton() {
JFrame myframe = new JFrame("Buttons");
myframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myframe.setLayout(new FlowLayout());
Font font = new Font("Dialog", Font.PLAIN, 30);
for (int index=0; index < Kommandos.length; index++)
{
//System.out.println("index: " + index );
Jb[index] = new JButton(Kommandos[index]);
Jb[index].setFont(font);
myframe.add(Jb[index]);
Jb[index].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ev) {
JButton theButton = (JButton) ev.getSource();
String text = theButton.getText();
//String num = theButton.getActionCommand();
//System.out.println(num);
//System.out.println(text);
try {
Runtime.getRuntime().exec(text);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
myframe.pack();
myframe.setLocationRelativeTo(myframe); //center on screen
myframe.setVisible(true);
myframe.setResizable(false);
}
}
public static void main(String[] args) {
mButton myKommands = new mButton();
}
}
Subscribe to:
Post Comments (Atom)

0 comments:
Post a Comment