11.7 使用調試器
❤🧡💛💚💙💜🤎🖤❤🧡💛💚💙💜🤎🖤❤🧡💛💚💙💜🤎🖤
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class BuggyButtonTest {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
BuggyButtonFrame frame = new BuggyButtonFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
class BuggyButtonFrame extends JFrame {
private static final int W = 300;
private static final int H = 200;
public BuggyButtonFrame(){
setTitle("BuggyButtonTest");
setSize(W,H);
BuggyButtonPanel panel = new BuggyButtonPanel();
add(panel);
}
}
class BuggyButtonPanel extends JPanel{
public BuggyButtonPanel(){
ActionListener listener = new ButtonListener();
String [] colors = new String[]{"Yellow","Blue","Red"};
for(int i = 0; i < colors.length; i++){
JButton b = new JButton(colors[i]);
add(b);
b.addActionListener(listener);
}
}
private class ButtonListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
String arg = e.getActionCommand();
String [] colors = new String[]{"yellow","blue","red"};
Color[] colorObjs = new Color[]{Color.YELLOW,Color.BLUE,Color.RED};
for(int i = 0;i < colors.length; i++){
if(arg.equals(colors[i])){
setBackground(colorObjs[i]);
}
}
}
}
}
❤🧡💛💚💙💜🤎🖤❤🧡💛💚💙💜🤎🖤❤🧡💛💚💙💜🤎🖤
🍓 斷點:希望在某一句執行前檢視的位置,點選行号左側,出現紅色小圓圈即可(需要在執行前或執行到這一句前加斷點)

🍓 IDEA 調試方式1:右鍵+DEBUG 按鈕
🍓 IDEA 調試方式2:點選 main 左側小圖示 + DEBUG 按鈕
比如點選這個位置
🍓 檢視參數方式 1:下方控制台 Debug->Debugger->右下角檢視
🍓 檢視參數方式 2:滑鼠光标移動到變量上檢視
此處發現起的名稱不同,把公共名稱改為在外側定義數組,防止重複書寫字元串出錯
❤🧡💛💚💙💜🤎🖤❤🧡💛💚💙💜🤎🖤❤🧡💛💚💙💜🤎🖤
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class BuggyButtonTest {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
BuggyButtonFrame frame = new BuggyButtonFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
class BuggyButtonFrame extends JFrame {
private static final int W = 300;
private static final int H = 200;
public BuggyButtonFrame(){
setTitle("BuggyButtonTest");
setSize(W,H);
BuggyButtonPanel panel = new BuggyButtonPanel();
add(panel);
}
}
class BuggyButtonPanel extends JPanel{
public BuggyButtonPanel(){
ActionListener listener = new ButtonListener();
for(int i = 0; i < colors.length; i++){
JButton b = new JButton(colors[i]);
add(b);
b.addActionListener(listener);
}
}
final String [] colors = new String[]{"Yellow","Blue","Red"};
private class ButtonListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
String arg = e.getActionCommand();
final Color[] colorObjs = new Color[]{Color.YELLOW,Color.BLUE,Color.RED};
for(int i = 0;i < colors.length; i++){
if(arg.equals(colors[i])){
setBackground(colorObjs[i]);
}
}
}
}
}
❤🧡💛💚💙💜🤎🖤❤🧡💛💚💙💜🤎🖤❤🧡💛💚💙💜🤎🖤
🍉 小貼士:相似的代碼盡量用循環處理,公共的變量使用全局變量(成員變量)定義