Java按钮布局和显示
我的目标是向控制台显示一条消息,显示我按下的按钮(按钮从1到6)。这是我得到的最远的距离 代码:Java按钮布局和显示,java,swing,jpanel,jbutton,actionlistener,Java,Swing,Jpanel,Jbutton,Actionlistener,我的目标是向控制台显示一条消息,显示我按下的按钮(按钮从1到6)。这是我得到的最远的距离 代码: public class excercise5_1 extends JFrame { public excercise5_1() { setLayout(new FlowLayout()); // Create two panels JPanel panel1 = new JPanel(); JPanel panel2 =
public class excercise5_1 extends JFrame {
public excercise5_1() {
setLayout(new FlowLayout());
// Create two panels
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
// Add three buttons to each panel
panel1.add(new JButton(" Button 1 "));
panel1.add(new JButton(" Button 2 "));
panel1.add(new JButton(" Button 3 "));
panel2.add(new JButton(" Button 4 "));
panel2.add(new JButton(" Button 5 "));
panel2.add(new JButton(" Button 6 "));
// Add panels to frame
add(panel1);
add(panel2);
}
public static void main(String[] args) {
excercise5_1 frame = new excercise5_1();
frame.setTitle(" Exercise 12_1 ");
frame.setSize(600,75);
frame.setLocationRelativeTo(null); // center frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
如果我按下按钮,我不知道该怎么做才能让它显示“按钮2”
panel1.add(新的JButton(…)
jbuttonmybutton=newjbutton(…)
;然后panel1.add(我的按钮)代码>
addActionListener(…)
方法向按钮添加ActionListener,并让ActionListener打印ActionEvent的getActionCommand()字符串。ActionEvent是传递到actionPerformed(ActionEvent e)
方法中的参数看看这个-。@Ryan:不客气。最重要的建议是我的最后一句话。在来这里之前,你必须先钻研教程。使用教程是一种学习技能,通过练习会变得更好。