Dynamically replacing a panel of buttons - java

This is my first trial in java Swing. The issue am having is recreating the calendar panel every time the month changes. I would like to have the panelRightDown repopulated when addMonth is called (when > or < is clicked). I have tried calling revalidate, invalidate, repaint in addMonth but everything just goes haywire. The same methods ought to be implemented while calculating the year. Any help would be appreciated. More so, a better approach to this is highly welcome.
public class Gui extends JFrame {
private final int windowWidth = 700;
private final int windowHeight = 600;
private final Container container;
private final JPanel panelLeft = new JPanel();
private final JPanel panelRight = new JPanel();
private final GridBagConstraints gridBagConstraints = new GridBagConstraints();
private final int verticalSpacerSize = 8;
private final int horizontalSpacerSize = 15;
private Border lowerEtchedBorder =
BorderFactory.createEtchedBorder(EtchedBorder.LOWERED);
// -----
protected boolean controlsOnTop;
protected boolean removeOnDaySelection;
protected Calendar currentDisplayDate;
protected JButton prevMonth;
protected JButton nextMonth;
protected JButton prevYear;
protected JButton nextYear;
protected JTextField textField;
protected List<ActionListener> popupListeners =
new ArrayList<ActionListener>();
protected Popup popup;
protected SimpleDateFormat dayName = new SimpleDateFormat("d");
protected SimpleDateFormat monthName = new SimpleDateFormat("MMMM");
protected String iconFile = "datepicker.gif";
protected String[] weekdayNames =
{"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
JPanel datePanel = new JPanel();
JPanel panelRightDown = new JPanel();
JPanel controlsPanel;
// -----
// Constructor to setup the GUI components and event handlers
public Gui() {
//-----
currentDisplayDate = Calendar.getInstance();
controlsOnTop = true;
removeOnDaySelection = true;
//createPanel();
// Retrieve the content-pane of the top-level container JFrame
// All operations done on the content-pane
container = getContentPane();
container.setLayout(new BorderLayout());
//container.setMinimumSize(new Dimension(windowWidth, windowHeight));
createMenuBar();
createStatusBar();
JPanel fullPane = new JPanel();
fullPane.setLayout(new GridBagLayout());
// Spacer
container.add(Box.createVerticalStrut(
4), BorderLayout.NORTH);
container.add(fullPane, BorderLayout.CENTER);
fullPane.setMinimumSize(new Dimension(windowWidth, windowHeight));
// Position Left and Right panels
gridBagConstraints.fill = GridBagConstraints.BOTH;
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.weightx = 0.3;
gridBagConstraints.weighty = 1.0;
fullPane.add(panelLeft, gridBagConstraints);
gridBagConstraints.gridx = 1;
gridBagConstraints.weightx = 0;
fullPane.add(Box.createHorizontalStrut(
15), gridBagConstraints);
gridBagConstraints.fill = GridBagConstraints.BOTH;
gridBagConstraints.gridx = 2;
gridBagConstraints.weightx = 0.9;
fullPane.add(panelRight, gridBagConstraints);
configurePanelLeft(panelLeft);
configurePanelRight(panelRight);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Prod - Reminder");
setSize(windowWidth, windowHeight);
setLocationRelativeTo(null);
setVisible(true);
addWindowListener(new Terminator());
}
public void setDate(String date) {
currentDisplayDate = Calendar.getInstance();
editDate(date);
}
public void setDate(Calendar date) {
currentDisplayDate = date;
//createPanel();
validate();
repaint();
}
public void setDate(int month, int day, int year) {
currentDisplayDate = Calendar.getInstance();
currentDisplayDate.set(expandYear(year), month - 1, day);
//createPanel();
validate();
repaint();
}
protected int expandYear(int year) {
if (year < 100) { // 2 digit year
int currentYear = Calendar.getInstance().get(Calendar.YEAR);
int current2DigitYear = currentYear % 100;
int currentCentury = currentYear / 100 * 100;
// set 2 digit year range +20 / -80 from current year
int high2DigitYear = (current2DigitYear + 20) % 100;
if (year <= high2DigitYear) {
year += currentCentury;
}
else {
year += (currentCentury - 100);
}
}
return year;
}
public void setControlsOnTop(boolean flag) {
controlsOnTop = flag;
//createPanel();
repaint();
}
public Calendar getCalendarDate() {
return currentDisplayDate;
}
public Date getDate() {
return currentDisplayDate.getTime();
}
public String getFormattedDate() {
return Integer.toString(getMonth()) + "/" +
Integer.toString(getDay()) + "/" +
Integer.toString(getYear());
}
public int getMonth() {
return currentDisplayDate.get(Calendar.MONTH) + 1;
}
public int getDay() {
return currentDisplayDate.get(Calendar.DAY_OF_MONTH);
}
public int getYear() {
return currentDisplayDate.get(Calendar.YEAR);
}
protected JPanel createControls() {
JPanel c = new JPanel();
c.setBorder(BorderFactory.createRaisedBevelBorder());
c.setFocusable(true);
c.setLayout(new FlowLayout(FlowLayout.CENTER));
prevYear = new JButton("<<");
c.add(prevYear);
prevYear.setMargin(new Insets(0,0,0,0));
prevYear.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
addYear(-1);
}
});
prevMonth = new JButton("<");
c.add(prevMonth);
prevMonth.setMargin(new Insets(0,0,0,0));
prevMonth.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
addMonth(-1);
}
});
textField = new JTextField(getFormattedDate(), 10);
c.add(textField);
textField.setEditable(true);
textField.setEnabled(true);
textField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
editDate(textField.getText());
}
});
nextMonth = new JButton(">");
c.add(nextMonth);
nextMonth.setMargin(new Insets(0,0,0,0));
nextMonth.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
addMonth(+1);
}
});
nextYear = new JButton(">>");
c.add(nextYear);
nextYear.setMargin(new Insets(0,0,0,0));
nextYear.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
addYear(+1);
}
});
return c;
}
protected JPanel configureDatePicker() {
GridBagLayout gridbag = new GridBagLayout();
GridBagConstraints c = new GridBagConstraints();
datePanel.setFocusable(true);
datePanel.setLayout(gridbag);
String month = monthName.format(currentDisplayDate.getTime());
String year = Integer.toString(getYear());
c.gridx = 0;
c.gridy = 0;
c.gridwidth = 7;
c.gridheight = 1;
JLabel title = new JLabel(month + " " + year);
datePanel.add(title, c);
Font font = title.getFont();
// Font titleFont = new Font(font.getName(), font.getStyle(),
// font.getSize() + 2);
Font weekFont = new Font(font.getName(), font.getStyle(),
font.getSize() - 2);
title.setFont(font);
c.gridy = 1;
c.weightx = 0.1;
c.weighty = 0.1;
c.gridwidth = 1;
c.gridheight = 1;
c.fill = GridBagConstraints.BOTH;
for (c.gridx = 0; c.gridx < 7; c.gridx++) {
JLabel label = new JLabel(
weekdayNames[c.gridx], SwingConstants.CENTER);
datePanel.add(label, c);
label.setFont(weekFont);
}
Calendar draw = (Calendar) currentDisplayDate.clone();
draw.set(Calendar.DATE, 1);
draw.add(Calendar.DATE, -draw.get(Calendar.DAY_OF_WEEK) + 1);
int monthInt = currentDisplayDate.get(Calendar.MONTH);
// monthInt = 0;
// System.out.println("Current month: " + monthInt);
c.gridwidth = 1;
c.gridheight = 1;
int width = getFontMetrics(weekFont).stringWidth(" Wed ");
int width1 = getFontMetrics(weekFont).stringWidth("Wed");
int height = getFontMetrics(weekFont).getHeight() +
(width - width1);
for (c.gridy = 2; c.gridy < 8; c.gridy++) {
for (c.gridx = 0; c.gridx < 7; c.gridx++) {
JButton dayButton;
// System.out.print("Draw month: " + draw.get(Calendar.MONTH));
if (draw.get(Calendar.MONTH) == monthInt) {
String dayString = dayName.format(draw.getTime());
if (draw.get(Calendar.DAY_OF_MONTH) < 10) {
dayString = " " + dayString;
}
dayButton = new JButton(dayString);
} else {
dayButton = new JButton();
dayButton.setEnabled(false);
}
// System.out.println(", day: " + dayName.format(draw.getTime()));
datePanel.add(dayButton, c);
Color color = dayButton.getBackground();
if ((draw.get(Calendar.DAY_OF_MONTH) == getDay()) &&
(draw.get(Calendar.MONTH) == monthInt)) {
dayButton.setBackground(Color.yellow);
// dayButton.setFocusPainted(true);
// dayButton.setSelected(true);
} else
dayButton.setBackground(color);
dayButton.setFont(weekFont);
dayButton.setFocusable(true);
//dayButton.setPreferredSize(new Dimension(width, height));
//dayButton.setMargin(new Insets(0,0,0,0));
dayButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
changeDay(e.getActionCommand());
}
});
//if (dateChange != null)
// dayButton.addActionListener(dateChange);
draw.add(Calendar.DATE, +1);
}
// if (draw.get(Calendar.MONTH) != monthInt) break;
}
return datePanel;
}
public void addMonth(int month) {
currentDisplayDate.add(Calendar.MONTH, month);
datePanel.invalidate();
controlsPanel.invalidate();
panelRightDown.validate();
datePanel = configureDatePicker();
controlsPanel = createControls();
panelRightDown.removeAll();
panelRightDown.add(controlsPanel);
panelRightDown.add(datePanel);
validate();
repaint();
}
public void addYear(int year) {
currentDisplayDate.add(Calendar.YEAR, year);
validate();
repaint();
}
public void editDate(String date) {
parseDate(date);
//createPanel();
validate();
repaint();
}
protected void parseDate(String date) {
String[] parts = date.split("/");
switch (parts.length) {
case 3:
currentDisplayDate.set(Calendar.MONTH,
Integer.valueOf(parts[0]) - 1);
currentDisplayDate.set(Calendar.DAY_OF_MONTH,
Integer.valueOf(parts[1]));
currentDisplayDate.set(Calendar.YEAR,
expandYear(Integer.valueOf(parts[2])));
break;
case 2:
currentDisplayDate = Calendar.getInstance();
currentDisplayDate.set(Calendar.MONTH,
Integer.valueOf(parts[0]) - 1);
currentDisplayDate.set(Calendar.DAY_OF_MONTH,
Integer.valueOf(parts[1]));
break;
default:
// invalid date
currentDisplayDate = Calendar.getInstance();
break;
}
}
public void changeDay(String day) {
currentDisplayDate.set(Calendar.DAY_OF_MONTH,
Integer.valueOf(day.trim()));
textField.setText(getFormattedDate());
if (!removeOnDaySelection) {
//createPanel();
//validate();
repaint();
}
}
private void createMenuBar() {
JMenuBar menubar = new JMenuBar();
JMenu file = new JMenu("File");
file.setMnemonic(KeyEvent.VK_F);
JMenuItem eMenuItem = new JMenuItem("Exit");
eMenuItem.setMnemonic(KeyEvent.VK_E);
eMenuItem.setToolTipText("Exit application");
eMenuItem.addActionListener((ActionEvent event) -> {
System.exit(0);
});
file.add(eMenuItem);
menubar.add(file);
setJMenuBar(menubar);
}
private void createStatusBar() {
// create the status bar panel and shove it down the bottom of the frame
JPanel statusPanel = new JPanel();
statusPanel.setBorder(new BevelBorder(BevelBorder.LOWERED));
container.add(statusPanel, BorderLayout.SOUTH);
statusPanel.setPreferredSize(new Dimension(container.getWidth(), 20));
statusPanel.setLayout(new BoxLayout(statusPanel, BoxLayout.X_AXIS));
JLabel statusLabel = new JLabel("status");
statusLabel.setHorizontalAlignment(SwingConstants.LEFT);
statusPanel.add(statusLabel);
}
public void configurePanelLeft(JPanel panel) {
// Configure Left-side panels
// Top panel
gridBagConstraints.fill = GridBagConstraints.BOTH;
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.weightx = 0.3;
gridBagConstraints.weighty = 0.3;
JPanel panelLeftTop = new JPanel();
panelLeftTop.setBorder(
BorderFactory.createMatteBorder(1, 1, 1, 1, Color.YELLOW));
panel.setLayout(new GridBagLayout());
panel.add(panelLeftTop, gridBagConstraints);
// Display Area
JTextArea displayItem = new JTextArea("Hello, left top!");
displayItem.setBorder(lowerEtchedBorder);
displayItem.setLineWrap(true);
displayItem.setBackground(panel.getBackground());
displayItem.setWrapStyleWord(true);
//displayItem.setEditable(false);
panelLeftTop.setLayout(new BorderLayout());
JScrollPane topScrollPane = new JScrollPane();
topScrollPane.getVerticalScrollBar().setUnitIncrement(3);
topScrollPane.setViewportView(displayItem);
topScrollPane.setHorizontalScrollBarPolicy(
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
panelLeftTop.add(topScrollPane);
// Spacer
gridBagConstraints.fill = GridBagConstraints.BOTH;
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 0;
panel.add(Box.createVerticalStrut(
verticalSpacerSize), gridBagConstraints);
// Bottom panel
gridBagConstraints.fill = GridBagConstraints.BOTH;
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 0.7;
JPanel panelLeftDown = new JPanel();
panelLeftDown.setBorder(
BorderFactory.createMatteBorder(1, 1, 1, 1, Color.BLUE));
panelLeftDown.setLayout(new GridBagLayout());
for (int i = 0; i < 50; i++) {
gridBagConstraints.fill = GridBagConstraints.BOTH;
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = i;
gridBagConstraints.weightx = 0.3;
//gridBagConstraints.weighty = 1.0;
String textValue = "Area: "+ i
+" This is a very long wrapped text, "
+ "which I expect to be an example of text in a label. "
+ "I really hope it works well."
+ "The Scroll Bar comes when your text goes beyond "
+ "the bounds of your view area. "
+ "Don't use Absolute Positioning, for such a small "
+ "talk at hand, always prefer Layout Managers, "
+ "do read the first para of the first link, "
+ "to know the advantage of using a Layout Manager.";
JTextArea textArea = new JTextArea(textValue);
textArea.setBorder(lowerEtchedBorder);
textArea.setLineWrap(true);
textArea.setBackground(panel.getBackground());
textArea.setWrapStyleWord(true);
textArea.setEditable(false);
textArea.addMouseListener(new MouseListener() {
#Override
public void mouseClicked(MouseEvent e) {
displayItem.setText(textValue);
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
topScrollPane.getVerticalScrollBar().setValue(0);
}
});
}
#Override
public void mousePressed(MouseEvent e) {
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
#Override
public void mouseReleased(MouseEvent e) {
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
#Override
public void mouseEntered(MouseEvent e) {
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
#Override
public void mouseExited(MouseEvent e) {
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
});
panelLeftDown.add(textArea, gridBagConstraints);
}
JScrollPane scrollPane = new JScrollPane(panelLeftDown,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
panelLeftDown.setAutoscrolls(true);
scrollPane.setPreferredSize(new Dimension(300,800));
scrollPane.getVerticalScrollBar().setUnitIncrement(3);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
scrollPane.getVerticalScrollBar().setValue(0);
}
});
panel.add(scrollPane, gridBagConstraints);
}
public void configurePanelRight(JPanel panel) {
// Configure right-side panels
// Top panel
gridBagConstraints.fill = GridBagConstraints.BOTH;
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 0.1;
JPanel panelRightTop = new JPanel();
panelRightTop.setBorder(
BorderFactory.createMatteBorder(1, 1, 1, 1, Color.YELLOW));
panelRightTop.add(new JLabel("Hello, right top!"));
panel.setLayout(new GridBagLayout());
panel.add(panelRightTop, gridBagConstraints);
// Spacer
gridBagConstraints.fill = GridBagConstraints.BOTH;
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 0;
panel.add(Box.createVerticalStrut(
verticalSpacerSize), gridBagConstraints);
// Bottom panel
gridBagConstraints.fill = GridBagConstraints.BOTH;
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 0.9;
panelRightDown.setBorder(
BorderFactory.createMatteBorder(1, 1, 1, 1, Color.BLUE));
//panelRightDown.add(new JLabel("Hello, right down!"));
panel.add(panelRightDown, gridBagConstraints);
panel.add(panelRightDown, gridBagConstraints);
// Date Picker
gridBagConstraints.fill = GridBagConstraints.BOTH;
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 0.1;
panelRightDown.setLayout(new BorderLayout());
datePanel = configureDatePicker();
controlsPanel = createControls();
panelRightDown.add(controlsPanel, BorderLayout.NORTH);
panelRightDown.add(datePanel, BorderLayout.CENTER);
}
private ListCellRenderer<? super String> getRenderer() {
return new DefaultListCellRenderer(){
#Override
public Component getListCellRendererComponent(JList<?> list,
Object value, int index, boolean isSelected,
boolean cellHasFocus) {
JLabel listCellRendererComponent =
(JLabel) super.getListCellRendererComponent(
list, value, index, isSelected,cellHasFocus);
listCellRendererComponent.setBorder(
lowerEtchedBorder);
listCellRendererComponent.setEnabled(true);
return listCellRendererComponent;
}
};
}
public static void main(String[] args) {
// Run the GUI construction in the Event-Dispatching thread for thread-safety
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Gui(); // Let the constructor do the job
}
});
}
}

