我正在尝试向我的GUI添加一个滑块,但它不会显示,我是java的新手,所以如果你能提供帮助,我将不胜感激!我不确定如何将滑块添加到主网格中,此时它不会出现。
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.io.*;
import javax.swing.*;
public class Grid extends JFrame
{
public void Slider()
{
setLayout(new FlowLayout());
JSlider slider;
JLabel label;
slider = new JSlider(JSlider.VERTICAL, 0, 20, 0);
slider.setMajorTickSpacing(5);
slider.setPaintTicks(true);
add(slider);
label = new JLabel ("Number of lifeforms: 0");
add(label);
}
public static void main (String args[])
{
JFrame Grid = new JFrame();
Grid.setSize(800,600);
Grid.setTitle("Artificial life simulator");
Grid.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
String rows = JOptionPane.showInputDialog("How many rows does the grid have?");
int row = Integer.parseInt(rows);
String columns = JOptionPane.showInputDialog("How many columns does the grid have?");
int col = Integer.parseInt(columns);
JOptionPane.showConfirmDialog(null, "Are these the correct demensions: "
+row+" x "+col+ "?",
"Yes or No", JOptionPane.YES_NO_OPTION);
Container pane = Grid.getContentPane();
pane.setLayout(new GridLayout(row,col));
Color square;
for (int x = 1; x <=(row*col); x++)
{
int altr = 0;
altr = (x-1) % col;
altr += (x-1) / col;
if (altr % 2 == 0)
{
square = Color.white;
}
else
{
square = Color.black;
}
JPanel panel = new JPanel();
panel.setPreferredSize(new Dimension(800/row, 600/col));
panel.setBackground(square);
pane.add(panel);
}
Grid.setVisible(true);
} }
答案 0 :(得分:2)
请注意您的示例的一些更改:
JFrame
的默认布局为BorerLayout
;垂直滑块在EAST
中运行良好。
slider()
方法返回JSlider
;标签可以进入其余三个BorerLayout
区域之一。
覆盖getPreferredSize()
以定义渲染窗格的大小。
TODO:另见Initial Threads。
经测试:
import java.awt.*;
import javax.swing.*;
public class Grid extends JFrame {
private static JSlider slider() {
JSlider slider;
slider = new JSlider(JSlider.VERTICAL, 0, 20, 0);
slider.setMajorTickSpacing(5);
slider.setPaintTicks(true);
return slider;
}
public static void main(String args[]) {
JFrame grid = new JFrame();
grid.setSize(800, 600);
grid.setTitle("Artificial life simulator");
grid.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
int row = 3;
int col = 3;
JPanel pane = new JPanel(){
@Override
public Dimension getPreferredSize() {
return new Dimension(320, 240);
}
};
pane.setLayout(new GridLayout(row, col));
Color square;
for (int x = 1; x <= (row * col); x++) {
int altr = 0;
altr = (x - 1) % col;
altr += (x - 1) / col;
if (altr % 2 == 0) {
square = Color.white;
} else {
square = Color.black;
}
JPanel panel = new JPanel(new GridLayout());
panel.setBackground(square);
pane.add(panel);
}
grid.add(pane);
grid.add(slider(), BorderLayout.EAST);
grid.pack();
grid.setVisible(true);
}
}