2013-11-16 3 views
0

Я создаю калькулятор, и я бы хотел, чтобы мой JTextField появлялся на самом верху, без других кнопок рядом с ним, как вы видели в обычном калькуляторе.Java Grid Layout

http://i.stack.imgur.com/cS6zN.png

Вот мой код:

import java.awt.BorderLayout; 
import java.awt.Dimension; 
import java.awt.GridLayout; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 

import javax.swing.JButton; 
import javax.swing.JFrame; 
import javax.swing.JLabel; 
import javax.swing.JPanel; 
import javax.swing.JTextField; 

public class Calculator { 

// oh boy.. lots of declarations here 
JLabel current = new JLabel(); 
static JPanel panel = new JPanel(); 
JButton add = new JButton("+"); 
JButton subtract = new JButton("-"); 
JButton multiply = new JButton("x"); 
JButton divide = new JButton("/"); 
JButton solve = new JButton("="); 
JButton number1 = new JButton("1"); 
JButton number2 = new JButton("2"); 
JButton number3 = new JButton("3"); 
JButton number4 = new JButton("4"); 
JButton number5 = new JButton("5"); 
JButton number6 = new JButton("6"); 
JButton number7 = new JButton("7"); 
JButton number8 = new JButton("8"); 
JButton number9 = new JButton("9"); 
JButton number0 = new JButton("0"); 
JButton dot = new JButton("."); 
JTextField solution = new JTextField(10); 
boolean addboolean = false; 
boolean subtractboolean = false; 
boolean multiplyboolean = false; 
boolean divideboolean = false; 

// just some variables for our dimensions 
int width = 150; 
int height = 150; 

public Calculator() { 
    // house keeping... initialization mostly 
    panel.setSize(width, height); 

    GridLayout grid = new GridLayout(5, 1); 
    panel.setLayout(grid); 

    solution.setEditable(false); 

    // add components to panel 

    panel.add(solution, BorderLayout.NORTH); 
    panel.add(number1); 
    panel.add(number2); 
    panel.add(number3); 
    panel.add(add); 
    panel.add(number4); 
    panel.add(number5); 
    panel.add(number6); 
    panel.add(subtract); 
    panel.add(number7); 
    panel.add(number8); 
    panel.add(number9); 
    panel.add(multiply); 
    panel.add(number0); 
    panel.add(dot); 
    panel.add(divide); 
    panel.add(solve); 

    // button listeners, they set our booleans to true on button click and 
    // set the symbol 
    add.addActionListener(new ActionListener() { 
     public void actionPerformed(ActionEvent e) { 
      addboolean = true; 
      current.setText("+"); 
     } 
    }); 

    subtract.addActionListener(new ActionListener() { 
     public void actionPerformed(ActionEvent e) { 
      subtractboolean = true; 
      current.setText("-"); 
     } 
    }); 

    multiply.addActionListener(new ActionListener() { 
     public void actionPerformed(ActionEvent e) { 
      multiplyboolean = true; 
      current.setText("x"); 
     } 
    }); 

    divide.addActionListener(new ActionListener() { 
     public void actionPerformed(ActionEvent e) { 
      divideboolean = true; 
      current.setText("/"); 
     } 
    }); 

    // listener for solve button which just parses our numbers and submits 
    // it to the solve method 
    solve.addActionListener(new ActionListener() { 
     public void actionPerformed(ActionEvent e) { 
      // double num1 = Double.parseDouble(firstNum.getText()); 
      // double num2 = Double.parseDouble(secondNum.getText()); 
      // solve(num1, num2); 
     } 
    }); 

} 

// solves the equation 
public void solve(double num1, double num2) { // takes 2 parameters (the 
                // first number and second 
               // number) 
    double result = 0; // initialize our result 

    // checks to see which type of equation we will be solving, then solves 
    // it 
    if (addboolean) { 
     result = num1 + num2; 
    } else if (subtractboolean) { 
     result = num1 - num2; 
    } else if (multiplyboolean) { 
     result = num1 * num2; 
    } else if (divideboolean) { 
     result = (num1)/(num2); 
    } 

    // prints out final text 
    solution.setText("The final result is: " + result); 

    // sets our booleans back to true so they can be reused during the same 
    // runtime 
    addboolean = false; 
    subtractboolean = false; 
    multiplyboolean = false; 
    divideboolean = false; 
} 

// runs the program 
public static void main(String[] args) { 
    new Calculator(); 
} 

} 

ответ

3

я бы порекомендовал вам использовать мастер-панель с BorderLayout

JPanel masterPanel = new JPanel(new BorderLayout()); 

, к которому добавляют раствор:

masterPanel.add(solution, BorderLayout.NORTH); 

и впоследствии GridLayout панель с ключами:

masterPanel.add(panel, BorderLayout.CENTER); 

Другие менеджеры компоновки могут работать, а также (в зависимости от требуемого конструкции), а именно: A BoxLayout

NB: Ваша линия panel.add(solution, BorderLayout.NORTH); не имеет эффект на макет, потому что ваш panel использует GridLayout

+0

+1, гнездовые менеджеры компоновки всегда вариант, чтобы рассмотреть. – camickr

+0

http://pastebin.com/zvh1AdKs? JTextField все еще находится на той же линии, что и кнопки. – Nicolas

+0

Вы должны добавить LayoutManager в свой 'masterPanel', иначе он будет использовать LayoutManager по умолчанию, который является' FlowLayout'. Я отредактировал свой ответ выше. – Delpes

1

Учтите, что это с головы, но это должно работать. Просто не устанавливайте макет панелей в сетку и вместо этого выполните следующее.

Gridlayout mainlayout= new GridLayout(1,2); 
GridLayout grid = new GridLayout(5, 1); //Probably need to change this, 
//as this is creating a grid containing 5 columns and 1 row. If you are 
//trying to make this like the picture you'll need at least a 4x4 grid. 

//Important!! Add items to grid here instead of panel. 
mainlayout.add(grid); 
mainlayout.add(solution); 
panel.setLayout(mainlayout); 
4

DYM как-то это?

enter image description here

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

public class Calculator { 

// oh boy.. lots of declarations here 
JLabel current = new JLabel(); 
// static is usually BAD NEWS & rarely necessary for GUI elements. 
//static JPanel panel = new JPanel(); 
JPanel panel = new JPanel(new GridLayout(0,4,3,3)); 
JPanel gui = new JPanel(new BorderLayout(3,3)); 

JButton add = new JButton("+"); 
JButton subtract = new JButton("-"); 
JButton multiply = new JButton("x"); 
JButton divide = new JButton("/"); 
JButton solve = new JButton("="); 
JButton number1 = new JButton("1"); 
JButton number2 = new JButton("2"); 
JButton number3 = new JButton("3"); 
JButton number4 = new JButton("4"); 
JButton number5 = new JButton("5"); 
JButton number6 = new JButton("6"); 
JButton number7 = new JButton("7"); 
JButton number8 = new JButton("8"); 
JButton number9 = new JButton("9"); 
JButton number0 = new JButton("0"); 
JButton dot = new JButton("."); 
JTextField solution = new JTextField(10); 
boolean addboolean = false; 
boolean subtractboolean = false; 
boolean multiplyboolean = false; 
boolean divideboolean = false; 

// just some variables for our dimensions 
int width = 150; 
int height = 150; 

public Calculator() { 
    // house keeping... initialization mostly 
    panel.setSize(width, height); 

    solution.setEditable(false); 

    // add components to panel 

    gui.add(solution, BorderLayout.PAGE_START); 
    gui.add(panel, BorderLayout.CENTER); 
    panel.add(number1); 
    panel.add(number2); 
    panel.add(number3); 
    panel.add(add); 
    panel.add(number4); 
    panel.add(number5); 
    panel.add(number6); 
    panel.add(subtract); 
    panel.add(number7); 
    panel.add(number8); 
    panel.add(number9); 
    panel.add(multiply); 
    panel.add(number0); 
    panel.add(dot); 
    panel.add(divide); 
    panel.add(solve); 

    // button listeners, they set our booleans to true on button click and 
    // set the symbol 
    add.addActionListener(new ActionListener() { 
     public void actionPerformed(ActionEvent e) { 
      addboolean = true; 
      current.setText("+"); 
     } 
    }); 

    subtract.addActionListener(new ActionListener() { 
     public void actionPerformed(ActionEvent e) { 
      subtractboolean = true; 
      current.setText("-"); 
     } 
    }); 

    multiply.addActionListener(new ActionListener() { 
     public void actionPerformed(ActionEvent e) { 
      multiplyboolean = true; 
      current.setText("x"); 
     } 
    }); 

    divide.addActionListener(new ActionListener() { 
     public void actionPerformed(ActionEvent e) { 
      divideboolean = true; 
      current.setText("/"); 
     } 
    }); 

    // listener for solve button which just parses our numbers and submits 
    // it to the solve method 
    solve.addActionListener(new ActionListener() { 
     public void actionPerformed(ActionEvent e) { 
      // double num1 = Double.parseDouble(firstNum.getText()); 
      // double num2 = Double.parseDouble(secondNum.getText()); 
      // solve(num1, num2); 
     } 
    }); 

} 

// solves the equation 
public void solve(double num1, double num2) { // takes 2 parameters (the 
                // first number and second 
               // number) 
    double result = 0; // initialize our result 

    // checks to see which type of equation we will be solving, then solves 
    // it 
    if (addboolean) { 
     result = num1 + num2; 
    } else if (subtractboolean) { 
     result = num1 - num2; 
    } else if (multiplyboolean) { 
     result = num1 * num2; 
    } else if (divideboolean) { 
     result = (num1)/(num2); 
    } 

    // prints out final text 
    solution.setText("The final result is: " + result); 

    // sets our booleans back to true so they can be reused during the same 
    // runtime 
    addboolean = false; 
    subtractboolean = false; 
    multiplyboolean = false; 
    divideboolean = false; 
} 

// runs the program 
public static void main(String[] args) { 
    Calculator c = new Calculator(); 
    JOptionPane.showMessageDialog(null, c.gui); 
} 

}