我正在尝试创建像GUI这样的网格(5 * 5)大小。我尝试并制作了一个非常基本的网格,它工作得非常好,但我试图在用户点击并放下它时更改每个JPanel的背景颜色。但我还没有意识到Java中的GUI。所以想知道是否有人可以帮助我。
这是我的网格代码并匹配两个文件(情感词分析)
public static TwitterSystem getObject()
{
if (Object==null)
Object = new TwitterSystem();
return Object;
}
long startTime = System.currentTimeMillis();
long endTime = System.currentTimeMillis();
long totalTime = endTime - startTime;
//read jason from file into String
//create a lot of tweet objects
//run the tweetSystem
public void Run()
{
double r;
for (int i = 0; i < 5; i++)
for (int j = 0; j < 5; j++)
DataGrid[i][j] = 0.0;
// trying to load the wordlist and tweets
try
{
WordList = new Sentiment_Analysis("E:\\JAVA\\src\\wordlist.txt");
Tweet = new Tweet_Reader("E:\\JAVA\\tweets.json");
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
tweets = Tweet.getTweets();
// for each tweet, we getting the rating and working out where it is in the grid.
for(Tweet t : tweets) {
r = WordList.getRating(t);
if((int)t.getCoordinate().getLatitude() == 24 && (int)t.getCoordinate().getLongitude() == 54 ) {
DataGrid[2][2] += r;
}
if((int)t.getCoordinate().getLatitude() == 25 && (int)t.getCoordinate().getLongitude() == 54 ) {
DataGrid[0][1] += r;
}
}
// printing out the score for each square.
for (int i = 0; i < 5; i ++)
for (int j = 0; j < 5; j++)
System.out.format("[%4d][%4d] = %.4f\n", i, j, DataGrid[i][j]);
System.out.println("Finish calculating");
System.out.println("STATS - TIME: Analysis took "
+ TimeUnit.SECONDS.convert(totalTime, TimeUnit.MILLISECONDS)
+ " seconds");
}
}
提前谢谢!我是编程
的新手到目前为止网格工作但我想在GUI中制作网格
HELP PLEASE !!!!
答案 0 :(得分:1)
从这个完整的example开始,我为网格中的每个ButtonPanel
添加了ActionListener
。监听器更新封闭面板的背景颜色。请注意,每个按钮都使用自己的同一匿名类的实例。注释掉计时器的start()
调用以更好地查看效果。作为练习,请尝试将班级ButtonPanel
更改为工厂方法,例如createButtonPanel()
,createGridPanel()
显示为here。
private static class ButtonPanel extends JPanel {
public ButtonPanel(int i) {
this.setBackground(new Color(rnd.nextInt()));
JButton b = new JButton("Button " + String.valueOf(i));
b.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JButton b = (JButton) e.getSource();
ButtonPanel.this.setBackground(new Color(rnd.nextInt()));
}
});
this.add(b);
}
}