Related

Transform my Java Swing program to an MVC program?

I was given the task to come up with a small game in Swing and implement it as an MVC (Model View Control) program. I'm new to MVC. So far I've finished the whole program in 1 Java file (View), what code do I need to change and insert in the Model file, in order for it to become MVC?
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Arrays;
public class MemoryGameView extends JFrame {
private JPanel gamePanel, settingsPanel, scorePanel;
private JButton[] button = new JButton[16];
private JButton start;
private JPanel buttonPanel, buttonPanel2;
private JPanel difficultyPanel, difficultyPanel2;
private JLabel difficultyLabel;
private ButtonGroup difficultyButtonGroup;
private JRadioButton[] difficultyButton = new JRadioButton[4];
private int difficulty = 0;
private JComboBox guiColorChanger;
private String[] guiColor = new String[2];
private JPanel guiColorChangerPanel;
private JLabel guiColorChangerLabel;
private JPanel currentScorePanel, currentScorePanel2, highScorePanel, highScorePanel2;
private JLabel currentScoreLabel, currentScoreLabel2, highScoreLabel, highScoreLabel2;
private int currentScore;
private int highScore = 0;
private int[] arrayAuto;
private int[] arrayUser;
private int counter;
private Timer timer;
private Color babyBlue = new Color(137, 156, 240);
private Color brightRed = new Color(255, 69, 0);
private Color limeGreen = new Color(50, 205, 50);
private Color whiteBlue = new Color(240, 240, 255);
private Color blackBlue = new Color(0, 0, 15);
public MemoryGameView() {
super();
init();
}
public void init() {
setTitle("Memory Game - by Marc");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(1200, 500);
setLocationRelativeTo(null);
setLayout(new GridLayout(1, 3));
settingsPanel = new JPanel(new BorderLayout());
gamePanel = new JPanel(new GridBagLayout());
scorePanel = new JPanel(new BorderLayout());
settingsPanel.setBackground(whiteBlue);
gamePanel.setBackground(Color.WHITE);
scorePanel.setBackground(whiteBlue);
add(settingsPanel);
add(gamePanel);
add(scorePanel);
//GAME PANEL (CENTER) -----------------------------------------------------------------------------------------------------
//GAME GRID PANEL:
buttonPanel = new JPanel(new GridLayout(4, 4, 4, 4));
for (int x = 0; x < 16; x++) {
button[x] = new JButton();
button[x].setBackground(babyBlue);
button[x].setEnabled(false);
button[x].addActionListener(new AttemptMemoryGame());
button[x].setActionCommand(x + "");
buttonPanel.add(button[x]);
}
buttonPanel2 = new JPanel();
buttonPanel2.setBackground(Color.WHITE);
buttonPanel2.setPreferredSize(new Dimension(320, 320));
buttonPanel.setPreferredSize(new Dimension(312, 312));
buttonPanel2.add(buttonPanel);
GridBagConstraints buttonGBC = new GridBagConstraints();
buttonGBC.gridy = 0;
buttonGBC.insets = new Insets(10, 10, 0, 10);
gamePanel.add(buttonPanel2, buttonGBC);
//START BUTTON:
start = new JButton("START");
start.setBackground(Color.ORANGE);
start.setPreferredSize(new Dimension(200, 40));
GridBagConstraints startGBC = new GridBagConstraints();
startGBC.gridy = 1;
startGBC.insets.top = 20;
startGBC.insets.bottom = 20;
gamePanel.add(start, startGBC);
start.addActionListener(new CreateMemoryGame());
timer = new Timer(750, new TimerListener());
//SETTINGS PANEL (LEFT) ----------------------------------------------------------------------------------------------
//GUI COLOR PANEL:
guiColor[0] = "Light";
guiColor[1] = "Dark";
guiColorChangerPanel = new JPanel(new GridBagLayout());
guiColorChangerPanel.setBackground(whiteBlue);
settingsPanel.add(guiColorChangerPanel, BorderLayout.NORTH);
guiColorChanger = new JComboBox(guiColor);
guiColorChanger.setBackground(Color.WHITE);
guiColorChanger.setPreferredSize(new Dimension(200, 30));
guiColorChanger.setBorder(BorderFactory.createLineBorder(Color.BLACK));
GridBagConstraints guiColorChangerGBC = new GridBagConstraints();
guiColorChangerGBC.gridy = 1;
guiColorChangerGBC.insets = new Insets(0, 20, 0, 50);
guiColorChangerGBC.anchor = GridBagConstraints.WEST;
guiColorChangerPanel.add(guiColorChanger, guiColorChangerGBC);
guiColorChangerLabel = new JLabel("GUI Color Mode:");
GridBagConstraints guiColorChangerLabelGBC = new GridBagConstraints();
guiColorChangerLabelGBC.gridy = 0;
guiColorChangerLabelGBC.insets = new Insets(30, 20, 5, 0);
guiColorChangerLabelGBC.anchor = GridBagConstraints.WEST;
guiColorChangerPanel.add(guiColorChangerLabel, guiColorChangerLabelGBC);
guiColorChanger.addActionListener(new ChangeColorsGUI());
guiColorChanger.setFocusable(false);
//GAME DIFFICULTY PANEL:
difficultyPanel2 = new JPanel(new GridBagLayout());
difficultyPanel2.setBackground(whiteBlue);
settingsPanel.add(difficultyPanel2, BorderLayout.SOUTH);
difficultyLabel = new JLabel("Difficulty:");
GridBagConstraints difficultyLabelGBC = new GridBagConstraints();
difficultyLabelGBC.gridy = 0;
difficultyLabelGBC.insets = new Insets(30, 0, 5, 50);
difficultyLabelGBC.anchor = GridBagConstraints.WEST;
difficultyPanel2.add(difficultyLabel, difficultyLabelGBC);
difficultyPanel = new JPanel(new GridBagLayout());
difficultyPanel.setBackground(Color.WHITE);
difficultyPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
GridBagConstraints difficultyPanelGBC = new GridBagConstraints();
difficultyPanelGBC.gridy = 1;
difficultyPanelGBC.insets = new Insets(0, 0, 75, 100);
difficultyPanel2.add(difficultyPanel, difficultyPanelGBC);
GridBagConstraints difficultyGBC = new GridBagConstraints();
difficultyGBC.insets = new Insets(5, 5, 5, 5);
difficultyGBC.anchor = GridBagConstraints.WEST;
difficultyButton[0] = new JRadioButton("Easy [3]");
difficultyButton[1] = new JRadioButton("Normal [5]");
difficultyButton[2] = new JRadioButton("Hard [7]");
difficultyButton[3] = new JRadioButton("Impossible [9]");
difficultyButtonGroup = new ButtonGroup();
for (int x = 0; x < 4; x++) {
difficultyButton[x].setBackground(Color.WHITE);
difficultyButton[x].setActionCommand(x + "");
difficultyGBC.gridy = x;
difficultyPanel.add(difficultyButton[x], difficultyGBC);
difficultyButtonGroup.add(difficultyButton[x]);
difficultyButton[x].addActionListener(new SelectDifficulty());
}
//SCORE PANEL (RIGHT) --------------------------------------------------------------------------------------------------------
//CURRENT SCORE:
currentScorePanel2 = new JPanel(new GridBagLayout());
currentScorePanel2.setBackground(whiteBlue);
scorePanel.add(currentScorePanel2, BorderLayout.NORTH);
currentScoreLabel2 = new JLabel("Score: ");
GridBagConstraints currentScoreLabelGBC = new GridBagConstraints();
currentScoreLabelGBC.gridx = 0;
currentScoreLabelGBC.insets = new Insets(5, 5, 5, 5);
currentScoreLabelGBC.anchor = GridBagConstraints.WEST;
currentScorePanel2.add(currentScoreLabel2, currentScoreLabelGBC);
currentScorePanel = new JPanel(new GridBagLayout());
currentScorePanel.setBackground(Color.WHITE);
currentScorePanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
GridBagConstraints currentScorePanelGBC = new GridBagConstraints();
currentScorePanelGBC.insets = new Insets(100, 0, 100, 100);
currentScorePanelGBC.anchor = GridBagConstraints.WEST;
currentScorePanel2.add(currentScorePanel, currentScorePanelGBC);
currentScoreLabel = new JLabel(" ");
currentScoreLabelGBC.gridx = 1;
currentScorePanel.add(currentScoreLabel, currentScoreLabelGBC);
//HIGHSCORE:
highScorePanel2 = new JPanel(new GridBagLayout());
highScorePanel2.setBackground(whiteBlue);
scorePanel.add(highScorePanel2, BorderLayout.SOUTH);
highScoreLabel2 = new JLabel("Highscore: ");
GridBagConstraints highScoreLabelGBC = new GridBagConstraints();
highScoreLabelGBC.gridx = 0;
highScoreLabelGBC.insets = new Insets(5, 5, 5, 5);
highScoreLabelGBC.anchor = GridBagConstraints.WEST;
highScorePanel2.add(highScoreLabel2, highScoreLabelGBC);
highScorePanel = new JPanel(new GridBagLayout());
highScorePanel.setBackground(Color.WHITE);
highScorePanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
GridBagConstraints highScorePanelGBC = new GridBagConstraints();
highScorePanelGBC.insets = new Insets(100, 0, 100, 100);
highScorePanelGBC.anchor = GridBagConstraints.WEST;
highScorePanel2.add(highScorePanel, highScorePanelGBC);
highScoreLabel = new JLabel(" ");
highScoreLabelGBC.gridx = 1;
highScorePanel.add(highScoreLabel, highScoreLabelGBC);
pack();
setVisible(true);
}
public class CreateMemoryGame implements ActionListener {
#Override
public void actionPerformed(ActionEvent ae) {
if (difficulty != 0) {
counter = 0;
for (JRadioButton rb: difficultyButton) {
rb.setEnabled(false);
}
for (JButton b: button) {
b.setBackground(babyBlue);
b.setEnabled(false);
}
start.setEnabled(false);
arrayAuto = new int[difficulty];
arrayAuto[0] = (int)(Math.random() * 16);
for (int x = 1; x < difficulty; x++) {
arrayAuto[x] = (int)(Math.random() * 16);
while (arrayAuto[x] == arrayAuto[x - 1]) {
arrayAuto[x] = (int)(Math.random() * 16);
}
}
arrayUser = Arrays.copyOf(arrayAuto, arrayAuto.length);
button[arrayAuto[0]].setBackground(limeGreen);
timer.start();
} else {
Object[] options = {"OK"};
JOptionPane.showOptionDialog(null, "Please select a Difficulty.", "ERROR", JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE,
null,
options,
options[0]);
}
}
}
public class TimerListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent ae) {
button[arrayAuto[0]].setBackground(babyBlue);
arrayAuto = Arrays.copyOfRange(arrayAuto, 1, arrayAuto.length);
if (arrayAuto.length == 0) {
timer.stop();
for (JButton b: button) {
b.setEnabled(true);
}
} else {
button[arrayAuto[0]].setBackground(limeGreen);
}
}
}
public class AttemptMemoryGame implements ActionListener {
#Override
public void actionPerformed(ActionEvent ae) {
if (Integer.parseInt(ae.getActionCommand()) == arrayUser[counter]) {
if (counter != 0) {
button[arrayUser[counter - 1]].setBackground(babyBlue);
}
button[arrayUser[counter]].setBackground(limeGreen);
counter++;
currentScore += difficulty;
currentScoreLabel.setText(" " + currentScore + " ");
} else {
if (currentScore > highScore) {
highScore = currentScore;
highScoreLabel.setText(" " + highScore + " ");
}
currentScore = 0;
currentScoreLabel.setText(" ");
for (int x = 0; x < difficulty; x++) {
button[arrayUser[x]].setBackground(brightRed);
}
start.setEnabled(true);
for (JRadioButton rb: difficultyButton) {
rb.setEnabled(true);
}
for (JButton b: button) {
b.setEnabled(false);
}
}
if (counter == arrayUser.length) {
start.setEnabled(true);
for (int x = 0; x < counter - 1; x++) {
button[arrayUser[x]].setBackground(limeGreen);
}
for (JButton b: button) {
b.setEnabled(false);
}
for (JRadioButton rb: difficultyButton) {
rb.setEnabled(true);
}
}
}
}
public class SelectDifficulty implements ActionListener {
#Override
public void actionPerformed(ActionEvent ae) {
if (ae.getActionCommand().equals(0 + "")) {
difficulty = 3;
} else if (ae.getActionCommand().equals(2 + "")) {
difficulty = 7;
} else if (ae.getActionCommand().equals(3 + "")) {
difficulty = 9;
} else {
difficulty = 5;
}
}
}
public class ChangeColorsGUI implements ActionListener {
#Override
public void actionPerformed(ActionEvent ae) {
if (guiColorChanger.getSelectedItem() == guiColor[0]) {
guiColorChanger.setBackground(Color.WHITE);
settingsPanel.setBackground(whiteBlue);
gamePanel.setBackground(Color.WHITE);
scorePanel.setBackground(whiteBlue);
buttonPanel.setBackground(Color.WHITE);
guiColorChangerPanel.setBackground(whiteBlue);
buttonPanel2.setBackground(Color.WHITE);
guiColorChanger.setForeground(Color.BLACK);
guiColorChangerLabel.setForeground(Color.BLACK);
difficultyPanel.setBackground(Color.WHITE);
for (JRadioButton rb: difficultyButton) {
rb.setBackground(Color.WHITE);
rb.setForeground(Color.BLACK);
}
difficultyLabel.setBackground(whiteBlue);
difficultyLabel.setForeground(Color.BLACK);
difficultyPanel2.setBackground(whiteBlue);
guiColorChanger.setBorder(BorderFactory.createLineBorder(Color.BLACK));
difficultyPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
scorePanel.setBackground(whiteBlue);
currentScoreLabel.setBackground(Color.WHITE);
currentScoreLabel.setForeground(Color.BLACK);
currentScoreLabel2.setForeground(Color.BLACK);
currentScorePanel.setBackground(whiteBlue);
currentScorePanel2.setBackground(whiteBlue);
currentScorePanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
highScoreLabel.setBackground(Color.WHITE);
highScoreLabel.setForeground(Color.BLACK);
highScoreLabel2.setForeground(Color.BLACK);
highScorePanel.setBackground(whiteBlue);
highScorePanel2.setBackground(whiteBlue);
highScorePanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
} else {
guiColorChanger.setBackground(Color.BLACK);
settingsPanel.setBackground(blackBlue);
gamePanel.setBackground(Color.BLACK);
scorePanel.setBackground(blackBlue);
buttonPanel.setBackground(Color.BLACK);
guiColorChangerPanel.setBackground(blackBlue);
buttonPanel2.setBackground(Color.BLACK);
guiColorChanger.setForeground(Color.WHITE);
guiColorChangerLabel.setForeground(Color.WHITE);
difficultyPanel.setBackground(Color.BLACK);
for (JRadioButton rb: difficultyButton) {
rb.setBackground(Color.BLACK);
rb.setForeground(Color.WHITE);
}
difficultyLabel.setBackground(blackBlue);
difficultyLabel.setForeground(Color.WHITE);
difficultyPanel2.setBackground(blackBlue);
guiColorChanger.setBorder(BorderFactory.createLineBorder(Color.WHITE));
difficultyPanel.setBorder(BorderFactory.createLineBorder(Color.WHITE));
scorePanel.setBackground(blackBlue);
currentScoreLabel.setBackground(Color.BLACK);
currentScoreLabel.setForeground(Color.WHITE);
currentScoreLabel2.setForeground(Color.WHITE);
currentScorePanel.setBackground(blackBlue);
currentScorePanel2.setBackground(blackBlue);
currentScorePanel.setBorder(BorderFactory.createLineBorder(Color.WHITE));
highScoreLabel.setBackground(Color.BLACK);
highScoreLabel.setForeground(Color.WHITE);
highScoreLabel2.setForeground(Color.WHITE);
highScorePanel.setBackground(blackBlue);
highScorePanel2.setBackground(blackBlue);
highScorePanel.setBorder(BorderFactory.createLineBorder(Color.WHITE));
}
}
}
public static void main(String[] args) {
new MemoryGameView();
}
}
I really appreciate any help! (#camickr? :D)
Edit: I only need to do the files Model and View, no Controller needed.
Here is something to get you started. Define a a Model class that holds the information and logic the View needs.
In this simple demo I implemented a model that has only one attribute the View needs namely difficulty :
class Model{
private int difficulty = 0; //why not set a default value ?
Model(){
}
int getDifficulty() {
return difficulty;
}
void setDifficulty(int difficulty) {
this.difficulty = difficulty;
}
}
Now introduce a View class which is almost identical to MemoryGameView with one important difference: it has an instance of Model and uses it.
(Another difference is a design preference and not a must: unlike MemoryGameView it has a JFrame and it does not extend one.):
class View {
private JPanel gamePanel, settingsPanel, scorePanel;
private final JButton[] button = new JButton[16];
private JButton start;
private JPanel buttonPanel, buttonPanel2;
private JPanel difficultyPanel, difficultyPanel2;
private JLabel difficultyLabel;
private ButtonGroup difficultyButtonGroup;
private final JRadioButton[] difficultyButton = new JRadioButton[4];
private JComboBox guiColorChanger;
private final String[] guiColor = new String[2];
private JPanel guiColorChangerPanel;
private JLabel guiColorChangerLabel;
private JPanel currentScorePanel, currentScorePanel2, highScorePanel, highScorePanel2;
private JLabel currentScoreLabel, currentScoreLabel2, highScoreLabel, highScoreLabel2;
private int currentScore;
private int highScore = 0;
private int[] arrayAuto,arrayUser;
private int counter;
private Timer timer;
private final Color babyBlue = new Color(137, 156, 240);
private final Color brightRed = new Color(255, 69, 0);
private final Color limeGreen = new Color(50, 205, 50);
private final Color whiteBlue = new Color(240, 240, 255);
private final Color blackBlue = new Color(0, 0, 15);
private final Model model;
public View(Model model) {
this.model = model;
init();
}
public void init() {
JFrame frame = new JFrame("Memory Game - by Marc");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(1200, 500);
frame.setLocationRelativeTo(null);
frame.setLayout(new GridLayout(1, 3));
settingsPanel = new JPanel(new BorderLayout());
gamePanel = new JPanel(new GridBagLayout());
scorePanel = new JPanel(new BorderLayout());
settingsPanel.setBackground(whiteBlue);
gamePanel.setBackground(Color.WHITE);
scorePanel.setBackground(whiteBlue);
frame.add(settingsPanel);
frame.add(gamePanel);
frame.add(scorePanel);
//GAME PANEL (CENTER) -----------------------------------------------------------------------------------------------------
//GAME GRID PANEL:
buttonPanel = new JPanel(new GridLayout(4, 4, 4, 4));
for (int x = 0; x < 16; x++) {
button[x] = new JButton();
button[x].setBackground(babyBlue);
button[x].setEnabled(false);
button[x].addActionListener(new AttemptMemoryGame());
button[x].setActionCommand(x + "");
buttonPanel.add(button[x]);
}
buttonPanel2 = new JPanel();
buttonPanel2.setBackground(Color.WHITE);
buttonPanel2.setPreferredSize(new Dimension(320, 320));
buttonPanel.setPreferredSize(new Dimension(312, 312));
buttonPanel2.add(buttonPanel);
GridBagConstraints buttonGBC = new GridBagConstraints();
buttonGBC.gridy = 0;
buttonGBC.insets = new Insets(10, 10, 0, 10);
gamePanel.add(buttonPanel2, buttonGBC);
//START BUTTON:
start = new JButton("START");
start.setBackground(Color.ORANGE);
start.setPreferredSize(new Dimension(200, 40));
GridBagConstraints startGBC = new GridBagConstraints();
startGBC.gridy = 1;
startGBC.insets.top = 20;
startGBC.insets.bottom = 20;
gamePanel.add(start, startGBC);
start.addActionListener(new CreateMemoryGame());
timer = new Timer(750, new TimerListener());
//SETTINGS PANEL (LEFT) ----------------------------------------------------------------------------------------------
//GUI COLOR PANEL:
guiColor[0] = "Light";
guiColor[1] = "Dark";
guiColorChangerPanel = new JPanel(new GridBagLayout());
guiColorChangerPanel.setBackground(whiteBlue);
settingsPanel.add(guiColorChangerPanel, BorderLayout.NORTH);
guiColorChanger = new JComboBox(guiColor);
guiColorChanger.setBackground(Color.WHITE);
guiColorChanger.setPreferredSize(new Dimension(200, 30));
guiColorChanger.setBorder(BorderFactory.createLineBorder(Color.BLACK));
GridBagConstraints guiColorChangerGBC = new GridBagConstraints();
guiColorChangerGBC.gridy = 1;
guiColorChangerGBC.insets = new Insets(0, 20, 0, 50);
guiColorChangerGBC.anchor = GridBagConstraints.WEST;
guiColorChangerPanel.add(guiColorChanger, guiColorChangerGBC);
guiColorChangerLabel = new JLabel("GUI Color Mode:");
GridBagConstraints guiColorChangerLabelGBC = new GridBagConstraints();
guiColorChangerLabelGBC.gridy = 0;
guiColorChangerLabelGBC.insets = new Insets(30, 20, 5, 0);
guiColorChangerLabelGBC.anchor = GridBagConstraints.WEST;
guiColorChangerPanel.add(guiColorChangerLabel, guiColorChangerLabelGBC);
guiColorChanger.addActionListener(new ChangeColorsGUI());
guiColorChanger.setFocusable(false);
//GAME DIFFICULTY PANEL:
difficultyPanel2 = new JPanel(new GridBagLayout());
difficultyPanel2.setBackground(whiteBlue);
settingsPanel.add(difficultyPanel2, BorderLayout.SOUTH);
difficultyLabel = new JLabel("Difficulty:");
GridBagConstraints difficultyLabelGBC = new GridBagConstraints();
difficultyLabelGBC.gridy = 0;
difficultyLabelGBC.insets = new Insets(30, 0, 5, 50);
difficultyLabelGBC.anchor = GridBagConstraints.WEST;
difficultyPanel2.add(difficultyLabel, difficultyLabelGBC);
difficultyPanel = new JPanel(new GridBagLayout());
difficultyPanel.setBackground(Color.WHITE);
difficultyPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
GridBagConstraints difficultyPanelGBC = new GridBagConstraints();
difficultyPanelGBC.gridy = 1;
difficultyPanelGBC.insets = new Insets(0, 0, 75, 100);
difficultyPanel2.add(difficultyPanel, difficultyPanelGBC);
GridBagConstraints difficultyGBC = new GridBagConstraints();
difficultyGBC.insets = new Insets(5, 5, 5, 5);
difficultyGBC.anchor = GridBagConstraints.WEST;
difficultyButton[0] = new JRadioButton("Easy [3]");
difficultyButton[1] = new JRadioButton("Normal [5]");
difficultyButton[2] = new JRadioButton("Hard [7]");
difficultyButton[3] = new JRadioButton("Impossible [9]");
difficultyButtonGroup = new ButtonGroup();
for (int x = 0; x < 4; x++) {
difficultyButton[x].setBackground(Color.WHITE);
difficultyButton[x].setActionCommand(x + "");
difficultyGBC.gridy = x;
difficultyPanel.add(difficultyButton[x], difficultyGBC);
difficultyButtonGroup.add(difficultyButton[x]);
difficultyButton[x].addActionListener(new SelectDifficulty());
}
//SCORE PANEL (RIGHT) --------------------------------------------------------------------------------------------------------
//CURRENT SCORE:
currentScorePanel2 = new JPanel(new GridBagLayout());
currentScorePanel2.setBackground(whiteBlue);
scorePanel.add(currentScorePanel2, BorderLayout.NORTH);
currentScoreLabel2 = new JLabel("Score: ");
GridBagConstraints currentScoreLabelGBC = new GridBagConstraints();
currentScoreLabelGBC.gridx = 0;
currentScoreLabelGBC.insets = new Insets(5, 5, 5, 5);
currentScoreLabelGBC.anchor = GridBagConstraints.WEST;
currentScorePanel2.add(currentScoreLabel2, currentScoreLabelGBC);
currentScorePanel = new JPanel(new GridBagLayout());
currentScorePanel.setBackground(Color.WHITE);
currentScorePanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
GridBagConstraints currentScorePanelGBC = new GridBagConstraints();
currentScorePanelGBC.insets = new Insets(100, 0, 100, 100);
currentScorePanelGBC.anchor = GridBagConstraints.WEST;
currentScorePanel2.add(currentScorePanel, currentScorePanelGBC);
currentScoreLabel = new JLabel(" ");
currentScoreLabelGBC.gridx = 1;
currentScorePanel.add(currentScoreLabel, currentScoreLabelGBC);
//HIGHSCORE:
highScorePanel2 = new JPanel(new GridBagLayout());
highScorePanel2.setBackground(whiteBlue);
scorePanel.add(highScorePanel2, BorderLayout.SOUTH);
highScoreLabel2 = new JLabel("Highscore: ");
GridBagConstraints highScoreLabelGBC = new GridBagConstraints();
highScoreLabelGBC.gridx = 0;
highScoreLabelGBC.insets = new Insets(5, 5, 5, 5);
highScoreLabelGBC.anchor = GridBagConstraints.WEST;
highScorePanel2.add(highScoreLabel2, highScoreLabelGBC);
highScorePanel = new JPanel(new GridBagLayout());
highScorePanel.setBackground(Color.WHITE);
highScorePanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
GridBagConstraints highScorePanelGBC = new GridBagConstraints();
highScorePanelGBC.insets = new Insets(100, 0, 100, 100);
highScorePanelGBC.anchor = GridBagConstraints.WEST;
highScorePanel2.add(highScorePanel, highScorePanelGBC);
highScoreLabel = new JLabel(" ");
highScoreLabelGBC.gridx = 1;
highScorePanel.add(highScoreLabel, highScoreLabelGBC);
frame.pack();
frame.setVisible(true);
}
public class CreateMemoryGame implements ActionListener {
#Override
public void actionPerformed(ActionEvent ae) {
if (model.getDifficulty() != 0) {
counter = 0;
for (JRadioButton rb: difficultyButton) {
rb.setEnabled(false);
}
for (JButton b: button) {
b.setBackground(babyBlue);
b.setEnabled(false);
}
start.setEnabled(false);
arrayAuto = new int[model.getDifficulty()];
arrayAuto[0] = (int)(Math.random() * 16);
for (int x = 1; x < model.getDifficulty(); x++) {
arrayAuto[x] = (int)(Math.random() * 16);
while (arrayAuto[x] == arrayAuto[x - 1]) {
arrayAuto[x] = (int)(Math.random() * 16);
}
}
arrayUser = Arrays.copyOf(arrayAuto, arrayAuto.length);
button[arrayAuto[0]].setBackground(limeGreen);
timer.start();
} else {
Object[] options = {"OK"};
JOptionPane.showOptionDialog(null, "Please select a Difficulty.", "ERROR", JOptionPane.DEFAULT_OPTION,
JOptionPane.ERROR_MESSAGE,
null,
options,
options[0]);
}
}
}
public class TimerListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent ae) {
button[arrayAuto[0]].setBackground(babyBlue);
arrayAuto = Arrays.copyOfRange(arrayAuto, 1, arrayAuto.length);
if (arrayAuto.length == 0) {
timer.stop();
for (JButton b: button) {
b.setEnabled(true);
}
} else {
button[arrayAuto[0]].setBackground(limeGreen);
}
}
}
public class AttemptMemoryGame implements ActionListener {
#Override
public void actionPerformed(ActionEvent ae) {
if (Integer.parseInt(ae.getActionCommand()) == arrayUser[counter]) {
if (counter != 0) {
button[arrayUser[counter - 1]].setBackground(babyBlue);
}
button[arrayUser[counter]].setBackground(limeGreen);
counter++;
currentScore += model.getDifficulty();
currentScoreLabel.setText(" " + currentScore + " ");
} else {
if (currentScore > highScore) {
highScore = currentScore;
highScoreLabel.setText(" " + highScore + " ");
}
currentScore = 0;
currentScoreLabel.setText(" ");
for (int x = 0; x < model.getDifficulty(); x++) {
button[arrayUser[x]].setBackground(brightRed);
}
start.setEnabled(true);
for (JRadioButton rb: difficultyButton) {
rb.setEnabled(true);
}
for (JButton b: button) {
b.setEnabled(false);
}
}
if (counter == arrayUser.length) {
start.setEnabled(true);
for (int x = 0; x < counter - 1; x++) {
button[arrayUser[x]].setBackground(limeGreen);
}
for (JButton b: button) {
b.setEnabled(false);
}
for (JRadioButton rb: difficultyButton) {
rb.setEnabled(true);
}
}
}
}
public class SelectDifficulty implements ActionListener {
#Override
public void actionPerformed(ActionEvent ae) {
if (ae.getActionCommand().equals(0 + "")) {
model.setDifficulty(3);
} else if (ae.getActionCommand().equals(2 + "")) {
model.setDifficulty(7);
} else if (ae.getActionCommand().equals(3 + "")) {
model.setDifficulty(9);
} else {
model.setDifficulty(5);
}
}
}
public class ChangeColorsGUI implements ActionListener {
#Override
public void actionPerformed(ActionEvent ae) {
if (guiColorChanger.getSelectedItem() == guiColor[0]) {
guiColorChanger.setBackground(Color.WHITE);
settingsPanel.setBackground(whiteBlue);
gamePanel.setBackground(Color.WHITE);
scorePanel.setBackground(whiteBlue);
buttonPanel.setBackground(Color.WHITE);
guiColorChangerPanel.setBackground(whiteBlue);
buttonPanel2.setBackground(Color.WHITE);
guiColorChanger.setForeground(Color.BLACK);
guiColorChangerLabel.setForeground(Color.BLACK);
difficultyPanel.setBackground(Color.WHITE);
for (JRadioButton rb: difficultyButton) {
rb.setBackground(Color.WHITE);
rb.setForeground(Color.BLACK);
}
difficultyLabel.setBackground(whiteBlue);
difficultyLabel.setForeground(Color.BLACK);
difficultyPanel2.setBackground(whiteBlue);
guiColorChanger.setBorder(BorderFactory.createLineBorder(Color.BLACK));
difficultyPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
scorePanel.setBackground(whiteBlue);
currentScoreLabel.setBackground(Color.WHITE);
currentScoreLabel.setForeground(Color.BLACK);
currentScoreLabel2.setForeground(Color.BLACK);
currentScorePanel.setBackground(whiteBlue);
currentScorePanel2.setBackground(whiteBlue);
currentScorePanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
highScoreLabel.setBackground(Color.WHITE);
highScoreLabel.setForeground(Color.BLACK);
highScoreLabel2.setForeground(Color.BLACK);
highScorePanel.setBackground(whiteBlue);
highScorePanel2.setBackground(whiteBlue);
highScorePanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
} else {
guiColorChanger.setBackground(Color.BLACK);
settingsPanel.setBackground(blackBlue);
gamePanel.setBackground(Color.BLACK);
scorePanel.setBackground(blackBlue);
buttonPanel.setBackground(Color.BLACK);
guiColorChangerPanel.setBackground(blackBlue);
buttonPanel2.setBackground(Color.BLACK);
guiColorChanger.setForeground(Color.WHITE);
guiColorChangerLabel.setForeground(Color.WHITE);
difficultyPanel.setBackground(Color.BLACK);
for (JRadioButton rb: difficultyButton) {
rb.setBackground(Color.BLACK);
rb.setForeground(Color.WHITE);
}
difficultyLabel.setBackground(blackBlue);
difficultyLabel.setForeground(Color.WHITE);
difficultyPanel2.setBackground(blackBlue);
guiColorChanger.setBorder(BorderFactory.createLineBorder(Color.WHITE));
difficultyPanel.setBorder(BorderFactory.createLineBorder(Color.WHITE));
scorePanel.setBackground(blackBlue);
currentScoreLabel.setBackground(Color.BLACK);
currentScoreLabel.setForeground(Color.WHITE);
currentScoreLabel2.setForeground(Color.WHITE);
currentScorePanel.setBackground(blackBlue);
currentScorePanel2.setBackground(blackBlue);
currentScorePanel.setBorder(BorderFactory.createLineBorder(Color.WHITE));
highScoreLabel.setBackground(Color.BLACK);
highScoreLabel.setForeground(Color.WHITE);
highScoreLabel2.setForeground(Color.WHITE);
highScorePanel.setBackground(blackBlue);
highScorePanel2.setBackground(blackBlue);
highScorePanel.setBorder(BorderFactory.createLineBorder(Color.WHITE));
}
}
}
}
MemoryGameView becomes the controller, and it is as simple as:
public class MemoryGameView{
public MemoryGameView() {
Model model = new Model();
View view = new View(model);
}
public static void main(String[] args) {
new MemoryGameView();
}
}
Follow this link for a complete working prototype.
To continue: refactor more attributes (data and logic) from View to Model.
You may need to add listener so View can listen to changes in Model.
Side note: if indeed no Controller needed you can simply eliminate MemoryGameView and refactor its functionality to a main method:
public static void main(String[] args) {
Model model = new Model();
View view = new View(model);
}
but I wouldn't recommend it.
The following members might go into the model class:
difficulty
currentScore
highScore
arrayAuto
arrayUser
counter
Effectively the "pure" information.
The view should contain only ui code, i.e. Swing-Code. Since the game loop (timer) might be regarded as business code it would probably be a good idea to move it to the controller.
I did a quick google about swing and mvc: You might try to use existing frameworks like this for mvc.

