Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.awt.*;
- import javax.swing.BorderFactory;
- import javax.swing.JButton;
- import javax.swing.JPanel;
- import javax.swing.JTextField;
- /*Just add this to a JFrame for an instant Calculator GUI*/
- public class GUIPanel extends JPanel {
- public GUIPanel(){
- addDisplay();
- addPanels();
- }
- private void addDisplay(){
- JTextField numberDisplay = new JTextField("0");
- numberDisplay.setHorizontalAlignment(JTextField.RIGHT);
- numberDisplay.setBorder(BorderFactory.createLoweredBevelBorder());
- numberDisplay.setPreferredSize(new Dimension(200,50));
- numberDisplay.setBackground(new Color(204,255,204));
- this.add(numberDisplay);
- }
- private void addPanels(){
- String [] inputButtons = {"MC","M+","M-", "MR","C","±","÷","×","1","2","3","-","4","5","6","+","7","8","9","0","="};
- JPanel topPanel = new JPanel();
- JPanel bottomPanel = new JPanel(new GridBagLayout());
- GridBagConstraints gbc = new GridBagConstraints();
- topPanel.setLayout(new GridLayout(4,4));
- for(String x:inputButtons){
- if(x.equals("0")){
- addWideButton(x,bottomPanel,gbc);
- }
- else if(x.equals("=")){
- addTallButton(x,bottomPanel,gbc);
- }
- else if(x.equals("7") || x.equals("8")|| x.equals("9")){
- gbc.gridwidth = 1;
- gbc.gridheight = 1;
- if(x.equals("7")){
- gbc.gridx = 0;
- gbc.gridy = 0;
- }
- else if(x.equals("8")){
- gbc.gridx = 0;
- gbc.gridy = 1;
- }
- else if(x.equals("9")){
- gbc.gridx = 0;
- gbc.gridy = 2;
- }
- addButton(x,bottomPanel,gbc);
- }
- else{
- addButton(x,topPanel,gbc);
- }
- }
- // this button would not go tot he right place for some reason!!
- gbc.gridx = 2;
- gbc.gridy = 1;
- JButton button = new JButton(".");
- button.setPreferredSize(new Dimension(55,30));
- bottomPanel.add(button, gbc);
- // end of the "." button fiasco!
- topPanel.setOpaque(false);
- bottomPanel.setOpaque(false);
- setPreferredSize(new Dimension(225,250));
- this.add(topPanel);
- this.add(bottomPanel);
- }
- private void addButton(String text, Container container, GridBagConstraints gbc){
- JButton button = new JButton(text);
- button.setPreferredSize(new Dimension(55,30));
- button.setOpaque(false);
- container.add(button);
- }
- private void addWideButton(String text, Container container, GridBagConstraints gbc){
- JButton button = new JButton(text);
- button.setOpaque(false);
- button.setPreferredSize(new Dimension(110,30));
- gbc.gridx = 0;
- gbc.gridy = 1;
- gbc.gridheight = 1;
- gbc.gridwidth = 2;
- container.add(button, gbc);
- }
- private void addTallButton(String text, Container container, GridBagConstraints gbc){
- JButton button = new JButton(text);
- button.setOpaque(false);
- button.setPreferredSize(new Dimension(55,60));
- gbc.gridx = 3;
- gbc.gridy = 0;
- gbc.gridheight = 2;
- gbc.gridwidth = 1;
- container.add(button, gbc);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement