我在应该显示键盘的屏幕键盘上写了这个。我的问题是我希望 JButtons 适合它们的标签大小,而不是为所有 JButtons 设置固定大小。例如键盘上的数字:“1,2,3....”应该是小的 jbutton,而“backspace”“tab”等键应该更大(适合他们标签的大小)
这是我写的代码:
package Q2;
import java.awt.*;
import javax.swing.*;
public class MainPanel extends JPanel{
private JButton[][] button;
private JPanel[] panel; //Array of panels for each buttons line
private JPanel parent;
private static final String[][] key = {
{"`","1","2","3","4","5","6","7","8","9","0","-","+","Backspace"},
{"Tab","Q","W","E","R","T","Y","U","I","O","P","[","]"},
{"Caps","A","S","D","F","G","H","J","K","L",";","'","\\","Enter"},
{"Shif","Z","X","C","V","B","N","M",",",".","?","/"},
{" ",",","<","v",">"}
};
//Constructor for main Panel
public MainPanel(){
super();
setLayout(new BorderLayout());
TextField textField= new TextField(20);
Font font1 = new Font("david", Font.BOLD, 22);
textField.setFont(font1);
add(textField,BorderLayout.CENTER);
//initialize the parent panel and array of 5 panels and the buttons array
parent = new JPanel();
parent.setLayout(new GridLayout(0,1));
panel = new JPanel[5];
button = new JButton[20][20];
for (int row = 0; row<key.length; row++){
panel[row] = new JPanel();
for (int column = 0; column<key[row].length; column++){
button[row][column] = new JButton(key[row][column]);
button[row][column].setPreferredSize(new Dimension(key[row][column].length()+80,30));
button[row][column].putClientProperty("row", row);
button[row][column].putClientProperty("column", column);
button[row][column].putClientProperty("key", key[row][column]);
//button[row][column].addActionListener(new MyActionListener());
panel[row].add(button[row][column]);
}
parent.add(panel[row]);
}
add(parent,BorderLayout.SOUTH);
}
/*
//panel for line 1 of keyboard buttons - numbers
protected JComponent getPanelLine1(){
JPanel panel1 = new JPanel();
for (int i=0; i<10; i++){
}
}
//panel for line 1 of keyboard buttons - Q-P
protected JComponent getPanelLine2(){
}
//panel for line 1 of keyboard buttons - A-L
protected JComponent getPanelLine3(){
}![enter image description here][1]
//panel for line 1 of keyboard buttons - Z-M
protected JComponent getPanelLine4(){
}
//panel for line 1 of keyboard buttons - space and arrows
protected JComponent getPanelLine5(){
}*/
}
图片: