I'm trying to get scrollbars to work.
The code displays the images I choose. And I've just read (on stackoverflow) about adding the image to a panel, then the panel to the scrollpane, and the scrollpane to the frame. So I tried doing that.
But I still can't get the scrollbars to show. Even when the image is bigger than the JFrame window.
Can anyone help? I've tried revalidate, but it didn't work so I took it out.
import java.awt.*;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class MakeResizedImage {
private JFrame frame;
private JFileChooser fc;
private File file;
private int r;
private JTextField textField;
private Image img;
JScrollPane scrollPane;
ImagePanel panel_2;
public static void main(String[] args) {
MakeResizedImage MRI = new MakeResizedImage();
MRI.BuildJFrameGui();
}
private MakeResizedImage() {
}
private void BuildJFrameGui() {
JPanel panel = new JPanel();
panel.setLayout(null);
frame = new JFrame("View/Resize a png, jpg or gif image");
frame.setSize(400, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
JPanel panel_1 = new JPanel();
frame.getContentPane().add(panel_1, BorderLayout.NORTH);
JLabel lblNewLabel = new JLabel("Image:");
lblNewLabel.setHorizontalAlignment(SwingConstants.LEFT);
panel_1.add(lblNewLabel);
textField = new JTextField();
panel_1.add(textField);
textField.setColumns(10);
JLabel lblNewLabel_1 = new JLabel("Width:");
panel_1.add(lblNewLabel_1);
Dimension Dim = new Dimension(45, 20);
JSpinner spinner = new JSpinner();
spinner.setModel(new SpinnerNumberModel(new Integer(0), new Integer(0),
null, new Integer(1)));
spinner.setPreferredSize(Dim);
panel_1.add(spinner);
JLabel lblHeight = new JLabel("Height:");
panel_1.add(lblHeight);
JSpinner spinner_1 = new JSpinner();
spinner_1.setModel(new SpinnerNumberModel(new Integer(0),
new Integer(0), null, new Integer(1)));
spinner_1.setPreferredSize(Dim);
panel_1.add(spinner_1);
JPanel panel_3 = new JPanel();
JButton btnNewButton = new JButton("Open");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
chooseFile();
}
});
panel_3.add(btnNewButton);
JButton btnNewButton_1 = new JButton("Cancel");
btnNewButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.exit(0);
}
});
panel_3.add(btnNewButton_1);
JButton btnSave = new JButton("Save");
panel_3.add(btnSave);
frame.getContentPane().add(panel_3, BorderLayout.SOUTH);
scrollPane = new JScrollPane();
frame.getContentPane().add(scrollPane, BorderLayout.CENTER);
panel_2 = new ImagePanel();
scrollPane.setViewportView(panel_2);
frame.setVisible(true);
}
public void chooseFile() {
if (aFileChosen()) {
file = fc.getSelectedFile();
if (file.exists()) {
textField.setText(fc.getName());
try {
img = ImageIO.read(file);
panel_2.setImg(img);
} catch (IOException e) {
}
}
} else
JOptionPane.showMessageDialog(frame, "No file was chosen");
}
public boolean aFileChosen() {
fc = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter(
"PNG, JPG & GIF Images", "png", "jpg", "gif");
fc.setFileFilter(filter);
fc.setApproveButtonText("Choose");
fc.setApproveButtonToolTipText("Selects the image you want to resize");
r = fc.showOpenDialog(frame);
if (r == JFileChooser.APPROVE_OPTION)
return true;
return false;
}
class ImagePanel extends JPanel {
private static final long serialVersionUID = 1L;
private Image img;
ImagePanel() {
};
ImagePanel(Image img) {
this.img = img;
}
public void setImg(Image img) {
this.img = img;
repaint();
}
#Override
public Dimension getPreferredSize() {
return (new Dimension(300, 300));
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
// Clears the previously drawn image.
g.clearRect(0, 0, getWidth(), getHeight());
//and draws the new one...
g.drawImage(img, 0, 0, this);
}
}
}
Use the other constructor, the one that wraps another component: JScrollPane(Component).
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;
/**
* This Swing program demonstrates how to scroll a table row to visible area
* programmatically.
* #author www.codejava.net
*
*/
public class JTableRowScrollingExample extends JFrame implements ActionListener {
private JTable table = new JTable();
private JLabel label = new JLabel("Row number: ");
private JTextField fieldRowNumber = new JTextField(5);
private JButton buttonScroll = new JButton("Scroll to");
public JTableRowScrollingExample() {
super("JTable Row Scrolling Example");
String columnNames[] = {"No#", "Name", "Age", "Job"};
String[][] data = {
{"1", "John", "30", "Developer"},
{"2", "Jane", "31", "Designer"},
{"3", "Peter", "28", "Programmer"},
{"4", "Mary", "35", "Consultant"},
{"5", "Kim", "27", "Developer"},
{"6", "Geogre", "32", "Leader"},
{"7", "Dash", "36", "Analyst"},
{"8", "Tim", "25", "Designer"},
{"9", "Ana", "29", "Developer"},
{"10", "Tom", "41", "Manager"},
{"11", "Sam", "40", "Consultant"},
{"12", "Patrick", "38", "Manager"},
{"13", "Jeremy", "24", "Programmer"},
{"14", "David", "25", "Programmer"},
{"15", "Steve", "26", "Designer"},
};
DefaultTableModel model = new DefaultTableModel(data, columnNames);
table.setModel(model);
JScrollPane scrollpane = new JScrollPane(table);
scrollpane.setPreferredSize(new Dimension(300, 150));
add(scrollpane, BorderLayout.CENTER);
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout());
panel.add(label);
panel.add(fieldRowNumber);
panel.add(buttonScroll);
add(panel, BorderLayout.NORTH);
buttonScroll.addActionListener(this);
pack();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new JTableRowScrollingExample().setVisible(true);
}
});
}
#Override
public void actionPerformed(ActionEvent event) {
int rowNumber = Integer.parseInt(fieldRowNumber.getText());
Rectangle cellRect = table.getCellRect(rowNumber, 0, false);
System.out.println(cellRect);
table.scrollRectToVisible(cellRect);
}
}
Related
I use the method getSelectedRow() to get the index of the selected row in the first table. When I use it again to get the index of the selected row in the second table it still returns the index of the selected row in the first table. I can't figure out why!
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Selection extends JFrame {
int row;
String actualArray;
JPanel panel = new JPanel();
JPanel dialogPanel = new JPanel();
DefaultTableModel model1 = new DefaultTableModel();
DefaultTableModel model2 = new DefaultTableModel();
JTable table1 = new JTable(model1);
JTable table2 = new JTable(model2);
JScrollPane scrollPane1 = new JScrollPane(table1);
JScrollPane scrollPane2 = new JScrollPane(table2);
JButton showSelectedRow = new JButton("Show");
JButton switchTable = new JButton("switch");
JDialog dialog = new JDialog();
JLabel label = new JLabel();
String [] columns = {"ID","Name"};
String [][] array1 = {{"0001","Alice"},{"0002","Evanka"},{"0003","Steve"}};
String [][] array2 = {{"0004","David"},{"0005","Mario"},{"0006","Marry"}};
public Selection() {
createAndShowGUI();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Selection();
}
});
}
private void createAndShowGUI() {
model1.setDataVector(array1,columns);
model2.setDataVector(array2,columns);
panel.setBounds(15,20,500,480);
scrollPane1.setBounds(20,25,50,50);
scrollPane2.setBounds(20,25,50,50);
showSelectedRow.setBounds(40,160,60,25);
switchTable.setBounds(120,160,60,25);
actions();
panel.add(scrollPane1);
actualArray="array1";
panel.add(showSelectedRow);
panel.add(switchTable);
add(panel);
setSize(550, 500);
setLocation(230, 70);
setLayout(null);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
private void actions() {
showSelectedRow.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (actualArray.equals("array1")) {
row =table1.getSelectedRow();
} else {
row =table2.getSelectedRow();
}
showDialog();
}
});
switchTable.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (actualArray.equals("array1")) {
panel.removeAll();
panel.add(scrollPane1);
actualArray = "array2";
panel.add(showSelectedRow);
panel.add(switchTable);
add(panel);
repaint();
} else {
panel.removeAll();
panel.add(scrollPane2);
actualArray = "array1";
panel.add(showSelectedRow);
panel.add(switchTable);
add(panel);
repaint();
}
}
});
}
private void showDialog() {
dialogPanel.setBounds(5,5,50,30);
label.setText(String.valueOf(row));
label.setBounds(10,10,180,20);
dialogPanel.add(label);
dialog.add(dialogPanel);
dialog.setSize(60, 50);
dialog.setLocation(450, 250);
dialog.setLayout(null);
dialog.setResizable(false);
dialog.setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE);
dialog.setVisible(true);
}
}
I think your logic is backwards here...
When actualArray equals "array1", you're adding scrollPane1 and setting actualArray to "array2" ... shouldn't you be adding scrollPane2?
if (actualArray.equals("array1")) {
panel.removeAll();
panel.add(scrollPane1);
actualArray = "array2";
panel.add(showSelectedRow);
panel.add(switchTable);
add(panel);
repaint();
} else {
panel.removeAll();
panel.add(scrollPane2);
actualArray = "array1";
panel.add(showSelectedRow);
panel.add(switchTable);
add(panel);
repaint();
}
Having said that, I "accidentally" fixed you code trying to repair the null layout issues.
This example makes use of a CardLayout to switch between the tables instead...
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
public class FixMe extends JFrame {
int row;
String actualArray;
JPanel panel = new JPanel();
JPanel dialogPanel = new JPanel();
DefaultTableModel model1 = new DefaultTableModel();
DefaultTableModel model2 = new DefaultTableModel();
JTable table1 = new JTable(model1);
JTable table2 = new JTable(model2);
JScrollPane scrollPane1 = new JScrollPane(table1);
JScrollPane scrollPane2 = new JScrollPane(table2);
JButton showSelectedRow = new JButton("Show");
JButton switchTable = new JButton("switch");
JDialog dialog = new JDialog();
JLabel label = new JLabel();
String[] columns = {"ID", "Name"};
String[][] array1 = {{"0001", "Alice"}, {"0002", "Evanka"}, {"0003", "Steve"}};
String[][] array2 = {{"0004", "David"}, {"0005", "Mario"}, {"0006", "Marry"}};
public FixMe() {
createAndShowGUI();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new FixMe();
}
});
}
private CardLayout cardLayout;
private void createAndShowGUI() {
setLayout(new BorderLayout());
label.setBorder(new EmptyBorder(16, 16, 16, 16));
label.setHorizontalAlignment(JLabel.CENTER);
dialog.add(label);
cardLayout = new CardLayout();
panel.setLayout(cardLayout);
model1.setDataVector(array1, columns);
model2.setDataVector(array2, columns);
actions();
actualArray = "array1";
panel.add(scrollPane1, "array1");
panel.add(scrollPane2, "array2");
JPanel actions = new JPanel(new GridBagLayout());
actions.add(showSelectedRow);
actions.add(switchTable);
// panel.add(showSelectedRow);
// panel.add(switchTable);
add(panel);
add(actions, BorderLayout.SOUTH);
pack();
setLocationRelativeTo(null);
// setSize(550, 500);
// setLocation(230, 70);
// setLayout(null);
// setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
private void actions() {
showSelectedRow.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (actualArray.equals("array1")) {
row = table1.getSelectedRow();
} else {
row = table2.getSelectedRow();
}
showDialog();
}
});
switchTable.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (actualArray.equals("array1")) {
// panel.removeAll();
// panel.add(scrollPane1);
actualArray = "array2";
cardLayout.show(panel, actualArray);
// panel.add(showSelectedRow);
// panel.add(switchTable);
// add(panel);
// repaint();
} else {
// panel.removeAll();
// panel.add(scrollPane2);
actualArray = "array1";
cardLayout.show(panel, actualArray);
// panel.add(showSelectedRow);
// panel.add(switchTable);
// add(panel);
// repaint();
}
}
});
}
private void showDialog() {
label.setText(String.valueOf(row));
dialog.pack();
dialog.setLocationRelativeTo(panel);
dialog.setVisible(true);
// label.setBounds(10, 10, 180, 20);
// dialogPanel.add(label);
// dialog.add(dialogPanel);
// dialog.setSize(60, 50);
// dialog.setLocation(450, 250);
// dialog.setLayout(null);
// dialog.setResizable(false);
// dialog.setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE);
// dialog.setVisible(true);
}
}
I recommend having a read through of Laying Out Components Within a Container
Now, having said all that, I would recommend just switching the models...
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
String[] columns = {"ID", "Name"};
String[][] array1 = {{"0001", "Alice"}, {"0002", "Evanka"}, {"0003", "Steve"}};
String[][] array2 = {{"0004", "David"}, {"0005", "Mario"}, {"0006", "Marry"}};
TableModel model1 = new DefaultTableModel(array1, columns);
TableModel model2 = new DefaultTableModel(array2, columns);
JFrame frame = new JFrame();
frame.add(new TestPane(new TableModel[]{model1, model2}));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JTable table;
private TableModel[] models;
private int currentModel = 0;
private JLabel selectedRowLabel;
public TestPane(TableModel[] models) {
setLayout(new BorderLayout());
table = new JTable();
this.models = models;
table.setModel(models[0]);
setLayout(new BorderLayout());
add(new JScrollPane(table));
selectedRowLabel = new JLabel("...");
JButton switchButton = new JButton("Switch");
switchButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
currentModel += 1;
if (currentModel >= models.length) {
currentModel = 0;
}
table.setModel(models[currentModel]);
updateSelectionInformation();
}
});
JPanel infoPane = new JPanel(new GridBagLayout());
infoPane.add(switchButton);
infoPane.add(selectedRowLabel);
add(infoPane, BorderLayout.SOUTH);
table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent e) {
updateSelectionInformation();
}
});
}
protected void updateSelectionInformation() {
if (table.getSelectedRow() > -1) {
selectedRowLabel.setText(Integer.toString(table.getSelectedRow()));
} else {
selectedRowLabel.setText("---");
}
}
}
}
Now, if the previously selected row is important, simply keep track of it when you switch and re-apply it, for example...
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Arrays;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
String[] columns = {"ID", "Name"};
String[][] array1 = {{"0001", "Alice"}, {"0002", "Evanka"}, {"0003", "Steve"}};
String[][] array2 = {{"0004", "David"}, {"0005", "Mario"}, {"0006", "Marry"}};
TableModel model1 = new DefaultTableModel(array1, columns);
TableModel model2 = new DefaultTableModel(array2, columns);
JFrame frame = new JFrame();
frame.add(new TestPane(new TableModel[]{model1, model2}));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JTable table;
private TableModel[] models;
private int[] lastSelectedRow;
private int currentModel = 0;
private JLabel selectedRowLabel;
public TestPane(TableModel[] models) {
setLayout(new BorderLayout());
table = new JTable();
lastSelectedRow = new int[models.length];
Arrays.fill(lastSelectedRow, -1);
this.models = models;
table.setModel(models[0]);
setLayout(new BorderLayout());
add(new JScrollPane(table));
selectedRowLabel = new JLabel("...");
JButton switchButton = new JButton("Switch");
switchButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
lastSelectedRow[currentModel] = table.getSelectedRow();
currentModel += 1;
if (currentModel >= models.length) {
currentModel = 0;
}
table.setModel(models[currentModel]);
if (lastSelectedRow[currentModel] > -1) {
table.setRowSelectionInterval(lastSelectedRow[currentModel], lastSelectedRow[currentModel]);
}
updateSelectionInformation();
}
});
JPanel infoPane = new JPanel(new GridBagLayout());
infoPane.add(switchButton);
infoPane.add(selectedRowLabel);
add(infoPane, BorderLayout.SOUTH);
table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent e) {
updateSelectionInformation();
}
});
}
protected void updateSelectionInformation() {
if (table.getSelectedRow() > -1) {
selectedRowLabel.setText(Integer.toString(table.getSelectedRow()));
} else {
selectedRowLabel.setText("---");
}
}
}
}
I'm writing a GUI in java. I have a JXTable in which I currently only have static data, but I want allow the user to input data by using a template panel that I have created.
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.Window;
import java.awt.Dialog.ModalityType;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.border.TitledBorder;
import javax.swing.table.DefaultTableModel;
public class Template_StackOverflowExample extends JPanel{
private JPanel diagPanel = new dialogTemplate();
Object[] columnIdentifiers = {
"id",
"imei",
};
Object[][] data = {
{"1", "123"},
{"2", "123"},
{"3", "123"}
};
private JDialog dialog;
private static DefaultTableModel model;
public Template_StackOverflowExample(){
setLayout(new BorderLayout());
JPanel pane = new JPanel(new BorderLayout());
JButton addRow = new JButton("Add Row");
addRow.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
openRowPane("Add Row");
}
});
JButton editRow = new JButton("Edit Row");
editRow.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
openRowPane("Edit Row");
}
});
JPanel buttonPane = new JPanel(new GridLayout(0, 1));
TitledBorder buttonBorder = new TitledBorder("Buttons");
buttonPane.setBorder(buttonBorder);
buttonPane.add(addRow);
buttonPane.add(editRow);
model = new DefaultTableModel();
model.setColumnIdentifiers(columnIdentifiers);
JTable table = new JTable(model);
for(int i = 0; i < data.length; i++){
model.insertRow(i, data[i]);
}
JScrollPane scrollPane = new JScrollPane(table);
pane.add(buttonPane, BorderLayout.LINE_END);
pane.add(scrollPane, BorderLayout.CENTER);
add(pane, BorderLayout.CENTER);
}
public void openRowPane(String name){
if(dialog == null){
Window win = SwingUtilities.getWindowAncestor(this);
if(win != null){
dialog = new JDialog(win, name, ModalityType.APPLICATION_MODAL);
dialog.getContentPane().add(diagPanel);
dialog.pack();
dialog.setLocationRelativeTo(null);
}
}
dialog.setVisible(true);
}
public static void createAndShowGUI(){
JFrame frame = new JFrame("MCVE");
Template_StackOverflowExample mainPanel = new Template_StackOverflowExample();
frame.add(mainPanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
createAndShowGUI();
}
});
}
}
class dialogTemplate extends JPanel{
private JComponent[] content;
private String[] labelHeaders = {
"ID:",
"IMEI:",
};
public dialogTemplate(){
JPanel diagTemplate = new JPanel();
diagTemplate.setLayout(new BorderLayout());
JPanel rowContent = new JPanel(new GridLayout(0, 2));
JLabel idLabel = null;
JLabel imeiLabel = null;
JLabel[] labels = {
idLabel,
imeiLabel,
};
JTextField idTextField = new JTextField(20);
JTextField imeiTextField = new JTextField(20);
content = new JComponent[] {
idTextField,
imeiTextField,
};
for(int i = 0; i < labels.length; i++){
labels[i] = new JLabel(labelHeaders[i]);
rowContent.add(labels[i]);
rowContent.add(content[i]);
labels[i].setLabelFor(content[i]);
}
JButton save = new JButton("Save");
save.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
closeWindow();
}
});
JButton cancel = new JButton("Cancel");
cancel.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
closeWindow();
}
});
JPanel buttonPane = new JPanel(new GridLayout(0, 1, 5, 5));
buttonPane.add(save);
buttonPane.add(cancel);
buttonPane.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
diagTemplate.add(buttonPane, BorderLayout.PAGE_END);
diagTemplate.add(rowContent, BorderLayout.CENTER);
add(diagTemplate);
}
public void closeWindow(){
Window win = SwingUtilities.getWindowAncestor(this);
if(win != null) {
win.dispose();
}
}
}
As you might see both of the buttons in the pane creates the dialog that is created first ("Add Row" or "Edit Row"). I want them to create different dialogs so that the editing of data doesn't conflict with the addition of data.
Thanks in advance.
Assign a different dialog-creating method to each button so you can open two dialogs:
public void openRowPane(String name){
if(dialog == null){
Window win = SwingUtilities.getWindowAncestor(this);
//change modality
dialog = new JDialog(win, name, ModalityType.MODELESS);
dialog.getContentPane().add(diagPanel);
dialog.pack();
dialog.setLocationRelativeTo(null);
}
dialog.setVisible(true);
}
public void openRowPane2(String name){
if(dialog2 == null){
Window win = SwingUtilities.getWindowAncestor(this);
//change modality
dialog2 = new JDialog(win, name, ModalityType.MODELESS);
dialog2.getContentPane().add(diagPanel2);
dialog2.pack();
dialog2.setLocationRelativeTo(null);
}
dialog2.setVisible(true);
}
I'm trying to make a traffic light program, changing the foreground colour of JLabel from red to yellow to green, everytime I press JButton (i.e once i press JButton, JLabel turns red, then when i again press JButton it turns yellow and so on). But somehow the colour changes only once to red & nothing happens on further pressing JButton. Any kind of help would be appreciated. Thanks.
import java.awt.Color;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import java.awt.Font;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JTextField;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class traffic {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
traffic window = new traffic();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public traffic() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 798, 512);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel lblTrafficLight = new JLabel("Traffic Light");
lblTrafficLight.setFont(new Font("Tahoma", Font.BOLD, 40));
lblTrafficLight.setHorizontalAlignment(SwingConstants.CENTER);
lblTrafficLight.setBounds(190, 11, 403, 61);
frame.getContentPane().add(lblTrafficLight);
JLabel lblRed = new JLabel("RED");
lblRed.setHorizontalAlignment(SwingConstants.CENTER);
lblRed.setFont(new Font("Tahoma", Font.PLAIN, 40));
lblRed.setBounds(273, 125, 249, 61);
frame.getContentPane().add(lblRed);
JButton btnButton = new JButton("Button");
btnButton.setActionCommand("B");
btnButton.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
if(btnButton.getActionCommand().equals("B"))
{
lblRed.setForeground(Color.RED);
}
if(btnButton.getActionCommand().equals("B"))
{
lblRed.setForeground(Color.YELLOW);
}
if(btnButton.getActionCommand().equals("B"))
{
lblRed.setForeground(Color.GREEN);
}
if(btnButton.getActionCommand().equals("B"))
{
lblRed.setForeground(Color.YELLOW);
}
if(btnButton.getActionCommand().equals("B"))
{
lblRed.setForeground(Color.RED);
}
}
});
btnButton.setBounds(353, 346, 89, 23);
frame.getContentPane().add(btnButton);
}
}
You're using the same actionCommand, B for each if block, and so all of the blocks will always run, and the last block will be the one seen.
e.g.,
int x = 1;
if (x == 1) {
// do something
}
if (x == 1) {
// do something else
}
all blocks will be done!
Either change the actionCommands used, or don't use actionCommand String but rather an incrementing int index. Also, don't use MouseListeners for JButtons but rather ActionListeners.
For example:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.util.HashMap;
import java.util.Map;
import javax.swing.*;
public class Traffic2 extends JPanel {
private static final int PREF_W = 400;
private static final int PREF_H = 300;
private static final String[] STRINGS = {"Red", "Blue", "Orange", "Yellow", "Green", "Cyan"};
private Map<String, Color> stringColorMap = new HashMap<>();
private JLabel label = new JLabel("", SwingConstants.CENTER);
private int index = 0;
public Traffic2() {
stringColorMap.put("Red", Color.red);
stringColorMap.put("Blue", Color.blue);
stringColorMap.put("Orange", Color.orange);
stringColorMap.put("Yellow", Color.YELLOW);
stringColorMap.put("Green", Color.GREEN);
stringColorMap.put("Cyan", Color.CYAN);
label.setFont(label.getFont().deriveFont(Font.BOLD, 40f));
String key = STRINGS[index];
label.setText(key);
label.setForeground(stringColorMap.get(key));
JPanel centerPanel = new JPanel(new GridBagLayout());
centerPanel.add(label);
JPanel topPanel = new JPanel();
topPanel.add(new JButton(new AbstractAction("Change Color") {
#Override
public void actionPerformed(ActionEvent e) {
index++;
index %= STRINGS.length;
String key = STRINGS[index];
label.setText(key);
label.setForeground(stringColorMap.get(key));
}
}));
setLayout(new BorderLayout());
add(topPanel, BorderLayout.PAGE_START);
add(centerPanel, BorderLayout.CENTER);
}
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
private static void createAndShowGui() {
Traffic2 mainPanel = new Traffic2();
JFrame frame = new JFrame("Traffic2");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
In this program, I am trying to select images from users using filechooser and then displaying those images. By default I added 2 images. When I add more images it doesn't display?
Below is my entire code
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import java.awt.FlowLayout;
import java.io.File;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
public class CLayout {
JFrame frame = new JFrame("CardLayout demo");
JPanel panelCont = new JPanel();
LoginView log = new LoginView();
JPanel Img = new ImageGallery();
CardLayout cl = new CardLayout();
public CLayout() {
panelCont.setLayout(cl);
log.setLayout(new BoxLayout(log, BoxLayout.PAGE_AXIS));
Img.setLayout(new BoxLayout(Img, BoxLayout.PAGE_AXIS));
panelCont.add(log, "1");
panelCont.add(Img, "2");
cl.show(panelCont, "1");
ActionListener loginListener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String userName = log.getUserName();
char[] password = log.getPassword();
String pass=new String(password);
if (LoginView.LOGIN.equals(e.getActionCommand())) {
if(userName.equals("imagegallery")&& pass.equals("12345"))
cl.show(panelCont, "2");
}
}
};
log.addActionListener(loginListener);
frame.add(panelCont);
frame.setSize(800,600);
frame.setTitle(" Image Gallery ");
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new CLayout();
}
});
}
}
class ImageGallery extends JPanel {
private ImageIcon myImage1 = new ImageIcon ("Chrysanthemum.jpg");
private ImageIcon myImage2 = new ImageIcon ("Desert.jpg");
JPanel ImageGallery = new JPanel();
private ImageIcon[] myImages =new ImageIcon[10];
private int curImageIndex=0;
private int count=0;
private int total=1;
public ImageGallery () {
ImageGallery.add(new JLabel (myImage1));
myImages[0]=myImage1;
myImages[1]=myImage2;
add(ImageGallery, BorderLayout.CENTER);
JButton PREVIOUS = new JButton ("Previous");
JButton NEXT = new JButton ("Next");
JDialog.setDefaultLookAndFeelDecorated(true);
JButton button = new JButton("Select File");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
JFileChooser fileChooser = new JFileChooser();
int returnValue = fileChooser.showOpenDialog(null);
if (returnValue == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
System.out.println(selectedFile.getName().toString());
ImageIcon tImage=new ImageIcon("selectedFile.getName().toString()");
System.out.println(myImages.length);
int n=2+count;
myImages[n]=tImage;
total=total+count+1;
count++;
System.out.println(total+" "+count);
}
}
});
JPanel Menu = new JPanel();
Menu.setLayout(new GridLayout(1,3));
add(Menu, BorderLayout.NORTH);
Menu.add(PREVIOUS);
Menu.add(NEXT);
Menu.add(button);
//register listener
PreviousButtonListener PreviousButton = new PreviousButtonListener ();
NextButtonListener NextButton = new NextButtonListener ();
//add listeners to corresponding componenets
PREVIOUS.addActionListener(PreviousButton);
NEXT.addActionListener(NextButton);
}
class PreviousButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
if(curImageIndex>0 && curImageIndex <=total) {
ImageGallery.remove(0);
curImageIndex=curImageIndex-1;
ImageIcon TheImage= myImages[curImageIndex];
ImageGallery.add(new JLabel (TheImage));
ImageGallery.validate();
ImageGallery.repaint();
} else {
ImageGallery.remove(0);
ImageGallery.add(new JLabel (myImage1));
curImageIndex=0;
ImageGallery.validate();
ImageGallery.repaint();
}
}
}
class NextButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
if(curImageIndex>=0 && curImageIndex <total){
ImageGallery.remove(0);
curImageIndex = curImageIndex + 1;
ImageIcon TheImage= myImages[curImageIndex];
ImageGallery.add(new JLabel (TheImage));
ImageGallery.validate();
ImageGallery.repaint();
} else {
ImageGallery.remove(0);
ImageGallery.add(new JLabel (myImages[total]));
curImageIndex=total ;
ImageGallery.validate();
ImageGallery.repaint();
}
}
}
}
class LoginView extends JPanel {
JLabel userLabel = new JLabel("User");
JTextField userText = new JTextField(20);
JLabel passwordLabel = new JLabel("Password");
JPasswordField passwordText = new JPasswordField(20);
private final JButton loginButton;
private final JButton registerButton;
public static final String LOGIN = "Login";
public static final String REGISTER = "Regster";
public LoginView() {
setLayout(new GridLayout(0, 2));
userLabel.setBounds(10, 10, 80, 25);
add(userLabel);
userText.setBounds(10, 10, 60, 25);
add(userText);
passwordLabel.setBounds(10, 40, 80, 25);
add(passwordLabel);
passwordText.setBounds(100, 40, 160, 25);
add(passwordText);
loginButton = new JButton("login");
loginButton.setActionCommand(LOGIN);
registerButton = new JButton("register");
registerButton.setActionCommand(REGISTER);
add(loginButton);
}
public void addActionListener(ActionListener listener) {
loginButton.addActionListener(listener);
registerButton.addActionListener(listener);
}
public String getUserName() {
return userText.getText();
}
public char[] getPassword() {
return passwordText.getPassword();
}
}
Problem is in this line
ImageIcon tImage=new ImageIcon("selectedFile.getName().toString()");
you need to remove double-quotes in order to read actual file name.
ImageIcon tImage=new ImageIcon(selectedFile.getName().toString());
Hope this helps.
I have set a background image on a JPanel but when i try to add buttons and selects to the custom background panel the buttons are hidden until i move the mouse over the buttons. I have included the code snippets below.
Below is my customized JPanel
package au.com.tankwarz.view.custompanels;
import java.awt.Color;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import javax.swing.JPanel;
public class BackgroundPanel extends JPanel
{
/**
*
*/
private static final long serialVersionUID = 1659728640545162103L;
public BackgroundPanel()
{
}
#Override
public void paintComponent(final Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g;
g2d.drawImage(loadBackgroundImage(), 0, 0, this);
g2d.dispose();
}
private static BufferedImage loadBackgroundImage()
{
BufferedImage bi = new BufferedImage(800, 600, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = bi.createGraphics();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
// Paint a gradient from top to bottom
GradientPaint gp = new GradientPaint( 0, 0, Color.BLACK, 0, 600, new Color(0, 0, 255).darker( ).darker() );
g2d.setPaint( gp );
g2d.fillRect( 0, 0, 800, 600 );
g2d.dispose();
return bi;
}
}
And here is where i try to use it to display the panel with the buttons on it.
package au.com.tankwarz.view;
import java.awt.event.ActionListener;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import org.jdesktop.application.Application;
import au.com.tankwarz.view.custompanels.BackgroundPanel;
import com.cloudgarden.layout.AnchorConstraint;
import com.cloudgarden.layout.AnchorLayout;
public class NewGamePanel extends BackgroundPanel {
/**
*
*/
private static final long serialVersionUID = 1L;
private JLabel numberOfPlayersLable;
private JComboBox numberOfPlayersCB;
private JButton cancelButton;
private JButton createPlayersButton;
private JComboBox numberOfTanksCB;
private JLabel numberOfTanksLable;
private JComboBox numberOfRoundsCB;
private JLabel numberOfRounds;
public static final String[] numberOfPlayersCBValues = new String[] { "Two", "Three", "Four" };
public static final String[] numberOfRoundsCBValues = new String[] { "One", "Two", "Three", "Four" };
public static final String[] numberOfTanksCBValues = new String[] { "One", "Two", "Three", "Four" };
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
//new NewGamePanel();
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new NewGamePanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public NewGamePanel() {
super();
initGUI();
}
private void initGUI() {
try {
AnchorLayout thisLayout = new AnchorLayout();
this.setLayout(thisLayout);
this.setPreferredSize(new java.awt.Dimension(800, 600));
this.setSize(800, 600);
this.setOpaque(true);
this.setName("this");
{
numberOfPlayersLable = new JLabel();
this.add(numberOfPlayersLable, new AnchorConstraint(144, 320, 201, 77, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL));
numberOfPlayersLable.setName("numberOfPlayersLable");
numberOfPlayersLable.setPreferredSize(new java.awt.Dimension(60, 40));
}
{
ComboBoxModel numberOfPlayersCBModel =
new DefaultComboBoxModel(numberOfPlayersCBValues);
numberOfPlayersCB = new JComboBox();
this.add(numberOfPlayersCB, new AnchorConstraint(125, 697, 219, 386, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL));
numberOfPlayersCB.setModel(numberOfPlayersCBModel);
numberOfPlayersCB.setPreferredSize(new java.awt.Dimension(60, 40));
}
{
numberOfRounds = new JLabel();
this.add(numberOfRounds, new AnchorConstraint(298, 371, 355, 77, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL));
numberOfRounds.setName("numberOfRounds");
numberOfRounds.setPreferredSize(new java.awt.Dimension(60, 40));
}
{
ComboBoxModel numberOfRoundsCBModel =
new DefaultComboBoxModel(numberOfRoundsCBValues);
numberOfRoundsCB = new JComboBox();
this.add(numberOfRoundsCB, new AnchorConstraint(283, 697, 366, 386, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL));
numberOfRoundsCB.setModel(numberOfRoundsCBModel);
numberOfRoundsCB.setName("numberOfRoundsCB");
numberOfRoundsCB.setPreferredSize(new java.awt.Dimension(60, 40));
}
{
numberOfTanksLable = new JLabel();
this.add(numberOfTanksLable, new AnchorConstraint(453, 320, 509, 77, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL));
numberOfTanksLable.setName("numberOfTanksLable");
numberOfTanksLable.setPreferredSize(new java.awt.Dimension(60, 40));
}
{
ComboBoxModel numberOfTanksCBModel =
new DefaultComboBoxModel(numberOfTanksCBValues);
numberOfTanksCB = new JComboBox();
this.add(numberOfTanksCB, new AnchorConstraint(437, 697, 520, 386, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL));
numberOfTanksCB.setModel(numberOfTanksCBModel);
numberOfTanksCB.setPreferredSize(new java.awt.Dimension(60, 40));
}
{
createPlayersButton = new JButton();
this.add(createPlayersButton, new AnchorConstraint(795, 758, 878, 511, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL));
createPlayersButton.setName("createPlayersButton");
createPlayersButton.setPreferredSize(new java.awt.Dimension(99, 25));
}
{
cancelButton = new JButton();
this.add(cancelButton, new AnchorConstraint(795, 248, 878, 128, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL));
cancelButton.setName("cancelButton");
cancelButton.setPreferredSize(new java.awt.Dimension(48, 25));
}
Application.getInstance().getContext().getResourceMap(getClass()).injectComponents(this);
} catch (Exception e) {
e.printStackTrace();
}
}
public void setCreatePlayersButtonActionListener(ActionListener actionListener)
{
createPlayersButton.addActionListener(actionListener);
}
public void setCancelButtonActionListener(ActionListener actionListener)
{
cancelButton.addActionListener(actionListener);
}
public JComboBox getNumberOfPlayersCB()
{
return numberOfPlayersCB;
}
public void setNumberOfPlayersCB(JComboBox numberOfPlayersCB)
{
this.numberOfPlayersCB = numberOfPlayersCB;
}
public JComboBox getNumberOfTanksCB()
{
return numberOfTanksCB;
}
public void setNumberOfTanksCB(JComboBox numberOfTanksCB)
{
this.numberOfTanksCB = numberOfTanksCB;
}
public JComboBox getNumberOfRoundsCB()
{
return numberOfRoundsCB;
}
public void setNumberOfRoundsCB(JComboBox numberOfRoundsCB)
{
this.numberOfRoundsCB = numberOfRoundsCB;
}
}
Any help would be appreciate as i have been struggling with this for a while.
Don't change the state of the component from within any paintXxx method, this could cause a repaint event to be triggered, repeating the process until your CPU is running hot.
Never change the opacity state of the component from within any paintXxx, this will cause a cascading series of repaint's as Swing suddenly starts trying to figure out what components are now visible behind the current one...
Don't dispose of a Graphics context you didn't create, doing so could prevent what ever you paint after it not to be rendered on some systems.
Try not to create the background image on each paint cycle, this is not only expensive from memory point of view, but also expensive from a time point of view
I'm not sure why you flipping the opacity state, you don't really want it to be transparent. Simply call super.paintComponent to prepare the graphics state and then draw your image on top.
You should also avoid using setPreferredSize, see Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing? for more details...
Just illustrate the point, this is what you code produces (after I corrected the paint issues)
This is what my test code produces
Updated with test code
import com.apple.eawt.Application;
import java.awt.Color;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.RenderingHints;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class BackgroundPanel extends JPanel {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
//new NewGamePanel();
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new NewGamePanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public BackgroundPanel() {
}
private static BufferedImage bi;
#Override
public void paintComponent(final Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.drawImage(loadBackgroundImage(), 0, 0, this);
g2d.dispose();
}
private static BufferedImage loadBackgroundImage() {
if (bi == null) {
bi = new BufferedImage(800, 600, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = bi.createGraphics();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
// Paint a gradient from top to bottom
GradientPaint gp = new GradientPaint(0, 0, Color.BLACK, 0, 600, new Color(0, 0, 255).darker().darker());
g2d.setPaint(gp);
g2d.fillRect(0, 0, 800, 600);
g2d.dispose();
}
return bi;
}
public static class NewGamePanel extends BackgroundPanel {
/**
*
*/
private static final long serialVersionUID = 1L;
private JLabel numberOfPlayersLable;
private JComboBox numberOfPlayersCB;
private JButton cancelButton;
private JButton createPlayersButton;
private JComboBox numberOfTanksCB;
private JLabel numberOfTanksLable;
private JComboBox numberOfRoundsCB;
private JLabel numberOfRounds;
public static final String[] numberOfPlayersCBValues = new String[]{"Two", "Three", "Four"};
public static final String[] numberOfRoundsCBValues = new String[]{"One", "Two", "Three", "Four"};
public static final String[] numberOfTanksCBValues = new String[]{"One", "Two", "Three", "Four"};
public NewGamePanel() {
super();
initGUI();
}
private void initGUI() {
try {
GridBagLayout thisLayout = new GridBagLayout();
this.setLayout(thisLayout);
this.setPreferredSize(new java.awt.Dimension(800, 600));
this.setSize(800, 600);
this.setOpaque(true);
this.setName("this");
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = gbc.REMAINDER;
{
numberOfPlayersLable = new JLabel();
this.add(numberOfPlayersLable, gbc);
numberOfPlayersLable.setName("numberOfPlayersLable");
}
{
ComboBoxModel numberOfPlayersCBModel
= new DefaultComboBoxModel(numberOfPlayersCBValues);
numberOfPlayersCB = new JComboBox();
this.add(numberOfPlayersCB, gbc);
numberOfPlayersCB.setModel(numberOfPlayersCBModel);
}
{
numberOfRounds = new JLabel();
this.add(numberOfRounds, gbc);
numberOfRounds.setName("numberOfRounds");
}
{
ComboBoxModel numberOfRoundsCBModel
= new DefaultComboBoxModel(numberOfRoundsCBValues);
numberOfRoundsCB = new JComboBox();
this.add(numberOfRoundsCB, gbc);
numberOfRoundsCB.setModel(numberOfRoundsCBModel);
numberOfRoundsCB.setName("numberOfRoundsCB");
}
{
numberOfTanksLable = new JLabel();
this.add(numberOfTanksLable, gbc);
numberOfTanksLable.setName("numberOfTanksLable");
}
{
ComboBoxModel numberOfTanksCBModel
= new DefaultComboBoxModel(numberOfTanksCBValues);
numberOfTanksCB = new JComboBox();
this.add(numberOfTanksCB, gbc);
numberOfTanksCB.setModel(numberOfTanksCBModel);
}
{
createPlayersButton = new JButton();
this.add(createPlayersButton, gbc);
createPlayersButton.setName("createPlayersButton");
}
{
cancelButton = new JButton();
this.add(cancelButton, gbc);
cancelButton.setName("cancelButton");
}
// Application.getInstance().getContext().getResourceMap(getClass()).injectComponents(this);
} catch (Exception e) {
e.printStackTrace();
}
}
public void setCreatePlayersButtonActionListener(ActionListener actionListener) {
createPlayersButton.addActionListener(actionListener);
}
public void setCancelButtonActionListener(ActionListener actionListener) {
cancelButton.addActionListener(actionListener);
}
public JComboBox getNumberOfPlayersCB() {
return numberOfPlayersCB;
}
public void setNumberOfPlayersCB(JComboBox numberOfPlayersCB) {
this.numberOfPlayersCB = numberOfPlayersCB;
}
public JComboBox getNumberOfTanksCB() {
return numberOfTanksCB;
}
public void setNumberOfTanksCB(JComboBox numberOfTanksCB) {
this.numberOfTanksCB = numberOfTanksCB;
}
public JComboBox getNumberOfRoundsCB() {
return numberOfRoundsCB;
}
public void setNumberOfRoundsCB(JComboBox numberOfRoundsCB) {
this.numberOfRoundsCB = numberOfRoundsCB;
}
}
}