import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
class MyFrame extends JFrame {
public MyFrame() {
JPanel panel = new JPanel(new GridBagLayout());
JLabel image = new JLabel();
image.setIcon(new ImageIcon(getClass().getResource("/image.png")));
JLabel question = new JLabel("3 + 3 = ?");
JRadioButton rb1 = new JRadioButton("5");
JRadioButton rb2 = new JRadioButton("3");
JRadioButton rb3 = new JRadioButton("6");
JRadioButton rb4 = new JRadioButton("9");
JRadioButton rb5 = new JRadioButton("23");
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;//set the x location of the grid for the next component
c.gridy = 0;//set the y location of the grid for the next component
panel.add(image,c);
c.gridy = 1;//change the y location
c.anchor=GridBagConstraints.WEST;//left align components after this point
panel.add(question,c);
c.gridy = 2;//change the y location
panel.add(rb1,c);
c.gridy = 3;//change the y location
panel.add(rb2,c);
c.gridy = 4;//change the y location
panel.add(rb3,c);
c.gridy = 5;//change the y location
panel.add(rb4,c);
c.gridy =6;//change the y location
panel.add(rb5,c);
this.getContentPane().add(panel);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.pack();
}
public static void main(String[] args) {
MyFrame myFrame = new MyFrame();
myFrame.setVisible(true);
}
}
2条答案
按热度按时间sbtkgmzw1#
你可以用
GridBagLayout
为了这个。它很容易使用。下面是一个示例实现。参考文献:https://docs.oracle.com/javase/tutorial/uiswing/layout/gridbag.html
qzwqbdag2#
有许多可能的解决方案,但最有用的可能是
GridBagLayout
,虽然复杂,但非常灵活。你甚至可以使用
anchor
要将组件移动到这些单元格中的不同位置。。。显然,这些约束也可以应用于单个组件,因此每个组件都可以有自己的约束集
查看如何使用gridbaglayout了解更多详细信息