Drawing with paintComponent in JScrollPanel

I'm actually stuck on something strange. I have a JFrame with a JScrollPane containing a jPanel far larger than the actual screen. I draw squares in colums and I want theses squares to go over the right border of the jPanel. (So that they will appear as you scroll to the right.) But the squares painted with the method paintComponents just stop at the visible ViewPort of the JScrollPane.
Here is my code for the JScrollPane inside of the JFrame:
public void initComponents(){
mainPanel = new DrawPanel(dim);
this.getContentPane().setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridheight = 1;
gbc.gridwidth = 1;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weighty = 1;
gbc.weightx = 1;
gbc.fill = GridBagConstraints.BOTH;
JScrollPane jsp = new JScrollPane(mainPanel, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
jsp.setLayout(new ScrollPaneLayout());
jsp.setViewportView(mainPanel);
jsp.getVerticalScrollBar().setUnitIncrement(20);
jsp.setBorder(BorderFactory.createEmptyBorder());
jsp.setPreferredSize(new Dimension(dim.width,dim.height -taskBarSize));
jsp.setMinimumSize(new Dimension(dim.width,dim.height -taskBarSize));
jsp.setMaximumSize(new Dimension(dim.width,dim.height -taskBarSize));
this.getContentPane().add(jsp, gbc);
this.getContentPane().revalidate();
this.getContentPane().repaint();
}
And here is my JPanel class :
public class DrawPanel extends JPanel {
private Dimension dim;
private Integer numberPanels = 7;
private Double startPointX;
private Double startPointY;
private Double heightRow;
private Double heightPanel;
public DrawPanel(Dimension d) {
this.dim = d;
//this.setBackground(Color.BLACK);
calculateStartPoint();
}
public void calculateStartPoint() {
startPointX = (dim.getWidth() / 10) * 1;
startPointY = (dim.getHeight() / 10) * 1;
heightRow = (dim.getHeight() * 0.8) / numberPanels;
heightPanel = heightRow - 10;
double colums = 366/numberPanels;
this.setPreferredSize(new Dimension((int)(heightRow *((int)colums + 1)), dim.height ));
this.setMinimumSize(new Dimension((int)(heightRow *((int)colums + 1)), dim.height ));
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.GRAY);
for (int i = 1; i <= 366; i++) {
// Si c'est le dernier d'une colonne
if (i%numberPanels == 0 && i != 0) {
g.fillRect(startPointX.intValue(), startPointY.intValue(), heightPanel.intValue(),
heightPanel.intValue());
startPointX = startPointX + heightRow;
startPointY = startPointY - ((numberPanels -1) * heightRow);
// Si c'est encore dans la meme colonne
} else {
g.fillRect(startPointX.intValue(), startPointY.intValue(), heightPanel.intValue(),
heightPanel.intValue());
startPointY = startPointY + heightRow;
}
}
}
}
At startup:
When I move the scrollPane:
Also, on resizing everything disapreas. Also I had to see that when scrolling back, the already painted squares disapeared, as if everything out of screen disppears.
Thanks for anybody who has some time for this.
Your problem is that you need to recalculate the starting points every time the painting is done. Else the variables keep increasing unnecessarily. So add two lines:
#Override
protected void paintComponent(Graphics g) { // should be protected
super.paintComponent(g);
// need to re-initialize variables within this
startPointX = (dim.getWidth() / 10) * 1;
startPointY = (dim.getHeight() / 10) * 1;
FYI, in the future, please post a MCVE with your question. For example, this is the MCVE that I made out of your code, code that now can be copied, pasted and run by anyone:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.*;
#SuppressWarnings("serial")
public class Foo02 extends JPanel {
private DrawPanel mainPanel;
private Dimension dim = new Dimension(200, 200);
public Foo02() {
initComponents();
}
public void initComponents() {
mainPanel = new DrawPanel(dim);
// !! this.getContentPane().setLayout(new GridBagLayout());
setLayout(new GridBagLayout()); // !!
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridheight = 1;
gbc.gridwidth = 1;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weighty = 1;
gbc.weightx = 1;
gbc.fill = GridBagConstraints.BOTH;
JScrollPane jsp = new JScrollPane(mainPanel, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
jsp.setLayout(new ScrollPaneLayout());
jsp.setViewportView(mainPanel);
jsp.getVerticalScrollBar().setUnitIncrement(20);
jsp.setBorder(BorderFactory.createEmptyBorder());
jsp.setPreferredSize(new Dimension(dim.width, dim.height));
jsp.setMinimumSize(new Dimension(dim.width, dim.height));
jsp.setMaximumSize(new Dimension(dim.width, dim.height));
add(jsp, gbc);
revalidate();
repaint();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
private static void createAndShowGui() {
Foo02 mainPanel = new Foo02();
JFrame frame = new JFrame("Foo02");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
}
#SuppressWarnings("serial")
class DrawPanel extends JPanel {
private Dimension dim;
private Integer numberPanels = 7;
private Double startPointX;
private Double startPointY;
private Double heightRow;
private Double heightPanel;
public DrawPanel(Dimension d) {
this.dim = d;
// this.setBackground(Color.BLACK);
calculateStartPoint();
}
public void calculateStartPoint() {
startPointX = (dim.getWidth() / 10) * 1;
startPointY = (dim.getHeight() / 10) * 1;
heightRow = (dim.getHeight() * 0.8) / numberPanels;
heightPanel = heightRow - 10;
double colums = 366 / numberPanels;
this.setPreferredSize(new Dimension((int) (heightRow * ((int) colums + 1)), dim.height));
this.setMinimumSize(new Dimension((int) (heightRow * ((int) colums + 1)), dim.height));
}
#Override
protected void paintComponent(Graphics g) { // should be protected
super.paintComponent(g);
// need to re-initialize variables within this
startPointX = (dim.getWidth() / 10) * 1;
startPointY = (dim.getHeight() / 10) * 1;
g.setColor(Color.GRAY);
for (int i = 1; i <= 366; i++) {
// Si c'est le dernier d'une colonne
if (i % numberPanels == 0 && i != 0) {
g.fillRect(startPointX.intValue(), startPointY.intValue(), heightPanel.intValue(),
heightPanel.intValue());
startPointX = startPointX + heightRow;
startPointY = startPointY - ((numberPanels - 1) * heightRow);
// Si c'est encore dans la meme colonne
} else {
g.fillRect(startPointX.intValue(), startPointY.intValue(), heightPanel.intValue(),
heightPanel.intValue());
startPointY = startPointY + heightRow;
}
}
}
}

EDIT: Having Trouble with Static Variables

I am writing a program that is supposed to take the input from two text fields, length and width. It is then supposed to calculate the cost based on the area and type of flooring selected. However, all of the static variables are not being used or updated by my program when I run it. Even when I click my Clear button, all of the fields will clear except ones that are declared static. Could someone please let me know what I'm doing wrong? If I try to remove the static, other classes aren't able to access it.
EDIT: I was able to remove the static declarations so that nothing in this class (Cost) is static. However, I have another class (OrderSummary) that needs to access the getFloorArea(), etc. methods from Cost. It also accesses methods getFirstName(), getLastName, etc. from another class (CustomerInfo). I did some reading and found out that I need to instantiate these classes so that OrderSummary can invoke these methods, I'm just confused as to where to instantiate these classes. In my Main? Or the class that I create the GUI in? I just need all of my information entered in the GUI to displayed in OrderSummary but I can't seem to figure out how to implement it.
I know I'm bad at this but I'm really trying to learn.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import helpers.*;
public class Cost extends JPanel {
static JRadioButton carpet;
static JRadioButton wood;
JButton btnClear;
JButton btnSubmit;
static JTextField enterLength;
static JTextField enterWidth;
JButton btnArea;
JButton btnCost;
JTextField txtArea;
JTextField txtCost;
JLabel length;
JLabel width;
static double woodCost = 20.00;
static double carpetCost = 10.00;
static double floorCost = 0.00;
static double floorLength = 0.00;
static double floorWidth = 0.00;
static double floorArea = 0.00;
static double totalCost = 0.00;
public Cost() {
createPanel();
}
private void createPanel() {
super.setLayout(new GridBagLayout());
GridBagConstraints bag = new GridBagConstraints();
bag.fill = GridBagConstraints.BOTH;
bag.anchor = GridBagConstraints.FIRST_LINE_START;
bag.insets = new Insets(5,5,5,5);
ButtonGroup bg = new ButtonGroup();
bag.gridx = 0;
bag.gridy = 0;
carpet = new JRadioButton("Carpet");
this.add(carpet, bag);
bg.add(carpet);
bag.gridx = 1;
bag.gridy = 0;
wood = new JRadioButton("Wood");
this.add(wood, bag);
bg.add(wood);
bag.gridx = 1;
bag.gridy = 1;
enterLength = new JTextField("0");
this.add(enterLength, bag);
bag.gridx = 0;
bag.gridy = 1;
length = new JLabel("Length");
length.setFont(new Font("Arial", Font.BOLD, 12));
length.setBackground(Color.BLUE);
this.add(length, bag);
bag.gridx = 3;
bag.gridy = 1;
btnArea = new JButton("Area");
btnArea.addActionListener(new AreaHandler());
this.add(btnArea, bag);
bag.gridx = 4;
bag.gridy = 1;
txtArea = new JTextField();
txtArea.setColumns(10);
this.add(txtArea, bag);
bag.gridx = 1;
bag.gridy = 2;
enterWidth = new JTextField("0");
this.add(enterWidth, bag);
bag.gridx = 0;
bag.gridy = 2;
width = new JLabel("Width");
this.add(width, bag);
bag.gridx = 3;
bag.gridy = 2;
btnCost = new JButton("Cost");
btnCost.addActionListener(new CostHandler());
this.add(btnCost, bag);
bag.gridx = 4;
bag.gridy = 2;
txtCost = new JTextField();
this.add(txtCost, bag);
bag.gridx = 4;
bag.gridy = 4;
btnSubmit = new JButton("Submit Order");
btnSubmit.addActionListener(new SubmitHandler());
this.add(btnSubmit, bag);
bag.gridx = 4;
bag.gridy = 5;
btnClear = new JButton("Clear");
btnClear.addActionListener(new ClearHandler());
this.add(btnClear, bag);
}
public static double getFlooringCost() {
if (carpet.isSelected())
floorCost = carpetCost;
if (wood.isSelected())
floorCost = woodCost;
return floorCost;
}
public static double getFloorArea() {
floorLength = Double.parseDouble(enterLength.getText());
floorWidth = Double.parseDouble(enterWidth.getText());
floorArea = floorLength * floorWidth;
return floorArea;
}
public static double getTotalCost() {
totalCost = floorCost * floorArea;
return totalCost;
}
public void setFloorArea(double floorArea) {
if (floorArea >= 0) {
Cost.floorArea = floorArea;
}
else {
JOptionPane.showMessageDialog(null, "Length or Width must be greater than 0.", "Error", JOptionPane.ERROR_MESSAGE);
}
}
public void setTotalCost(double totalCost) {
Cost.totalCost = totalCost;
}
private class AreaHandler implements ActionListener {
#Override
public void actionPerformed(ActionEvent arg0) {
txtArea.setText(String.valueOf(getFloorArea()));
}
}
private class CostHandler implements ActionListener {
#Override
public void actionPerformed(ActionEvent arg0) {
txtCost.setText(OutputHelpers.formattedCurrency(getTotalCost()));
}
}
private class ClearHandler implements ActionListener {
#Override
public void actionPerformed(ActionEvent arg0) {
enterLength.setText("");
enterWidth.setText("");
txtArea.setText("");
txtCost.setText("");
}
}
private class SubmitHandler implements ActionListener {
#Override
public void actionPerformed(ActionEvent arg0) {
setFloorArea(getFloorArea());
setTotalCost(getTotalCost());
enterLength.setText("");
enterWidth.setText("");
txtArea.setText("");
txtCost.setText("");
}
}
//class OrderSummary
import javax.swing.*;
import java.awt.*;
import helpers.*;
public class OrderSummary extends JPanel {
JTextArea orderSummary;
public OrderSummary() {
createPanel();
}
private void createPanel() {
super.setLayout(new GridBagLayout());
GridBagConstraints bag = new GridBagConstraints();
bag.fill = GridBagConstraints.BOTH;
bag.anchor = GridBagConstraints.FIRST_LINE_START;
bag.insets = new Insets(5,5,5,5);
bag.gridx = 0;
bag.gridy = 0;
orderSummary = new JTextArea(5, 20);
orderSummary.setFont(new Font("Arial", Font.BOLD, 12));
orderSummary.setBackground(Color.WHITE);
this.add(orderSummary, bag);
//this is where I need to get data from classes Cost and CustomerInfo
orderSummary.setText("Customer Name: " + aCustomerInfo.getFirstName() + " " + aCustomerInfo.getLastName() +
"\nAddress: " + aCustomerInfo.getStreet() + "\n" + aCustomerInfo.getCity() + "\n" + aCustomerInfo.getState() + "\n" + aCustomerInfo.getZip() +
"\n\nTotal Area: " + aCost.getFloorArea() + " square feet" +
"\nCost: " + OutputHelpers.formattedCurrency(aCost.getTotalCost()));
}
}

Show BarChar In JTable Column In Java

I have JTable in that I need to Show Chart but i have tired several Code but not able to achieve waht i wanted to make. here what i have tried so far
http://www.jroller.com/Thierry/entry/swing_barchart_rendering_in_a
and i want to achieve according to this image
but how ever i dont get any Render-er for same.
Please Any suggestion will be welcomed.
I would try 3 columns table. For the middle column I would use a custom renderer - a JPanel with JLabels on it. The labels could have different columns and sizes.
The TableModel should keep datasource for the bars and preparing renderer component means reading the cell value, extracting barchar data from the cell and setting colors/sizes for the JLabels in the JPanel (renderer component)
Okay, here's an idea...
Instead of using a JTable, you could create a layout manager which would calculate the offsets and allow for elements to overlap "columns"
Prototype example - !! DO NOT USE IN PRODUCTION !!
This is an EXAMPLE only and should be used to LEARN from, do not try using this in production, there is a lot that needs to improved, such as a proper event notification API
This example makes use of the JIDE Common Layer API (the JideScrollPane in particular), you can get a copy from here
import com.jidesoft.swing.JideScrollPane;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.LayoutManager2;
import java.awt.LinearGradientPaint;
import java.awt.Point;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JViewport;
import javax.swing.ScrollPaneConstants;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import javax.swing.border.MatteBorder;
public class WorkSheetReport {
public static final Color WORKING_HOURS_COLOR = new Color(93, 89, 88);
public static final Color LUNCH_HOURS_COLOR = new Color(215, 142, 27);
public static final Color OTHER_HOURS_COLOR = new Color(30, 141, 213);
public static void main(String[] args) {
new WorkSheetReport();
}
public WorkSheetReport() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
DefaultTimeSheetReport report = new DefaultTimeSheetReport();
report.add(createTimeSheet(
"NWD/Full"));
report.add(createTimeSheet(
"Present",
new DefaultTimeEntry(WorkType.WORK, 10, 12.5),
new DefaultTimeEntry(WorkType.LUNCH, 12.5, 13.25),
new DefaultTimeEntry(WorkType.WORK, 13.25, 18),
new DefaultTimeEntry(WorkType.OTHER, 18, 18.5),
new DefaultTimeEntry(WorkType.WORK, 18.5, 20.5)));
report.add(createTimeSheet(
"0.5UUPL",
new DefaultTimeEntry(WorkType.WORK, 10, 12.5),
new DefaultTimeEntry(WorkType.LUNCH, 12.5, 17.75),
new DefaultTimeEntry(WorkType.OTHER, 17.75, 18),
new DefaultTimeEntry(WorkType.WORK, 18, 20)));
report.add(createTimeSheet(
"Present",
new DefaultTimeEntry(WorkType.WORK, 11, 13),
new DefaultTimeEntry(WorkType.LUNCH, 13, 13.5),
new DefaultTimeEntry(WorkType.WORK, 13.5, 17.75),
new DefaultTimeEntry(WorkType.OTHER, 17.75, 18),
new DefaultTimeEntry(WorkType.WORK, 18, 20.5)));
report.add(createTimeSheet(
"Present",
new DefaultTimeEntry(WorkType.WORK, 10, 12.75),
new DefaultTimeEntry(WorkType.LUNCH, 12.75, 13.5),
new DefaultTimeEntry(WorkType.WORK, 13.5, 17.5),
new DefaultTimeEntry(WorkType.OTHER, 17.5, 17.75),
new DefaultTimeEntry(WorkType.WORK, 17.75, 20.5)));
report.add(createTimeSheet(
"Present",
new DefaultTimeEntry(WorkType.WORK, 9.75, 12),
new DefaultTimeEntry(WorkType.LUNCH, 12, 12.5),
new DefaultTimeEntry(WorkType.WORK, 12.5, 17.25),
new DefaultTimeEntry(WorkType.OTHER, 17.25, 17.75),
new DefaultTimeEntry(WorkType.WORK, 17.75, 20)));
report.add(createTimeSheet(
"Present",
new DefaultTimeEntry(WorkType.WORK, 10, 11.75),
new DefaultTimeEntry(WorkType.LUNCH, 11.75, 12.25),
new DefaultTimeEntry(WorkType.WORK, 12.25, 17.5),
new DefaultTimeEntry(WorkType.OTHER, 17.5, 18),
new DefaultTimeEntry(WorkType.WORK, 18, 20.25)));
report.add(createTimeSheet(
"NWD/Full"));
report.add(createTimeSheet(
"Present",
new DefaultTimeEntry(WorkType.WORK, 10, 12.5),
new DefaultTimeEntry(WorkType.LUNCH, 12.5, 13.5),
new DefaultTimeEntry(WorkType.WORK, 13.5, 18),
new DefaultTimeEntry(WorkType.OTHER, 18, 18.5),
new DefaultTimeEntry(WorkType.WORK, 18.5, 20.5)));
TimeSheetReportPane pane = new TimeSheetReportPane(report);
JFrame frame = new JFrame("Testing");
frame.getContentPane().setBackground(Color.BLACK);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JideScrollPane sp = new JideScrollPane(pane);
sp.setColumnHeadersHeightUnified(true);
frame.add(sp);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
protected TimeSheet createTimeSheet(String name, TimeEntry... entries) {
DefaultTimeSheet ts = new DefaultTimeSheet(name);
for (TimeEntry entry : entries) {
ts.add(entry);
}
return ts;
}
protected static String format(double time) {
time *= 60 * 60; // to seconds
int hours = (int) Math.floor(time / (60 * 60));
double remainder = time % (60 * 60);
int mins = (int) Math.floor(remainder / 60);
int secs = (int) Math.floor(time % 60);
return hours + ":" + mins + ":" + secs;
}
public class TimeSheetReportPane extends JPanel {
private TimeSheetReport report;
private int columnWidth;
private int rowHeight;
public TimeSheetReportPane(TimeSheetReport report) {
this.report = report;
setLayout(new GridBagLayout());
setBackground(Color.BLACK);
FontMetrics fm = getFontMetrics(UIManager.getFont("Label.font"));
columnWidth = fm.stringWidth("0000");
rowHeight = fm.getHeight() + 8;
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.weightx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(0, 0, 1, 0);
int count = 0;
for (TimeSheet ts : report) {
Color color = getColorForSheet(count);
TimeSheetPane pane = new TimeSheetPane(this, ts);
pane.setBackground(color);
add(pane, gbc);
count++;
}
gbc.weighty = 1;
JPanel fill = new JPanel();
fill.setOpaque(false);
add(fill, gbc);
}
public Color getColorForSheet(int index) {
Color endColor = Color.GRAY;
Color startColor = Color.DARK_GRAY;
double progress = (double) index / (double) getReport().size();
return blend(startColor, endColor, progress);
}
public TimeSheetReport getReport() {
return report;
}
public int getRowHeight() {
return rowHeight;
}
public int getColumnWidth() {
return columnWidth;
}
#Override
public void addNotify() {
super.addNotify();
configureEnclosingScrollPane();
}
protected void configureEnclosingScrollPane() {
Container parent = getParent();
if (parent instanceof JViewport) {
JViewport viewport = (JViewport) parent;
parent = viewport.getParent();
if (parent instanceof JideScrollPane) {
JideScrollPane sp = (JideScrollPane) parent;
sp.setRowFooterView(new RowFooter(this));
}
if (parent instanceof JScrollPane) {
JScrollPane sp = (JScrollPane) parent;
JLabel leftHeader = new JLabel("Status");
leftHeader.setForeground(Color.WHITE);
leftHeader.setBackground(Color.BLACK);
leftHeader.setOpaque(true);
leftHeader.setHorizontalAlignment(JLabel.CENTER);
leftHeader.setVerticalAlignment(JLabel.TOP);
leftHeader.setBorder(new EdgeBorder(EdgeBorder.Edge.RIGHT, Color.WHITE, Color.BLACK));
sp.setCorner(ScrollPaneConstants.UPPER_LEFT_CORNER, leftHeader);
JLabel rightHeader = new JLabel("Working Hr");
rightHeader.setForeground(Color.WHITE);
rightHeader.setBackground(Color.BLACK);
rightHeader.setOpaque(true);
rightHeader.setHorizontalAlignment(JLabel.CENTER);
rightHeader.setBorder(new EdgeBorder(EdgeBorder.Edge.LEFT, Color.WHITE, Color.BLACK));
sp.setCorner(ScrollPaneConstants.UPPER_RIGHT_CORNER, rightHeader);
sp.setRowHeaderView(new RowHeader(this));
sp.setColumnHeaderView(new ColumnHeader(this));
}
}
}
}
public class ColumnHeader extends JPanel {
private TimeSheetReportPane reportPane;
public ColumnHeader(TimeSheetReportPane tsrp) {
reportPane = tsrp;
setBackground(Color.BLACK);
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridheight = GridBagConstraints.REMAINDER;
gbc.weighty = 1;
gbc.fill = GridBagConstraints.VERTICAL;
gbc.ipady = 8;
Border border = new MatteBorder(0, 0, 0, 1, Color.GRAY);
for (int hour = 8; hour < 25; hour++) {
JLabel label = new JLabel(Integer.toString(hour)) {
#Override
public Dimension getPreferredSize() {
Dimension dim = super.getPreferredSize();
dim.width = reportPane.getColumnWidth();
return dim;
}
#Override
public Dimension getMinimumSize() {
return getPreferredSize();
}
};
label.setVerticalAlignment(JLabel.TOP);
label.setHorizontalAlignment(JLabel.CENTER);
label.setForeground(Color.WHITE);
label.setBorder(border);
add(label, gbc);
}
gbc.weightx = 1;
JPanel fill = new JPanel();
fill.setOpaque(false);
add(fill, gbc);
}
}
public class RowHeader extends JPanel {
private TimeSheetReportPane reportPane;
public RowHeader(TimeSheetReportPane tsrp) {
reportPane = tsrp;
setBackground(Color.BLACK);
setLayout(new GridBagLayout());
TimeSheetReport tsr = reportPane.getReport();
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.weightx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.ipadx = 16;
gbc.ipady = 2;
gbc.insets = new Insets(0, 0, 1, 0);
int index = 0;
for (TimeSheet ts : tsr) {
JLabel label = new JLabel(ts.getName()) {
#Override
public Dimension getPreferredSize() {
Dimension dim = super.getPreferredSize();
dim.height = reportPane.getRowHeight();
return dim;
}
#Override
public Dimension getMinimumSize() {
return getPreferredSize();
}
};
label.setHorizontalAlignment(JLabel.CENTER);
label.setForeground(Color.WHITE);
label.setBackground(reportPane.getColorForSheet(index));
label.setOpaque(true);
add(label, gbc);
index++;
}
gbc.weighty = 1;
JPanel fill = new JPanel();
fill.setOpaque(false);
add(fill, gbc);
}
}
public class RowFooter extends JPanel {
private TimeSheetReportPane reportPane;
public RowFooter(TimeSheetReportPane tsrp) {
reportPane = tsrp;
setBackground(Color.BLACK);
setLayout(new GridBagLayout());
TimeSheetReport tsr = reportPane.getReport();
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.weightx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.ipadx = 36;
gbc.ipady = 2;
gbc.insets = new Insets(0, 0, 1, 0);
int index = 0;
for (TimeSheet ts : tsr) {
double time = ts.getWorkingHours();
String workHrs = "";
if (time > 0) {
workHrs = format(time);
}
JLabel label = new JLabel(workHrs) {
#Override
public Dimension getPreferredSize() {
Dimension dim = super.getPreferredSize();
dim.height = reportPane.getRowHeight();
return dim;
}
#Override
public Dimension getMinimumSize() {
return getPreferredSize();
}
};
label.setHorizontalAlignment(JLabel.CENTER);
label.setForeground(Color.WHITE);
label.setBackground(reportPane.getColorForSheet(index));
label.setOpaque(true);
add(label, gbc);
index++;
}
gbc.weighty = 1;
JPanel fill = new JPanel();
fill.setOpaque(false);
add(fill, gbc);
}
}
public static class EdgeBorder implements Border {
public enum Edge {
LEFT,
RIGHT
}
private Edge edge;
private Color startColor;
private Color endColor;
public EdgeBorder(Edge edge, Color startColor, Color endColor) {
this.edge = edge;
this.startColor = startColor;
this.endColor = endColor;
}
#Override
public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
int xPos = x;
switch (edge) {
case RIGHT:
xPos = x + (width - 1);
}
LinearGradientPaint lgp = new LinearGradientPaint(
new Point(x, 0),
new Point(x, height),
new float[]{0, 1},
new Color[]{startColor, endColor});
Graphics2D g2d = (Graphics2D) g;
g2d.setPaint(lgp);
g2d.drawLine(xPos, y, xPos, y + height);
}
#Override
public Insets getBorderInsets(Component c) {
int left = edge == Edge.LEFT ? 1 : 0;
int right = edge == Edge.RIGHT ? 1 : 0;
return new Insets(0, left, 0, right);
}
#Override
public boolean isBorderOpaque() {
return false;
}
}
/**
* Blend two colors.
*
* #param color1 First color to blend.
* #param color2 Second color to blend.
* #param ratio Blend ratio. 0.5 will give even blend, 1.0 will return color1,
* 0.0 will return color2 and so on.
* #return Blended color.
*/
public static Color blend(Color color1, Color color2, double ratio) {
float r = (float) ratio;
float ir = (float) 1.0 - r;
float rgb1[] = new float[3];
float rgb2[] = new float[3];
color1.getColorComponents(rgb1);
color2.getColorComponents(rgb2);
float red = rgb1[0] * r + rgb2[0] * ir;
float green = rgb1[1] * r + rgb2[1] * ir;
float blue = rgb1[2] * r + rgb2[2] * ir;
if (red < 0) {
red = 0;
} else if (red > 255) {
red = 255;
}
if (green < 0) {
green = 0;
} else if (green > 255) {
green = 255;
}
if (blue < 0) {
blue = 0;
} else if (blue > 255) {
blue = 255;
}
Color color = null;
try {
color = new Color(red, green, blue);
} catch (IllegalArgumentException exp) {
exp.printStackTrace();
}
return color;
}
public class TimeSheetPane extends JPanel {
private final JPanel timeEntriesPane;
public TimeSheetPane(TimeSheetReportPane reportPane, TimeSheet ts) {
timeEntriesPane = new JPanel(new TimeSheetLayoutManager(reportPane.getColumnWidth(), reportPane.getRowHeight()));
timeEntriesPane.setBackground(Color.BLACK);
setBorder(new EmptyBorder(1, 0, 1, 0));
setLayout(new BorderLayout());
add(timeEntriesPane);
for (TimeEntry te : ts) {
JLabel label = createLabel(te.getType().getColor());
String startTime = format(te.getStartTime());
String duration = format(te.getDuration());
label.setToolTipText("<html>StartTime: " + startTime + "<br>Duration: " + duration);
timeEntriesPane.add(label, te);
}
}
protected JLabel createLabel(Color color) {
JLabel label = new JLabel();
label.setOpaque(true);
label.setBackground(color);
return label;
}
}
public class TimeSheetLayoutManager implements LayoutManager2 {
private Map<Component, TimeEntry> mapConstraints;
private int colWidth;
private int rowHeight;
public TimeSheetLayoutManager(int colWidth, int rowHeight) {
mapConstraints = new HashMap<>(25);
this.colWidth = colWidth;
this.rowHeight = rowHeight;
}
#Override
public void addLayoutComponent(Component comp, Object constraints) {
if (constraints instanceof TimeEntry) {
mapConstraints.put(comp, (TimeEntry) constraints);
} else {
throw new IllegalArgumentException(
constraints == null ? "Null is not a valid constraint"
: constraints.getClass().getName() + " is not a valid TimeEntry constraint"
);
}
}
#Override
public Dimension maximumLayoutSize(Container target) {
return preferredLayoutSize(target);
}
#Override
public float getLayoutAlignmentX(Container target) {
return 0.5f;
}
#Override
public float getLayoutAlignmentY(Container target) {
return 0.5f;
}
#Override
public void invalidateLayout(Container target) {
}
#Override
public void addLayoutComponent(String name, Component comp) {
throw new UnsupportedOperationException("Not supported yet.");
}
#Override
public void removeLayoutComponent(Component comp) {
mapConstraints.remove(comp);
}
#Override
public Dimension preferredLayoutSize(Container parent) {
return new Dimension(colWidth * (24 - 8), rowHeight);
}
#Override
public Dimension minimumLayoutSize(Container parent) {
return preferredLayoutSize(parent);
}
#Override
public void layoutContainer(Container parent) {
Insets insets = parent.getInsets();
int width = parent.getWidth() - (insets.left + insets.right);
int height = rowHeight;
int hourWidth = colWidth;
int offset = 8;
for (Component comp : mapConstraints.keySet()) {
TimeEntry te = mapConstraints.get(comp);
double startTime = te.getStartTime();
double duration = te.getDuration();
startTime -= offset;
int x = (int) Math.round(startTime * hourWidth);
int unitWidth = (int) Math.round(duration * hourWidth);
comp.setLocation(x, insets.top);
comp.setSize(unitWidth, height);
}
}
}
public enum WorkType {
WORK(WORKING_HOURS_COLOR),
LUNCH(LUNCH_HOURS_COLOR),
OTHER(OTHER_HOURS_COLOR);
private Color color;
private WorkType(Color color) {
this.color = color;
}
public Color getColor() {
return color;
}
}
public interface TimeEntry {
public WorkType getType();
public double getStartTime();
public double getDuration();
}
public interface TimeSheet extends Iterable<TimeEntry> {
public String getName();
public int size();
public TimeEntry get(int index);
public double getWorkingHours();
}
public interface TimeSheetReport extends Iterable<TimeSheet> {
public int size();
public TimeSheet get(int index);
}
public class DefaultTimeEntry implements TimeEntry {
private final double startTime;
private final double endTime;
private final WorkType workType;
public DefaultTimeEntry(WorkType type, double startTime, double endTime) {
this.startTime = startTime;
this.endTime = endTime;
this.workType = type;
}
#Override
public double getStartTime() {
return startTime;
}
public double getEndTime() {
return endTime;
}
#Override
public double getDuration() {
return endTime - startTime;
}
#Override
public WorkType getType() {
return workType;
}
}
public class DefaultTimeSheet implements TimeSheet {
private final List<TimeEntry> timeEntries;
private final String name;
public DefaultTimeSheet(String name) {
this.name = name;
timeEntries = new ArrayList<>(25);
}
public TimeSheet add(TimeEntry te) {
timeEntries.add(te);
return this;
}
#Override
public Iterator<TimeEntry> iterator() {
return timeEntries.iterator();
}
#Override
public int size() {
return timeEntries.size();
}
#Override
public TimeEntry get(int index) {
return timeEntries.get(index);
}
#Override
public String getName() {
return name;
}
#Override
public double getWorkingHours() {
double time = 0;
for (TimeEntry te : this) {
switch (te.getType()) {
case WORK:
time += te.getDuration();
break;
}
}
return time;
}
}
public class DefaultTimeSheetReport implements TimeSheetReport {
private final List<TimeSheet> timeSheets;
public DefaultTimeSheetReport() {
timeSheets = new ArrayList<>(25);
}
public DefaultTimeSheetReport add(TimeSheet ts) {
timeSheets.add(ts);
return this;
}
#Override
public int size() {
return timeSheets.size();
}
#Override
public TimeSheet get(int index) {
return timeSheets.get(index);
}
#Override
public Iterator<TimeSheet> iterator() {
return timeSheets.iterator();
}
}
}

Remove the gap between components in gridBagLayout

This is my class:
public class Main extends JFrame{
private Container container;
private GridBagConstraints cons;
private JPanel panelDisplay;
private int curX = 0, curY = 0;
public Main() {
initComp();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
Main ex = new Main();
ex.setVisible(true);
}
});
}
private void initComp()
{
container = this.getContentPane();
container.setLayout(new GridBagLayout());
cons = new GridBagConstraints();
cons.gridx = 0;
cons.gridy = 0;
container.add(new PanelNot(), cons);
panelDisplay = new JPanel();
panelDisplay.setBackground(Color.blue);
panelDisplay.setPreferredSize(new Dimension(600, 400));
panelDisplay.setLayout(new GridBagLayout());
cons.gridx = 1;
cons.gridy = 0;
container.add(panelDisplay, cons);
for (int i = 0; i < 15; i++) // display 15 components
{
displayNot();
}
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //setting the default close operation of JFrame
this.pack();
this.setResizable(false);
this.setLocationRelativeTo(null);
this.setVisible(true);
}
private void displayNot()
{
setLocGrid();
panelDisplay.add(new Not1(), cons);
}
private void setLocGrid()
{
if(curX==11) // maximum component to be display in 1 row is 11
{
curY += 1;
curX = 0;
}
cons.gridx = curX;
cons.gridy = curY;
cons.anchor = GridBagConstraints.FIRST_LINE_START;
cons.weightx = 1.0;
cons.weighty = 1.0;
curX += 1;
}
}
this is the output:
Just ignore the left panel. My problem is in the right panel which is, there is a gap between one component (component: Not1) to the other. i have set the preferedSize of each component to x=20 and y=30 as you can see in every component's background where the color is gray. So my question is, how to make the gap disappear?
UPDATE : my expectation:
Start by getting rid of cons.weightx and cons.weightx
private void setLocGrid() {
if (curX == 11) // maximum component to be display in 1 row is 11
{
curY += 1;
curX = 0;
}
cons.gridx = curX;
cons.gridy = curY;
cons.anchor = GridBagConstraints.FIRST_LINE_START;
//cons.weightx = 1.0;
//cons.weighty = 1.0;
curX += 1;
}
This will get you something like...
Now, you need some kind of filler that can push the components to the top/left position, for example...
for (int i = 0; i < 15; i++) // display 15 components
{
displayNot();
}
cons.gridy++;
cons.gridx = 12; // Based on you conditions in setLocGrid
cons.weightx = 1;
cons.weighty = 1;
JPanel filler = new JPanel();
filler.setOpaque(false);
panelDisplay.add(filler, cons);
Which will give you something like...

Categories

Resources