So I have a couple Jpanels in my frame, and the idea is that, when one of the panels is selected, it will be highlighted. 这只是第一步,因为最后,我希望能够让按钮在面板上起作用,但只有突出显示的那个。
我在想我想要在面板上安装某种鼠标监听器,但我不确定如何实现它以获得我想要的结果。
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.Border;
public class CustomComponent {
Border emptyBorder = BorderFactory.createEmptyBorder(1,1,1,1);
Border selectBorder = BorderFactory.createLineBorder(Color.blue);
JPanel[] panels;
private JPanel getContent() {
JLabel label = new JLabel();
label.setText("fffffffff");
label.setBounds(5, 5, 25, 25);
JLabel label2 = new JLabel();
label2.setText("HHHHHHHHHH");
label2.setBounds(25, 25, 25, 25);
JLabel label3 = new JLabel();
label3.setText("YYYYYYYY");
label3.setBounds(50, 50, 25, 25);
JPanel mainPanel = new JPanel();
mainPanel.setSize(new Dimension(300,300));
JPanel panel1 = new JPanel();
panel1.add(label);
JPanel panel2 = new JPanel();
panel2.add(label2);
JPanel panel3 = new JPanel();
panel3.add(label3);
panel1.setBackground(Color.WHITE);
panel2.setBackground(Color.MAGENTA);
panel3.setBackground(Color.orange);
panel1.setBorder(emptyBorder);
panel2.setBorder(emptyBorder);
panel3.setBorder(emptyBorder);
panels = new JPanel[] { panel1, panel2, panel3 };
mainPanel.add(panel1);
mainPanel.add(panel2);
mainPanel.add(panel3);
return mainPanel;
}
public static void main(String[] args) {
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new CustomComponent().getContent());
frame.pack();
frame.setVisible(true);
}
}