3
我有一个网格作为我在JFrame中的输出,我试图弄清楚如何在网格和1,2,3等等的左边垂直显示文本,如A,B,C等。在上面。如何在GridLayout中显示文本?
这是我的输出: http://imgur.com/a/rDs2Y
,这是代码:
import java.util.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class battleShips extends JFrame{
/**
*
*/
private static final long serialVersionUID = 1L;
JButton applyButton = new JButton("New Game");
GridLayout experimentLayout = new GridLayout(0,6);
public battleShips(String name) {
super(name);
setResizable(false);
}
public void addComponentsToPane(final Container pane) {
final JPanel compsToExperiment = new JPanel();
compsToExperiment.setLayout(experimentLayout);
JPanel controls = new JPanel();
controls.setLayout(new GridLayout(2,3));
//Set up components preferred size
JButton b = new JButton("Just fake button");
Dimension buttonSize = b.getPreferredSize();
compsToExperiment.setPreferredSize(new Dimension((int)(buttonSize.getWidth() * 2.5)+5,
(int)(buttonSize.getHeight() * 3.5)+50*2));
//Add buttons to experiment with Grid Layout
for (int i = 0; i<36; i++)
{
compsToExperiment.add(new JButton("~"));
}
//Add controls to set up horizontal and vertical gaps
controls.add(applyButton);
//Process the Apply gaps button press
applyButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
//Set up the layout of the buttons
experimentLayout.layoutContainer(compsToExperiment);
}
});
pane.add(compsToExperiment, BorderLayout.NORTH);
pane.add(new JSeparator(), BorderLayout.CENTER);
pane.add(controls, BorderLayout.SOUTH);
}
private static void createAndShowGUI() {
//Create and set up the window.
battleShips frame = new battleShips("Battleships");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Set up the content pane.
frame.addComponentsToPane(frame.getContentPane());
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
/* Use an appropriate Look and Feel */
try {
//UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
} catch (UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
} catch (IllegalAccessException ex) {
ex.printStackTrace();
} catch (InstantiationException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
/* Turn off metal's use of bold fonts */
UIManager.put("swing.boldMetal", Boolean.FALSE);
//Schedule a job for the event dispatch thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
帮助将不胜感激!
完美的伴侣,干杯! – KingF
只是想知道,如果按下其中一个'〜'它会改变符号,你会如何做到这一点? – KingF
@KingF如果你更新你的视图,就可以更改'〜'的符号,我想你可以使用'repaint()'方法。你可以谷歌它或在这里搜索gridlayout摆动更新视图或类似的关键字,或问一个新的问题。 –