Well since both JScrollPane and JLabel are direct subclasses of JComponent, they both have the paintComponent method.
JScrollPane is to paintComponent as JLabel is to paintComponent.
Exterminateee (Dalek)
You can use a JLabel to put text on a JPanel. You put a string in the JLabel and put the JLabel on a JPanel
import javax.swing.*; import java.awt.*; import java.awt.event.*; class fcfs extends JFrame implements ActionListener { JButton jb[] = new JButton[3]; JTextField jt1[],jt2[]; JLabel jl[],jl1,jl2,jl3; JPanel jp,jp1; Container con; int k,p; String str[] = {"SUBMIT","RESET","EXIT"}; String str1[] = {"Process"," AT","ST","WT","FT","TAT","NTAT"}; public fcfs() { super("fcfs scheduling algoritham"); con = getContentPane(); k= Integer.parseInt(JOptionPane.showInputDialog("Enter number of process")); jl1 = new JLabel("Process"); jl2 = new JLabel("Arival Time"); jl3 = new JLabel("Service Time"); jl = new JLabel[k]; jt1 = new JTextField[k]; jt2 = new JTextField[k]; for(int i=0;i<k;i++) { jl[i] = new JLabel("process"+(i+1)); jt1[i] = new JTextField(10); jt2[i] = new JTextField(10); } for(int i=0;i<3;i++) { jb[i] = new JButton(str[i]); } con.setLayout(new GridLayout(k+2,3)); con.add(jl1); con.add(jl2); con.add(jl3); int l=0; for(int i=0;i<k;i++) { con.add(jl[l]); con.add(jt1[l]); con.add(jt2[l]); l++; } l=0; for(int i=0;i<3;i++) { con.add(jb[l]); jb[l].addActionListener(this); l++; } }//end of constructor public void actionPerformed(ActionEvent ae) { int FT[] = new int[k]; int WT[] = new int[k]; int TAT[] = new int[k]; float NTAT[] = new float[k]; float sum=0; float avg; JPanel main = new JPanel(); main.setLayout(new BorderLayout()); jp = new JPanel(); jp1 = new JPanel(); jp.setLayout(new GridLayout(k+1,7)); jp1.setLayout(new FlowLayout()); if(ae.getSource() jb[1]) { setVisible(false); fcfs window = new fcfs(); window.setSize(400,300); window.setVisible(true); window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } }//END ACTION PERFORMED public static void main(String[] args) { fcfs window = new fcfs(); window.setSize(400,300); window.setVisible(true); window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }//end main }//end class
import javax.swing.*; import java.awt.*; import java.awt.event.*; class jwp extends JFrame implements ActionListener{ JButton button = new JButton ("Submit"); JTextField field = new JTextField(); JLabel label = new JLabel("Enter your name : ",Label.RIGHT); public jwp(){ super("JFrame with panel and button"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel panel = new JPanel(null); panel.add(label); panel.add(field); panel.add(button); setContentPane(panel); button.setBounds(100,70,100,50); label.setBounds(20,30,200,20); field.setBounds(120,30,100,20); button.addActionListener(this);} public void actionPerformed (ActionEvent e){ if (e.getSource() ==button){ JOptionPane.showMessageDialog(this,"Youre name was "+field.getText());} } } public class frame1 { public static void main (String[] args) { jwp start = new jwp(); start.setSize(300, 200); start.setVisible(true); } } that's alll.......i can't upgrade it anymore......
Swing is the api defined in javax.swing package and used to add graphical interface to the user by providing controls like JButton , JLabel , JTextField etc. if there is a User Interface then there has to be a way to handle the events generated by these controls so event is the general interaction of the user and the application which can be delegated using any delegation model..simple examples of the events are MouseEvent (click, double click etc.) swing is also known as JFC (java foundation classes) before using swing for designing user interface we were using awt which are heavy objects as compared to swing objects and swing has a better look and feel also.
java beans provide business logic methods by which we manually call methods such as setter methods and getter methods in a encapsulated way of object oriented programming. Or even we can say these are model components in MVC architecture.
import java.awt.*;import java.awt.event.*;import javax.swing.*;import java.net.*;import java.io.*;public class Browser{private JFrame frame;private JPanel panelTop;private JEditorPane editor;private JScrollPane scroll;private JTextField field;private JButton button;private JButton button1;private URL url;public Browser(String title){initComponents();//set the title of the frameframe.setTitle(title);//set the default cloe op of the jframeframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//set size of frameframe.setSize(1370,700);//add jpanel to north of jframeframe.add(BorderLayout.NORTH, panelTop);//add textfield and navigation button to jpanel.panelTop.add(field);panelTop.add(button);//panelTop.add(button1);// panelTop.add(button);//add scroll pane to jframe centerframe.add(BorderLayout.CENTER, scroll);//set the frame visibleframe.setVisible(true);}//end Browser() constructorprivate void initComponents(){//create the JFrameframe = new JFrame();//create the JPanel used to hold the text field and button.panelTop = new JPanel();//set the urltry{url = new URL("http://www.mr-jatt.com");}catch(MalformedURLException mue){JOptionPane.showMessageDialog(null,mue);}//create the JEditorPanetry{editor = new JEditorPane(url);//set the editor pane to false.editor.setEditable(false);}catch(IOException ioe){JOptionPane.showMessageDialog(null,ioe);}//create the scroll pane and add the JEditorPane to it.scroll = new JScrollPane(editor, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);//create the JTextFieldfield = new JTextField();//set the JTextField text to the url.//we're not doing this on the event dispatch thread, so we need to use//SwingUtilities.SwingUtilities.invokeLater(new Runnable(){public void run(){field.setText(url.toString());}});//create the button for chanign pages.button = new JButton("Go");//add action listener to the buttonbutton.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {try{editor.setPage(field.getText());}catch(IOException ioe) {JOptionPane.showMessageDialog(null, ioe);}}});//button=new JButton("back");}//end initComponents()public static void main(String[] args){SwingUtilities.invokeLater(new Runnable(){public void run(){new Browser("Simple web browser");}});}//end main method.}//end Browser class
JPanel, a part of Java Swing package, is a container that can store a group of components. The main task of JPanel is to organize components, various layouts can be set in JPanel which provide better organization of components, and however it does not have a title bar. For Example: Program to create a JPanel with a Border layout and add components to it . // java Program to create a JPanel with a Border layout and add components to it . import java.awt.event.; import java.awt.; import javax.swing.*; class solution extends JFrame { // JFrame static JFrame f; // JButton static JButton b, b1, b2, b3; // label to diaplay text static JLabel l; // main class public static void main(String[] args) { // create a new frame to stor text field and button f = new JFrame("panel"); // create a label to display text l = new JLabel("panel label"); // create a new buttons b = new JButton("button1"); b1 = new JButton("button2"); b2 = new JButton("button3"); b3 = new JButton("button4"); // create a panel to add buttons and a specific layout JPanel p = new JPanel(new BorderLayout()); // add buttons and textfield to panel p.add(b, BorderLayout.NORTH); p.add(b1, BorderLayout.SOUTH); p.add(b2, BorderLayout.EAST); p.add(b3, BorderLayout.WEST); p.add(l, BorderLayout.CENTER); // setbackground of panel p.setBackground(Color.red); // add panel to frame f.add(p); // set the size of frame f.setSize(300, 300); f.show(); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package simpletexteditor; /** * * @author Ibrahim Alwazir */ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.io.*; class MyPad extends JFrame implements ActionListener, KeyListener { boolean txtChanged = false; String fname = ""; JMenuBar mbar; JMenu mnuFile, mnuEdit; JMenuItem fileNew, fileOpen, fileSave, fileExit; JMenuItem editCut, editCopy, editPaste, editSelectAll, editDel; JToolBar tlbr; ImageIcon iconNew, iconOpen, iconSave; ImageIcon iconCut, iconCopy, iconPaste; JButton bttnNew, bttnOpen, bttnSave; JButton bttnCut, bttnCopy, bttnPaste; JCheckBoxMenuItem wordWrap; JTextArea txtPad; Container c; MyPad() { initComponents(); setTitle("Simple Text Editor"); setSize(400,300); setVisible(true); setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); addWindowListener(new WinHandler()); } void initComponents() { //get a handle (reference) to the //content pane of window c = getContentPane(); //set BorderLayout Manager to arrange components in content pane c.setLayout(new BorderLayout()); initMenu(); //create textarea txtPad = new JTextArea(); Font f = new Font("Arial", Font.PLAIN, 20); txtPad.setFont(f); txtPad.addKeyListener(this); txtPad.setLineWrap(false); /* Sets word wrap style to false. */ txtPad.setWrapStyleWord(false); //add txtPad in scrollpane JScrollPane jscroll = new JScrollPane(txtPad); //add scrollpane in window c.add(jscroll, BorderLayout.CENTER); } void initMenu() { //create menubar mbar = new JMenuBar(); //create menus mnuFile = new JMenu("File"); mnuEdit = new JMenu("Edit"); //create menuitems fileNew = new JMenuItem("New"); fileOpen= new JMenuItem("Open"); fileSave= new JMenuItem("Save"); fileExit = new JMenuItem("Exit"); wordWrap = new JCheckBoxMenuItem("word wrap"); editCut = new JMenuItem("Cut"); editCopy= new JMenuItem("Copy"); editPaste = new JMenuItem("Paste"); editSelectAll = new JMenuItem("Select All"); editDel= new JMenuItem("Delete"); //add menuitems in menus mnuFile.add(fileNew); mnuFile.add(fileOpen); mnuFile.add(fileSave); mnuFile.add(fileExit); mnuEdit.add(editCut); mnuEdit.add(editCopy); mnuEdit.add(editPaste); mnuEdit.addSeparator(); mnuEdit.add(editSelectAll); mnuEdit.add(editDel); mnuEdit.add(wordWrap); //attach menus to menubar mbar.add(mnuFile); mbar.add(mnuEdit); //attach menubar to window setJMenuBar(mbar); //attach actionlister to menuitems fileNew.addActionListener(this); fileOpen.addActionListener(this); fileSave.addActionListener(this); fileExit.addActionListener(this); editCut.addActionListener(this); editCopy.addActionListener(this); editPaste.addActionListener(this); editSelectAll.addActionListener(this); editDel.addActionListener(this); wordWrap.addActionListener(this); } public void actionPerformed(ActionEvent e) { Object src = e.getSource(); if(src.equals(fileNew)) { newFile(); } else if(src.equals(fileOpen) ) { openFile(); } else if(src.equals(fileSave) ) { saveFile(); } else if(src.equals(fileExit)) { exitFile(); } else if(src.equals(wordWrap)) { /* Calls the warpFile() method. */ wrapFile(); } else if(src.equals(editCut)) { txtPad.cut(); } else if(src.equals(editCopy) ) { txtPad.copy(); } else if(src.equals(editPaste)) { txtPad.paste(); } else if(src.equals(editSelectAll)) { txtPad.selectAll(); } else if(src.equals(editDel)) { //replace selected content with a blank txtPad.replaceSelection(""); } }//end of actionPerformed void newFile() { if(txtChanged true) { /* Sets the line and word wrap style to TRUE. */ txtPad.setLineWrap(true); txtPad.setWrapStyleWord(true); } else { /* Sets the line and word wrap style to FALSE. */ txtPad.setLineWrap(false); txtPad.setWrapStyleWord(false); } } public void keyPressed(KeyEvent e) { //System.out.println("KP"); } public void keyReleased(KeyEvent e) { //System.out.println("KR"); } public void keyTyped(KeyEvent e) { txtChanged = true; } class WinHandler extends WindowAdapter { public void windowClosing(WindowEvent e) { exitFile(); } } public static void main(String args[]) { MyPad mp = new MyPad(); } } class HelpDlg extends JDialog { public HelpDlg(MyPad m) { //MyPad object is the parent window of this dialog super(m,true); //register it //m is the MYPad ref that will be the owner //true means current dialog will be a modal window setSize(200, 150); setVisible(true); setDefaultCloseOperation(DISPOSE_ON_CLOSE); } }
The following is for a simple calculator; a scientific calculator is more complicated. I will assume the user will press keys to have a number appear on the display; to (for example) add this with another number, the user presses "+" followed by the second number, followed by "=". You would use a visual interface, with the number display, the digits, the equal sign, and a few operations (plus, minus, multiply, divide, ...). As soon as the user types the second number, the first number will disappear from the screen; therefore, you have to save it into some variable. Every time a key is pressed, you have to decide whether you should add a digit to the number in the display (if it is a digit, or a period), or whether to do a calculation (if it is +, -, *, /). If it is an operation, do the operation (conditionally, depending on the selected operation), and replace the number displayed by the new value. This is my sample code using JAVA: import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; import java.text.*; import javax.swing.border.*; class Calc extends JFrame implements ActionListener { private static final Font BIGGER_FONT = new Font("Tahoma", Font.BOLD, 13); private JRadioButton decimalb,binaryb,octalb,hexab,enableb, disableb; private JTextField _displayField, decimalTF, binaryTF, octalTF, hexaTF; private JLabel decimalL,binaryL,octalL,hexaL; private JButton exitb, convertb, clearb, backSpace, b9, b8, b7, b6, b5, b4, b3, b2, b1, b0, b11, b12, b13; private JButton b14, b15, b16, b17, b18, b19, b20, b21, b22, b23, b24, b25; private JPanel cbPanel, upperButtonPanel; private ButtonGroup group, group2; private boolean pluz = false; private boolean subs = false; private boolean multiply = false; private boolean divide = false; private boolean _startNumber = true; private boolean dotCheck = false; private String firstValue, Secondvalue; private String _previousOp = "="; private DecimalFormat df = new DecimalFormat("###,###,###.##"); private CalculatorLogic calLogic = new CalculatorLogic(); public static void main(String[] args) { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception unused) { ; } Calc window = new Calc(); window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); window.setVisible(true); } public Calc() { super("Calculator With Number System Converter"); _displayField = new JTextField("", 15); _displayField.setHorizontalAlignment(JTextField.RIGHT); _displayField.setFont(BIGGER_FONT); _displayField.setEditable(false); _displayField.setBackground(Color.WHITE); upperButtonPanel = new JPanel(); upperButtonPanel.setLayout(new FlowLayout()); upperButtonPanel.setBackground(Color.lightGray); upperButtonPanel.setPreferredSize(new Dimension(170, 300)); decimalb = new JRadioButton("Decimal", false); binaryb = new JRadioButton("Binary", false); octalb = new JRadioButton("Octal", false); hexab = new JRadioButton("Hexadecimal", false); decimalb.setFont(BIGGER_FONT); binaryb.setFont(BIGGER_FONT); octalb.setFont(BIGGER_FONT); hexab.setFont(BIGGER_FONT); decimalb.addActionListener(this); binaryb.addActionListener(this); octalb.addActionListener(this); hexab.addActionListener(this); group = new ButtonGroup(); group.add(decimalb); group.add(binaryb); group.add(octalb); group.add(hexab); upperButtonPanel.add(decimalb); upperButtonPanel.add(binaryb); upperButtonPanel.add(octalb); upperButtonPanel.add(hexab); upperButtonPanel.setVisible(false); JPanel panel = new JPanel(new GridLayout(10, 1)); panel.setPreferredSize(new Dimension(300, 300)); panel.setBorder(new BevelBorder(BevelBorder.LOWERED)); decimalTF = new JTextField(20); binaryTF = new JTextField(20); octalTF = new JTextField(20); hexaTF = new JTextField(20); decimalTF.setEditable(false); binaryTF.setEditable(false); octalTF.setEditable(false); hexaTF.setEditable(false); decimalTF.setBackground(Color.WHITE); binaryTF.setBackground(Color.WHITE); octalTF.setBackground(Color.WHITE); hexaTF.setBackground(Color.WHITE); decimalTF.setFont(BIGGER_FONT); binaryTF.setFont(BIGGER_FONT); octalTF.setFont(BIGGER_FONT); hexaTF.setFont(BIGGER_FONT); decimalTF.setVisible(false); binaryTF.setVisible(false); octalTF.setVisible(false); hexaTF.setVisible(false); decimalL = new JLabel("Decimal Value"); binaryL = new JLabel("Binary Value"); octalL = new JLabel("Octal Value"); hexaL = new JLabel("Hexadecimal Value"); decimalL.setFont(BIGGER_FONT); binaryL.setFont(BIGGER_FONT); octalL.setFont(BIGGER_FONT); hexaL.setFont(BIGGER_FONT); decimalL.setVisible(false); binaryL.setVisible(false); octalL.setVisible(false); hexaL.setVisible(false); panel.add(decimalL); panel.add(decimalTF); panel.add(binaryL); panel.add(binaryTF); panel.add(octalL); panel.add(octalTF); panel.add(hexaL); panel.add(hexaTF); upperButtonPanel.add(panel); add(upperButtonPanel, BorderLayout.NORTH); JPanel buttonPanel = new JPanel(); buttonPanel.setLayout(new GridLayout(5, 2, 5, 5)); buttonPanel.setBackground(Color.lightGray); buttonPanel.setBorder(new BevelBorder(BevelBorder.LOWERED)); b9 = new JButton("9"); b8 = new JButton("8"); b7 = new JButton("7"); b6 = new JButton("6"); b5 = new JButton("5"); b4 = new JButton("4"); b3 = new JButton("3"); b2 = new JButton("2"); b1 = new JButton("1"); b0 = new JButton("0"); b11 = new JButton("."); b12 = new JButton("/"); b13 = new JButton("*"); b14 = new JButton("-"); b15 = new JButton("+"); b16 = new JButton("A"); b17 = new JButton("B"); b18 = new JButton("C"); b19 = new JButton("D"); b20 = new JButton("E"); b21 = new JButton("F"); b22 = new JButton("="); b23 = new JButton("sqrt"); b24 = new JButton("x\u00B2"); b25 = new JButton("x\u00B3"); b1.setFont(BIGGER_FONT); b2.setFont(BIGGER_FONT); b3.setFont(BIGGER_FONT); b4.setFont(BIGGER_FONT); b5.setFont(BIGGER_FONT); b6.setFont(BIGGER_FONT); b7.setFont(BIGGER_FONT); b8.setFont(BIGGER_FONT); b9.setFont(BIGGER_FONT); b0.setFont(BIGGER_FONT); b11.setFont(BIGGER_FONT); b12.setFont(BIGGER_FONT); b13.setFont(BIGGER_FONT); b14.setFont(BIGGER_FONT); b15.setFont(BIGGER_FONT); b16.setFont(BIGGER_FONT); b17.setFont(BIGGER_FONT); b18.setFont(BIGGER_FONT); b19.setFont(BIGGER_FONT); b20.setFont(BIGGER_FONT); b21.setFont(BIGGER_FONT); b22.setFont(BIGGER_FONT); b23.setFont(BIGGER_FONT); b24.setFont(BIGGER_FONT); b25.setFont(BIGGER_FONT); b1.addActionListener(this); b2.addActionListener(this); b3.addActionListener(this); b4.addActionListener(this); b5.addActionListener(this); b6.addActionListener(this); b7.addActionListener(this); b8.addActionListener(this); b9.addActionListener(this); b0.addActionListener(this); b11.addActionListener(this); b12.addActionListener(this); b13.addActionListener(this); b14.addActionListener(this); b15.addActionListener(this); b16.addActionListener(this); b17.addActionListener(this); b18.addActionListener(this); b19.addActionListener(this); b20.addActionListener(this); b21.addActionListener(this); b22.addActionListener(this); b23.addActionListener(this); b24.addActionListener(this); b25.addActionListener(this); b16.setEnabled(false); b17.setEnabled(false); b18.setEnabled(false); b19.setEnabled(false); b20.setEnabled(false); b21.setEnabled(false); buttonPanel.add(b7); buttonPanel.add(b8); buttonPanel.add(b9); buttonPanel.add(b12); buttonPanel.add(b13); buttonPanel.add(b15); buttonPanel.add(b4); buttonPanel.add(b5); buttonPanel.add(b6); buttonPanel.add(b15); buttonPanel.add(b14); buttonPanel.add(b11); buttonPanel.add(b1); buttonPanel.add(b2); buttonPanel.add(b3); buttonPanel.add(b0); buttonPanel.add(b22); buttonPanel.add(b16); buttonPanel.add(b17); buttonPanel.add(b18); buttonPanel.add(b11); buttonPanel.add(b23); buttonPanel.add(b19); buttonPanel.add(b20); buttonPanel.add(b21); buttonPanel.add(b24); buttonPanel.add(b25); add(buttonPanel); group2 = new ButtonGroup(); disableb = new JRadioButton("Disable Converter", true); enableb = new JRadioButton("Enable Converter", false); disableb.setFont(BIGGER_FONT); enableb.setFont(BIGGER_FONT); disableb.addActionListener(this); enableb.addActionListener(this); group2.add(disableb); group2.add(enableb); cbPanel = new JPanel(new GridLayout(3, 3)); cbPanel.setBorder(new BevelBorder(BevelBorder.RAISED)); cbPanel.add(disableb); cbPanel.add(enableb); convertb = new JButton("Convert"); clearb = new JButton("Clear"); exitb = new JButton("Exit"); backSpace = new JButton("BackSpace"); convertb.addActionListener(this); clearb.addActionListener(this); exitb.addActionListener(this); backSpace.addActionListener(this); convertb.setFont(BIGGER_FONT); clearb.setFont(BIGGER_FONT); exitb.setFont(BIGGER_FONT); backSpace.setFont(BIGGER_FONT); cbPanel.add(convertb); cbPanel.add(clearb); cbPanel.add(backSpace); cbPanel.add(exitb); convertb.setEnabled(false); JPanel content2 = new JPanel(); content2.setLayout(new BorderLayout(5, 5)); content2.add(_displayField, BorderLayout.NORTH); content2.add(buttonPanel , BorderLayout.CENTER); content2.add(cbPanel, BorderLayout.SOUTH); add(content2, BorderLayout.SOUTH); this.setSize(340, 300); this.setResizable(false); this.setLocationRelativeTo(null); } public void actionPerformed(ActionEvent e) { try{ if(decimalb.isSelected()) { b0.setEnabled(true); b1.setEnabled(true); b2.setEnabled(true); b3.setEnabled(true); b4.setEnabled(true); b5.setEnabled(true); b6.setEnabled(true); b7.setEnabled(true); b8.setEnabled(true); b9.setEnabled(true); b16.setEnabled(false); b17.setEnabled(false); b18.setEnabled(false); b19.setEnabled(false); b20.setEnabled(false); b21.setEnabled(false); } else if(binaryb.isSelected()) { b2.setEnabled(false); b3.setEnabled(false); b4.setEnabled(false); b5.setEnabled(false); b6.setEnabled(false); b7.setEnabled(false); b8.setEnabled(false); b9.setEnabled(false); b16.setEnabled(false); b17.setEnabled(false); b18.setEnabled(false); b19.setEnabled(false); b20.setEnabled(false); b21.setEnabled(false); } else if(octalb.isSelected()) { b0.setEnabled(true); b1.setEnabled(true); b2.setEnabled(true); b3.setEnabled(true); b4.setEnabled(true); b5.setEnabled(true); b6.setEnabled(true); b7.setEnabled(true); b16.setEnabled(false); b17.setEnabled(false); b18.setEnabled(false); b19.setEnabled(false); b20.setEnabled(false); b21.setEnabled(false); b8.setEnabled(false); b9.setEnabled(false); } else if(hexab.isSelected()) { b0.setEnabled(true); b1.setEnabled(true); b2.setEnabled(true); b3.setEnabled(true); b4.setEnabled(true); b5.setEnabled(true); b6.setEnabled(true); b7.setEnabled(true); b8.setEnabled(true); b9.setEnabled(true); b16.setEnabled(true); b17.setEnabled(true); b18.setEnabled(true); b19.setEnabled(true); b20.setEnabled(true); b21.setEnabled(true); } if((e.getActionCommand().equals("Convert")) && decimalb.isSelected()) { String input, bin="",oct="",hex=""; int rem,rem2,rem3,len; char x; input = _displayField.getText().trim(); try{ if(input.equals("")) throw new Exception("Error"); else len = input.length(); int num = Integer.parseInt(input); while(num>0) { rem = num%2; num/=2; bin = rem + bin; } binaryTF.setText(bin); decimalTF.setText(input); int num2 = Integer.parseInt(input); while(num2>0) { rem2 = num2%8; oct = rem2 + oct; num2/=8; } octalTF.setText(oct); int num3 = Integer.parseInt(input); while(num3>0) { rem3 = num3%16; if(rem3<10) hex = rem3 + hex; else if(rem3 0) { JOptionPane.showMessageDialog(null,"Can't divide by zero", "Error Message", JOptionPane.ERROR_MESSAGE); return 0; } else return (a / b); } public double stringToDouble(String a) { return Double.parseDouble(a); } }
"Pluggable look and feel" refers to the ability to change the look and feel (LnF) of a Java program on the fly. The term is actually quite descriptive. If you change the LnF of your program, all GUI elements will have a distinctly different look to them. Windows will be drawn differently, buttons and scroll bars will look (and may respond) differently, etc. You can change the current LnF by invoking: UIManager.setLookAndFeel(lookAndFeel); Probably the most useful invocation of this method uses the UIManager class to figure out what the underlying operating system is, and to use the default LnF for your program: UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); This will make programs run on a Windows machine look like a Windows application, programs run on a Mac look like a Mac application, etc. Another useful function is the UIManager.getInstalledLookAndFeels(), which will return an array of all available LnFs. Below is a simple sample program which will demonstrate these methods. Two things to take note of: # Once you change the look and feel, you need to call the updateUI method on all JComponents. The good people at Sun recommend calling SwingUtilities.updateComponentTreeUI(Component). If you call this on your top level components (main frame/window), it should update all components contained within it. # UIManager.setLookAndFeel can throw a lot of exceptions. Be prepared to have a large try-catch block (or a throws clause) everywhere you set the LnF. try { // Start off with the system default LnF UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); // Ugly, ugly try-catch block if you catch each type individually. } catch (final ClassNotFoundException ex) { } catch (final InstantiationException ex) { } catch (final IllegalAccessException ex) { } catch (final UnsupportedLookAndFeelException ex) { } catch (final ClassCastException ex) { } // Create our frame final JFrame frame = new JFrame("LnF Test Frame"); // Set up our simple panel final JPanel panel = new JPanel(); panel.setLayout(new GridLayout(4, 4)); // Set up a button for each installed LookAndFeel. // When a button is pressed, the LnF will change. for (final LookAndFeelInfo lnfInfo : UIManager.getInstalledLookAndFeels()) { final String lnfName = lnfInfo.getName(); final String lnfClassName = lnfInfo.getClassName(); final JButton button = new JButton(lnfName); button.addActionListener(new ActionListener() { // Here's where we change and update the LnF public final void actionPerformed(final ActionEvent ev) { try { UIManager.setLookAndFeel(lnfClassName); SwingUtilities.updateComponentTreeUI(frame); } catch (final Exception ex) { } } }); panel.add(button); } // Set up and display our frame frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // (adding a scroll panel just to see some more components) frame.setContentPane(new JScrollPane(panel, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS)); frame.setSize(300, 300); frame.setVisible(true);
import java.io.*; import java.util.*; public class Calculator { public static void main(String args[]) { System.out.println("Make your arithmetic selection from the choices below:\n"); System.out.println(" 1. Addition"); System.out.println(" 2. Subtraction"); System.out.println(" 3. Multiplication"); System.out.println(" 4. Division\n"); System.out.print(" Your choice? "); Scanner kbReader = new Scanner(System.in); int choice = kbReader.nextInt(); if((choice<=4) && (choice>0)) { System.out.print("\nEnter first operand. "); double op1 = kbReader.nextDouble(); System.out.print("\nEnter second operand."); double op2 = kbReader.nextDouble(); System.out.println(""); switch (choice) { case 1: //addition System.out.println(op1 + " plus " + op2 + " = " + (op1 + op2) ); break; case 2: //subtraction System.out.println(op1 + " minus " + op2 + " = " + (op1 - op2) ); break; case 3: //multiplication System.out.println(op1 + " times " + op2 + " = " + (op1 * op2) ); break; case 4: //division System.out.println(op1 + " divided by " + op2 + " = " + (op1 / op2) ); } } else { System.out.println("Please enter a 1, 2, 3, or 4."); } } }