在我的代码中,我将所有内容都显示在一行中。我希望列中的button1,button2,button3,button4和label1以及另一个中的两个。
有人可以帮我吗?我认为javax.swing.ButtonGroup可以完成这项工作但是当我在Internet上搜索示例时,我发现只有复杂的代码......
import java.awt.Color;
import java.awt.Container;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class RadioButtonV3 extends JFrame{
private static final long serialVersionUID = 1L;
public static void main(String[] args)
{
new RadioButtonV3();
}
public RadioButtonV3()
{
EventQueue.invokeLater
(
new Runnable()
{
@Override
public void run() {
try
{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex)
{
}
Container c = getContentPane();
c.setLayout(new FlowLayout());
final JPanel panel = new JPanel();
final JRadioButton button1 = new JRadioButton("option 1");
final JRadioButton button2 = new JRadioButton("option 2");
final JRadioButton button3 = new JRadioButton("option 3");
final JRadioButton button4 = new JRadioButton("option 4");
String s = "this text will be deleted in -> public void actionPerformed(ActionEvent e)";
JLabel label1 = new JLabel(s, JLabel.CENTER);
JLabel label2 = new JLabel(s, JLabel.CENTER);
label1.setFont(new Font("DigifaceWide Regular", Font.PLAIN, 20));
label2.setFont(new Font("DigifaceWide Regular", Font.PLAIN, 20));
Timer t = new Timer
(
500, new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
Double rand = Math.random();
label1.setText(rand.toString());
if (rand < 0.3) {
label1.setForeground(Color.RED);
}
else if (rand < 0.6) {
label1.setForeground(Color.GRAY);
}
else {
label1.setForeground(Color.GREEN);
}
rand = Math.random();
label2.setText(rand.toString());
if (rand < 0.3) {
label2.setForeground(Color.RED);
}
else if (rand < 0.6) {
label2.setForeground(Color.GRAY);
}
else {
label2.setForeground(Color.GREEN);
}
}
}
);
t.setRepeats(true);
t.start();
panel.add(button1);
panel.add(button2);
panel.add(button3);
panel.add(button4);
panel.add(label1);
panel.add(label2);
JOptionPane.showMessageDialog(null, panel, "title", JOptionPane.INFORMATION_MESSAGE);
t.stop();
}
}
);
}
}
答案 0 :(得分:0)
试试这个
更改您的代码
Container c = getContentPane();
c.setLayout(new FlowLayout());
final JPanel panel = new JPanel();
panel.setLayout(new GridLayout(2,1));
final JPanel panel1 = new JPanel();
final JPanel panel2 = new JPanel();
panel.add(panel1);
panel.add(panel2);
然后到最后
panel1.add(button1);
panel1.add(button2);
panel1.add(button3);
panel1.add(button4);
panel2.add(label1);
panel2.add(label2);